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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4,740 | 133266_1 | package com.wyona.katie.answers;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* Add to a Katie domain a QnA with an answer containing <p><ak-exec>com.wyona.askkatie.answers.OpenERZ#getCalendarPaper(ak-entity:number,'de')</ak-exec></p> or <p><ak-exec>com.wyona.askkatie.answers.OpenERZ#getCalendarCardboard(ak-entity:number,'de')</ak-exec></p>
* IMPORTANT: Make sure that NER can recognize numbers, like for example set <ner impl="MOCK"/> inside domain configuration
*/
@Slf4j
public class OpenERZ {
private String baseUrl = "https://openerz.metaodi.ch";
/**
*
*/
public OpenERZ() {
}
/**
* @param zip ZIP code, e.g. "8044"
* @param language Language of answer, e.g. "de" or "en"
*/
public String getCalendarPaper(String zip, String language) {
if (zip == null) {
return "Um die Frage beantworten zu können wird eine gültige Postleitzahl benötigt. Bitte probieren Sie es nochmals, z.B. stellen Sie die Frage 'Nächste Papiersammlung 8032?'";
}
List<Date> dates = getDates(zip, "paper");
Locale locale = new Locale(language);
java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("dd. MMMM yyyy", locale);
StringBuilder answer = new StringBuilder();
if (dates.size() > 0) {
//answer.append("<p>Die Abholtermine für Papier an der TODO:Strasse in Zürich (Postleitzahl " + zip + ") sind wie folgt:</p>");
answer.append("<p>Die Abholtermine für Papier in " + zip + " Zürich sind wie folgt:</p>");
answer.append("<ul>");
for (Date date : dates) {
answer.append("<li>" + dateFormat.format(date) + "</li>"); // INFO: 14. Juli 2023
}
answer.append("</ul>");
} else {
answer.append("<p>Leider konnten keine Abholtermine für Papier in " + zip + " Zürich gefunden werden.</p>");
}
return answer.toString();
}
/**
* @param zip ZIP code, e.g. "8044"
* @param language Language of answer, e.g. "de" or "en"
*/
public String getCalendarCardboard(String zip, String language) {
if (zip == null) {
return "Um die Frage beantworten zu können wird eine gültige Postleitzahl benötigt. Bitte probieren Sie es nochmals, z.B. stellen Sie die Frage 'Nächste Kartonsammlung 8032?'";
}
List<Date> dates = getDates(zip, "cardboard");
Locale locale = new Locale(language);
java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("dd. MMMM yyyy", locale);
StringBuilder answer = new StringBuilder();
if (dates.size() > 0) {
//answer.append("<p>Die Abholtermine für Karton an der TODO:Strasse in Zürich (Postleitzahl " + zip + ") sind wie folgt:</p>");
answer.append("<p>Die Abholtermine für Karton in " + zip + " Zürich sind wie folgt:</p>");
answer.append("<ul>");
for (Date date : dates) {
answer.append("<li>" + dateFormat.format(date) + "</li>"); // INFO: 14. Juli 2023
}
answer.append("</ul>");
} else {
answer.append("<p>Leider konnten keine Abholtermine für Karton in " + zip + " Zürich gefunden werden.</p>");
}
return answer.toString();
}
/**
* @param zip ZIP code, e.g. "8044"
* @param type Waste type, e.g. "paper" or "cardboard"
*/
private List<Date> getDates(String zip, String type) {
List<Date> dates = new ArrayList<Date>();
java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd");
// INFO: See https://openerz.metaodi.ch/documentation
Date current = new Date();
String requestUrl = baseUrl + "/api/calendar.json?types=" + type + "&zip=" + zip + "&start=" + dateFormat.format(current) + "&sort=date&offset=0&limit=500";
log.info("Get dates from '" + requestUrl + "' ...");
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = getHttpHeaders();
headers.set("Accept", "application/json");
//headers.set("Content-Type", "application/json; charset=UTF-8");
HttpEntity<String> request = new HttpEntity<String>(headers);
try {
ResponseEntity<JsonNode> response = restTemplate.exchange(requestUrl, HttpMethod.GET, request, JsonNode.class);
JsonNode bodyNode = response.getBody();
log.info("Response JSON: " + bodyNode);
JsonNode resultNode = bodyNode.get("result");
if (resultNode.isArray()) {
for (int i = 0; i < resultNode.size(); i++) {
JsonNode dateNode = resultNode.get(i);
String dateAsString = dateNode.get("date").asText(); // INFO: 2023-07-04"
try {
dates.add(dateFormat.parse(dateAsString));
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
} else {
log.error("No dates received!");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return dates;
}
/**
*
*/
private HttpHeaders getHttpHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", "application/json");
//headers.set("Content-Type", "application/json; charset=UTF-8");
return headers;
}
}
| wyona/katie-backend | src/main/java/com/wyona/katie/answers/OpenERZ.java | 1,758 | /**
* @param zip ZIP code, e.g. "8044"
* @param language Language of answer, e.g. "de" or "en"
*/ | block_comment | nl | package com.wyona.katie.answers;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* Add to a Katie domain a QnA with an answer containing <p><ak-exec>com.wyona.askkatie.answers.OpenERZ#getCalendarPaper(ak-entity:number,'de')</ak-exec></p> or <p><ak-exec>com.wyona.askkatie.answers.OpenERZ#getCalendarCardboard(ak-entity:number,'de')</ak-exec></p>
* IMPORTANT: Make sure that NER can recognize numbers, like for example set <ner impl="MOCK"/> inside domain configuration
*/
@Slf4j
public class OpenERZ {
private String baseUrl = "https://openerz.metaodi.ch";
/**
*
*/
public OpenERZ() {
}
/**
* @param zip ZIP<SUF>*/
public String getCalendarPaper(String zip, String language) {
if (zip == null) {
return "Um die Frage beantworten zu können wird eine gültige Postleitzahl benötigt. Bitte probieren Sie es nochmals, z.B. stellen Sie die Frage 'Nächste Papiersammlung 8032?'";
}
List<Date> dates = getDates(zip, "paper");
Locale locale = new Locale(language);
java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("dd. MMMM yyyy", locale);
StringBuilder answer = new StringBuilder();
if (dates.size() > 0) {
//answer.append("<p>Die Abholtermine für Papier an der TODO:Strasse in Zürich (Postleitzahl " + zip + ") sind wie folgt:</p>");
answer.append("<p>Die Abholtermine für Papier in " + zip + " Zürich sind wie folgt:</p>");
answer.append("<ul>");
for (Date date : dates) {
answer.append("<li>" + dateFormat.format(date) + "</li>"); // INFO: 14. Juli 2023
}
answer.append("</ul>");
} else {
answer.append("<p>Leider konnten keine Abholtermine für Papier in " + zip + " Zürich gefunden werden.</p>");
}
return answer.toString();
}
/**
* @param zip ZIP code, e.g. "8044"
* @param language Language of answer, e.g. "de" or "en"
*/
public String getCalendarCardboard(String zip, String language) {
if (zip == null) {
return "Um die Frage beantworten zu können wird eine gültige Postleitzahl benötigt. Bitte probieren Sie es nochmals, z.B. stellen Sie die Frage 'Nächste Kartonsammlung 8032?'";
}
List<Date> dates = getDates(zip, "cardboard");
Locale locale = new Locale(language);
java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("dd. MMMM yyyy", locale);
StringBuilder answer = new StringBuilder();
if (dates.size() > 0) {
//answer.append("<p>Die Abholtermine für Karton an der TODO:Strasse in Zürich (Postleitzahl " + zip + ") sind wie folgt:</p>");
answer.append("<p>Die Abholtermine für Karton in " + zip + " Zürich sind wie folgt:</p>");
answer.append("<ul>");
for (Date date : dates) {
answer.append("<li>" + dateFormat.format(date) + "</li>"); // INFO: 14. Juli 2023
}
answer.append("</ul>");
} else {
answer.append("<p>Leider konnten keine Abholtermine für Karton in " + zip + " Zürich gefunden werden.</p>");
}
return answer.toString();
}
/**
* @param zip ZIP code, e.g. "8044"
* @param type Waste type, e.g. "paper" or "cardboard"
*/
private List<Date> getDates(String zip, String type) {
List<Date> dates = new ArrayList<Date>();
java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd");
// INFO: See https://openerz.metaodi.ch/documentation
Date current = new Date();
String requestUrl = baseUrl + "/api/calendar.json?types=" + type + "&zip=" + zip + "&start=" + dateFormat.format(current) + "&sort=date&offset=0&limit=500";
log.info("Get dates from '" + requestUrl + "' ...");
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = getHttpHeaders();
headers.set("Accept", "application/json");
//headers.set("Content-Type", "application/json; charset=UTF-8");
HttpEntity<String> request = new HttpEntity<String>(headers);
try {
ResponseEntity<JsonNode> response = restTemplate.exchange(requestUrl, HttpMethod.GET, request, JsonNode.class);
JsonNode bodyNode = response.getBody();
log.info("Response JSON: " + bodyNode);
JsonNode resultNode = bodyNode.get("result");
if (resultNode.isArray()) {
for (int i = 0; i < resultNode.size(); i++) {
JsonNode dateNode = resultNode.get(i);
String dateAsString = dateNode.get("date").asText(); // INFO: 2023-07-04"
try {
dates.add(dateFormat.parse(dateAsString));
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
} else {
log.error("No dates received!");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return dates;
}
/**
*
*/
private HttpHeaders getHttpHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", "application/json");
//headers.set("Content-Type", "application/json; charset=UTF-8");
return headers;
}
}
| False | 1,395 | 39 | 1,588 | 41 | 1,591 | 44 | 1,587 | 41 | 1,775 | 45 | false | false | false | false | false | true |
17 | 18917_0 | package be.thomasmore.qrace.model;
// de mascottes zijn de verschillende characters binnen QRace
public class Mascot {
private String name;
private String description;
public Mascot(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
} | 22-project-programmeren-thomasmore/QRace | src/main/java/be/thomasmore/qrace/model/Mascot.java | 158 | // de mascottes zijn de verschillende characters binnen QRace | line_comment | nl | package be.thomasmore.qrace.model;
// de mascottes<SUF>
public class Mascot {
private String name;
private String description;
public Mascot(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
} | True | 119 | 12 | 136 | 15 | 146 | 12 | 136 | 15 | 164 | 15 | false | false | false | false | false | true |
188 | 25618_1 | package Machiavelli.Controllers;
import Machiavelli.Interfaces.Remotes.BeurtRemote;
import Machiavelli.Interfaces.Remotes.SpelRemote;
import Machiavelli.Interfaces.Remotes.SpelerRemote;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
/**
*
* Deze klasse bestuurt het model van het spel.
*
*/
public class SpelController extends UnicastRemoteObject {
private SpelerRemote speler;
private SpelRemote spel;
private BeurtRemote beurt;
private GebouwKaartController gebouwKaartController;
private SpeelveldController speelveldController;
public SpelController(SpelRemote spel) throws RemoteException {
// super(1099);
try {
this.spel = spel;
this.speler = this.spel.getSpelers().get(this.spel.getSpelers().size() - 1);
this.beurt = this.spel.getBeurt();
this.gebouwKaartController = new GebouwKaartController(this.spel, this.speler);
// Start nieuwe SpeelveldController
new SpeelveldController(this.spel, speler, this.gebouwKaartController, this.beurt);
} catch (Exception re) {
re.printStackTrace();
}
}
public GebouwKaartController getGebouwKaartController() {
return this.gebouwKaartController;
}
public SpeelveldController getSpeelveldController()
{
return this.speelveldController;
}
}
| Badmuts/Machiavelli | src/Machiavelli/Controllers/SpelController.java | 443 | // Start nieuwe SpeelveldController | line_comment | nl | package Machiavelli.Controllers;
import Machiavelli.Interfaces.Remotes.BeurtRemote;
import Machiavelli.Interfaces.Remotes.SpelRemote;
import Machiavelli.Interfaces.Remotes.SpelerRemote;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
/**
*
* Deze klasse bestuurt het model van het spel.
*
*/
public class SpelController extends UnicastRemoteObject {
private SpelerRemote speler;
private SpelRemote spel;
private BeurtRemote beurt;
private GebouwKaartController gebouwKaartController;
private SpeelveldController speelveldController;
public SpelController(SpelRemote spel) throws RemoteException {
// super(1099);
try {
this.spel = spel;
this.speler = this.spel.getSpelers().get(this.spel.getSpelers().size() - 1);
this.beurt = this.spel.getBeurt();
this.gebouwKaartController = new GebouwKaartController(this.spel, this.speler);
// Start nieuwe<SUF>
new SpeelveldController(this.spel, speler, this.gebouwKaartController, this.beurt);
} catch (Exception re) {
re.printStackTrace();
}
}
public GebouwKaartController getGebouwKaartController() {
return this.gebouwKaartController;
}
public SpeelveldController getSpeelveldController()
{
return this.speelveldController;
}
}
| True | 347 | 8 | 405 | 10 | 371 | 7 | 409 | 10 | 437 | 8 | false | false | false | false | false | true |
1,034 | 11151_1 | import java.lang. *;
/**
* Deze klasse is een java programma
* @author Ruben Wouters
* @version 1,5
*/
public class EersteProg_4{
public static void main(String args[])
{
System.out.println(~10);
}
/* Verklaar het resultaat:
~ duidt op een NOT operator. Deze operator inverteert elke bit van het getal.
Om in 2's complement van 10 naar -10 te gaan, kan je alle bits inverteren en dan +1
Maar de +1 doe je niet hier, dus je komt op -11 uit
*/
} | MTA-Digital-Broadcast-2/Q-Van-Schevensteen-Dries-Wouters-Ruben-Project-MHP | Ruben Wouters/blz17/EersteProg.java | 169 | /* Verklaar het resultaat:
~ duidt op een NOT operator. Deze operator inverteert elke bit van het getal.
Om in 2's complement van 10 naar -10 te gaan, kan je alle bits inverteren en dan +1
Maar de +1 doe je niet hier, dus je komt op -11 uit
*/ | block_comment | nl | import java.lang. *;
/**
* Deze klasse is een java programma
* @author Ruben Wouters
* @version 1,5
*/
public class EersteProg_4{
public static void main(String args[])
{
System.out.println(~10);
}
/* Verklaar het resultaat:<SUF>*/
} | True | 148 | 83 | 175 | 92 | 157 | 80 | 175 | 92 | 180 | 92 | false | false | false | false | false | true |
313 | 8080_3 | /*
* Copyright (c) 2016.
*
* This file is part of Project AGI. <http://agi.io>
*
* Project AGI 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.
*
* Project AGI 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 Project AGI. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package io.agi.core.sdr;
import io.agi.core.data.Data;
import io.agi.core.data.Data2d;
import io.agi.core.orm.AbstractPair;
import java.awt.*;
/**
* Encodes to binary matrix by encoding values as subsets of bits.
* <p/>
* The properties of SDRs are that similar input should have similar bits.
* So there must be some redundancy - you can't have one bit per feature.
* <p/>
* This encoder assumes that each scalar input is represented as an array
* of bits.
* <p/>
* This is an adaptation of the Nupic ScalarEncoder
* https://github.com/numenta/nupic/wiki/Encoders
*
* @author dave
*/
public class ScalarEncoder implements SparseDistributedEncoder {
public boolean _encodeZero = false;
public int _bits = 0;
public int _density = 0;
public ScalarEncoder() {
}
public void setup( int bits, int density, boolean encodeZero ) {
_bits = bits;
_density = density;
_encodeZero = encodeZero;
}
public int getBins() {
// density = 2 bits = 4
// 1100 0110 0011 = 3 bins = 4-2 +1
// density = 2 bits = 5
// 11000 01100 00110 00011 = 4 bins = 5-2 +1
// density = 3 bits = 5
// 11100 01110 00111 = 3 bins = 5-3 +1 = 3
// density = 3 bits = 8
// 1110 0000
// 0111 0000
// 0011 1000
// 0001 1100
// 0000 1110
// 0000 0111 = 6 bins = 8-3 +1 = 6
return _bits - _density + 1;
}
@Override
public Data createEncodingOutput( Data encodingInput ) {
int inputs = encodingInput.getSize();
// Force the dimensions into a 2d (rectangular) shape.
// Increase width to cope with extra bits.
Point size = Data2d.getSize( encodingInput );
// Dimensions.DIMENSION_X, outputs
int w = size.x * _bits;
int h = size.y;
Data encodingOutput = new Data( w, h );
return encodingOutput;
}
@Override
public Data createDecodingOutput( Data encodingInput, Data decodingInput ) {
int inputs = decodingInput.getSize();
// Assuming the same type of encoder did the encoding, we can reverse the geometric changes.
// However, we assume the input was 2d
Point size = Data2d.getSize( decodingInput );
// Dimensions.DIMENSION_X, outputs
int w = size.x / _bits;
int h = size.y;
Data decodingOutput = new Data( w, h );
return decodingOutput;
}
@Override
public void encode( Data encodingInput, Data encodingOutput ) {
int inputs = encodingInput.getSize();
int bins = getBins();
for( int i = 0; i < inputs; ++i ) {
float inputValue = encodingInput._values[ i ];
int offset = i * _bits;
if( ( !_encodeZero ) && ( inputValue == 0.f ) ) {
for( int b = 0; b < _bits; ++b ) {
encodingOutput._values[ offset + b ] = 0.f;
}
continue;
}
// density = 2 bits = 5
// possible patterns are:
// 11000
// 01100
// 00110
// 00011 = 4 possible bins = 5-2 +1 = 4
//
// density = 3 bits = 8
// 1110 0000
// 0111 0000
// 0011 1000
// 0001 1100
// 0000 1110
// 0000 0111 = 6 bins = 8-3 +1 = 6
// 0 0.25 0.5 0.75
// 0 * 4 = [0,2)
// 0.24 * 4 = [0,2)
// 0.25 * 4 = [1,3)
// 0.49 * 4 = [1,3)
// 0.5 * 4 = [2,4)
// 0.75 * 4 = [3,5)
// 0.99 * 4 = [3,5)
// 1 * 4 = [4,5) <-- bad, so limit it
float bin = inputValue * ( float ) bins;
int bin1 = Math.min( bins-1, (int)bin ); // captured case where value is 1.
int bin2 = bin1 + _density; // excluding this value
for( int b = 0; b < _bits; ++b ) {
float bitValue = 0.f;
if( ( b < bin2 ) && ( b >= bin1 ) ) {
bitValue = 1.f;
}
encodingOutput._values[ offset + b ] = bitValue;
}
}
}
@Override
public void decode( Data decodingInput, Data decodingOutput ) {
// computes the decode by taking the mean position of the encoded '1' bits.
// e.g.
// density = 2 bits = 5
// 11000 01100 00110 00011 = 4 bins = 5-2 +1
//
//Example: A scalar encoder with a range from 0 to 100 with n=12 and w=3 will
//produce the following encoders:
//
//1 becomes 111000000000
//7 becomes 111000000000
//15 becomes 011100000000
//36 becomes 000111000000
int inputs = decodingInput.getSize();
int outputs = inputs / _bits;
int bins = getBins();
float reciprocalBits = 1.f / (float)_bits;
float denominatorBits = (float)( Math.max( 1, _bits -1 ) );
for( int i = 0; i < outputs; ++i ) {
float output = 0.f;
if( _bits == 1 ) {
float bitValue = decodingInput._values[ i ];
if( bitValue > 0.f ) {
output = 1.f;
}
}
else {
int offset = i * _bits;
float sum = 0.f;
float count = 0.f;
for( int b = 0; b < _bits; ++b ) {
float bitValue = decodingInput._values[ offset + b ];
if( bitValue < 1.f ) {
continue;
}
// density = 1 bits = 1
// possible patterns are: bit / (bits-1)
// 0 00000 0/1 = 0
// 1 = 1 possible bins 00001 1/1 = 1
//
// density = 2 bits = 5
// possible patterns are: bit / (bits-1)
// 11000 10000 0/4 = 0.0
// 01100 01000 1/4 = 0.25
// 00110 00100 2/4 = 0.5
// 00011 = 4 possible bins = 5-2 +1 = 4 00010 3/4 = 0.75
// 00001 4/4 = 1.0
// density = 3 bits = 8
// 1110 0000 0/7 = 0.0
// 0111 0000 1/7 = 0.14
// 0011 1000 2/7 = 0.28
// 0001 1100 3/7 = 0.42
// 0000 1110 4/7 = 0.57
// 0000 0111 = 6 bins = 8-3 +1 = 6 5/7 = 0.71
// 6/7 = 0.85
// 7/7 = 1.0
float bitWeight = ( float ) b / denominatorBits; // so between zero and 1 inclusive
sum += bitWeight;
count += 1.f;
}
// e.g. 11000 = 0.0 + 0.25 / 2 = 0.125
// e.g. 00011 = 0.75 + 1.0 / 2 = 0.875
// e.g. 1110 0000 = 0.0 + 0.14 + 0.28 / 3 = 0.14 0.14 would've been encoded as 0.14*(6) = 0.84 = bin 0,1,2
float meanBit = 0.f;
if( count > 0.f ) {
meanBit = sum / count; // mean
}
output = meanBit * reciprocalBits;
}
decodingOutput._values[ i ] = output;
}
}
}
| Cerenaut/agi | code/core/src/main/java/io/agi/core/sdr/ScalarEncoder.java | 2,724 | // density = 2 bits = 4 | line_comment | nl | /*
* Copyright (c) 2016.
*
* This file is part of Project AGI. <http://agi.io>
*
* Project AGI 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.
*
* Project AGI 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 Project AGI. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package io.agi.core.sdr;
import io.agi.core.data.Data;
import io.agi.core.data.Data2d;
import io.agi.core.orm.AbstractPair;
import java.awt.*;
/**
* Encodes to binary matrix by encoding values as subsets of bits.
* <p/>
* The properties of SDRs are that similar input should have similar bits.
* So there must be some redundancy - you can't have one bit per feature.
* <p/>
* This encoder assumes that each scalar input is represented as an array
* of bits.
* <p/>
* This is an adaptation of the Nupic ScalarEncoder
* https://github.com/numenta/nupic/wiki/Encoders
*
* @author dave
*/
public class ScalarEncoder implements SparseDistributedEncoder {
public boolean _encodeZero = false;
public int _bits = 0;
public int _density = 0;
public ScalarEncoder() {
}
public void setup( int bits, int density, boolean encodeZero ) {
_bits = bits;
_density = density;
_encodeZero = encodeZero;
}
public int getBins() {
// density =<SUF>
// 1100 0110 0011 = 3 bins = 4-2 +1
// density = 2 bits = 5
// 11000 01100 00110 00011 = 4 bins = 5-2 +1
// density = 3 bits = 5
// 11100 01110 00111 = 3 bins = 5-3 +1 = 3
// density = 3 bits = 8
// 1110 0000
// 0111 0000
// 0011 1000
// 0001 1100
// 0000 1110
// 0000 0111 = 6 bins = 8-3 +1 = 6
return _bits - _density + 1;
}
@Override
public Data createEncodingOutput( Data encodingInput ) {
int inputs = encodingInput.getSize();
// Force the dimensions into a 2d (rectangular) shape.
// Increase width to cope with extra bits.
Point size = Data2d.getSize( encodingInput );
// Dimensions.DIMENSION_X, outputs
int w = size.x * _bits;
int h = size.y;
Data encodingOutput = new Data( w, h );
return encodingOutput;
}
@Override
public Data createDecodingOutput( Data encodingInput, Data decodingInput ) {
int inputs = decodingInput.getSize();
// Assuming the same type of encoder did the encoding, we can reverse the geometric changes.
// However, we assume the input was 2d
Point size = Data2d.getSize( decodingInput );
// Dimensions.DIMENSION_X, outputs
int w = size.x / _bits;
int h = size.y;
Data decodingOutput = new Data( w, h );
return decodingOutput;
}
@Override
public void encode( Data encodingInput, Data encodingOutput ) {
int inputs = encodingInput.getSize();
int bins = getBins();
for( int i = 0; i < inputs; ++i ) {
float inputValue = encodingInput._values[ i ];
int offset = i * _bits;
if( ( !_encodeZero ) && ( inputValue == 0.f ) ) {
for( int b = 0; b < _bits; ++b ) {
encodingOutput._values[ offset + b ] = 0.f;
}
continue;
}
// density = 2 bits = 5
// possible patterns are:
// 11000
// 01100
// 00110
// 00011 = 4 possible bins = 5-2 +1 = 4
//
// density = 3 bits = 8
// 1110 0000
// 0111 0000
// 0011 1000
// 0001 1100
// 0000 1110
// 0000 0111 = 6 bins = 8-3 +1 = 6
// 0 0.25 0.5 0.75
// 0 * 4 = [0,2)
// 0.24 * 4 = [0,2)
// 0.25 * 4 = [1,3)
// 0.49 * 4 = [1,3)
// 0.5 * 4 = [2,4)
// 0.75 * 4 = [3,5)
// 0.99 * 4 = [3,5)
// 1 * 4 = [4,5) <-- bad, so limit it
float bin = inputValue * ( float ) bins;
int bin1 = Math.min( bins-1, (int)bin ); // captured case where value is 1.
int bin2 = bin1 + _density; // excluding this value
for( int b = 0; b < _bits; ++b ) {
float bitValue = 0.f;
if( ( b < bin2 ) && ( b >= bin1 ) ) {
bitValue = 1.f;
}
encodingOutput._values[ offset + b ] = bitValue;
}
}
}
@Override
public void decode( Data decodingInput, Data decodingOutput ) {
// computes the decode by taking the mean position of the encoded '1' bits.
// e.g.
// density = 2 bits = 5
// 11000 01100 00110 00011 = 4 bins = 5-2 +1
//
//Example: A scalar encoder with a range from 0 to 100 with n=12 and w=3 will
//produce the following encoders:
//
//1 becomes 111000000000
//7 becomes 111000000000
//15 becomes 011100000000
//36 becomes 000111000000
int inputs = decodingInput.getSize();
int outputs = inputs / _bits;
int bins = getBins();
float reciprocalBits = 1.f / (float)_bits;
float denominatorBits = (float)( Math.max( 1, _bits -1 ) );
for( int i = 0; i < outputs; ++i ) {
float output = 0.f;
if( _bits == 1 ) {
float bitValue = decodingInput._values[ i ];
if( bitValue > 0.f ) {
output = 1.f;
}
}
else {
int offset = i * _bits;
float sum = 0.f;
float count = 0.f;
for( int b = 0; b < _bits; ++b ) {
float bitValue = decodingInput._values[ offset + b ];
if( bitValue < 1.f ) {
continue;
}
// density = 1 bits = 1
// possible patterns are: bit / (bits-1)
// 0 00000 0/1 = 0
// 1 = 1 possible bins 00001 1/1 = 1
//
// density = 2 bits = 5
// possible patterns are: bit / (bits-1)
// 11000 10000 0/4 = 0.0
// 01100 01000 1/4 = 0.25
// 00110 00100 2/4 = 0.5
// 00011 = 4 possible bins = 5-2 +1 = 4 00010 3/4 = 0.75
// 00001 4/4 = 1.0
// density = 3 bits = 8
// 1110 0000 0/7 = 0.0
// 0111 0000 1/7 = 0.14
// 0011 1000 2/7 = 0.28
// 0001 1100 3/7 = 0.42
// 0000 1110 4/7 = 0.57
// 0000 0111 = 6 bins = 8-3 +1 = 6 5/7 = 0.71
// 6/7 = 0.85
// 7/7 = 1.0
float bitWeight = ( float ) b / denominatorBits; // so between zero and 1 inclusive
sum += bitWeight;
count += 1.f;
}
// e.g. 11000 = 0.0 + 0.25 / 2 = 0.125
// e.g. 00011 = 0.75 + 1.0 / 2 = 0.875
// e.g. 1110 0000 = 0.0 + 0.14 + 0.28 / 3 = 0.14 0.14 would've been encoded as 0.14*(6) = 0.84 = bin 0,1,2
float meanBit = 0.f;
if( count > 0.f ) {
meanBit = sum / count; // mean
}
output = meanBit * reciprocalBits;
}
decodingOutput._values[ i ] = output;
}
}
}
| False | 2,594 | 10 | 2,614 | 10 | 2,776 | 10 | 2,614 | 10 | 2,984 | 10 | false | false | false | false | false | true |
494 | 154456_26 | /*
* Copyright (C) 2010-2018 Gordon Fraser, Andrea Arcuri and EvoSuite
* contributors
*
* This file is part of EvoSuite.
*
* EvoSuite 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.0 of the License, or
* (at your option) any later version.
*
* EvoSuite 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>.
*/
package org.evosuite.contracts;
import org.evosuite.Properties;
import org.evosuite.TestGenerationContext;
import org.evosuite.testcase.TestCase;
import org.evosuite.testcase.execution.ExecutionObserver;
import org.evosuite.testcase.execution.ExecutionResult;
import org.evosuite.testcase.execution.Scope;
import org.evosuite.testcase.statements.Statement;
import org.evosuite.utils.generic.GenericMethod;
import org.junit.experimental.theories.Theory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import java.util.Set;
/**
* <p>
* ContractChecker class.
* </p>
*
* @author Gordon Fraser
*/
public class ContractChecker extends ExecutionObserver {
private static final Logger logger = LoggerFactory.getLogger(ContractChecker.class);
private final Set<Contract> contracts = new HashSet<>();
/*
* Maybe it was not a problem, but it all depends on when Properties.CHECK_CONTRACTS_END
* is initialized. Maybe best to just call it directly
*/
//private static final boolean checkAtEnd = Properties.CHECK_CONTRACTS_END;
private static final Set<Contract> invalid = new HashSet<>();
//private static boolean valid = true;
private static boolean active = true;
/**
* <p>
* Constructor for ContractChecker.
* </p>
*/
public ContractChecker() {
// Default from EvoSuite
contracts.add(new UndeclaredExceptionContract());
contracts.add(new JCrasherExceptionContract());
// Defaults from Randoop paper
contracts.add(new NullPointerExceptionContract());
contracts.add(new AssertionErrorContract());
contracts.add(new EqualsContract());
contracts.add(new ToStringReturnsNormallyContract());
contracts.add(new HashCodeReturnsNormallyContract());
// Further Randoop contracts, not in paper
contracts.add(new EqualsHashcodeContract());
contracts.add(new EqualsNullContract());
contracts.add(new EqualsSymmetricContract());
loadJUnitTheories();
}
private void loadJUnitTheories() {
if (Properties.JUNIT_THEORIES.isEmpty())
return;
for (String theoryName : Properties.JUNIT_THEORIES.split(":")) {
try {
Class<?> theory = TestGenerationContext.getInstance().getClassLoaderForSUT().loadClass(theoryName);
Constructor<?> constructor = theory.getConstructor();
if (!Modifier.isPublic(constructor.getModifiers())) {
logger.info("Theory class does not have public default constructor");
continue;
}
for (Method method : theory.getDeclaredMethods()) {
if (method.isAnnotationPresent(Theory.class)) {
logger.info("Found theory method: " + method.getName());
if (method.getParameterTypes().length != 1) {
logger.info("Wrong number of arguments!");
continue;
}
try {
GenericMethod gm = new GenericMethod(method, theory);
JUnitTheoryContract contract = new JUnitTheoryContract(gm);
contracts.add(contract);
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} catch (ClassNotFoundException e) {
logger.warn("Could not load theory " + theoryName + ": " + e);
} catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
/**
* <p>
* Setter for the field <code>active</code>.
* </p>
*
* @param isActive a boolean.
*/
public static void setActive(boolean isActive) {
active = isActive;
}
/* (non-Javadoc)
* @see org.evosuite.testcase.ExecutionObserver#output(int, java.lang.String)
*/
/**
* {@inheritDoc}
*/
@Override
public void output(int position, String output) {
// TODO Auto-generated method stub
}
/**
* Set the current test case, on which we check oracles while it is executed
*
* @param test a {@link org.evosuite.testcase.TestCase} object.
*/
public static void currentTest(TestCase test) {
currentTest = test;
//ContractChecker.valid = true;
ContractChecker.invalid.clear();
// TODO: Keep track of objects that raised an exception, and exclude them from contract checking
}
/* (non-Javadoc)
* @see org.evosuite.testcase.ExecutionObserver#statement(int, org.evosuite.testcase.Scope, org.evosuite.testcase.VariableReference)
*/
/**
* {@inheritDoc}
*/
@Override
public void afterStatement(Statement statement, Scope scope,
Throwable exception) {
//if (!ContractChecker.valid) {
/*
* once we get a contract that is violated, no point in checking the following statements,
* because the internal state of the SUT is corrupted.
*
* TODO: at this point, for the fitness function we still consider the coverage given by the
* following statements. Maybe that should be changed? At the moment, we only stop if exceptions
*/
// logger.debug("Not checking contracts for invalid test");
// return;
//}
if (!ContractChecker.active) {
return;
}
if (Properties.CHECK_CONTRACTS_END
&& statement.getPosition() < (currentTest.size() - 1))
return;
for (Contract contract : contracts) {
if (invalid.contains(contract))
continue;
try {
logger.debug("Checking contract {}", contract);
ContractViolation violation = contract.check(statement, scope, exception);
if (violation != null) {
logger.debug("Contract failed: {} {}", contract, statement.getCode());
FailingTestSet.addFailingTest(violation);
/*
FailingTestSet.addFailingTest(currentTest, contract, statement,
exception);
*/
//ContractChecker.valid = false;
invalid.add(contract);
//break;
}
} catch (Throwable t) {
logger.debug("Caught exception during contract checking: " + t);
for (StackTraceElement e : t.getStackTrace())
logger.info(e.toString());
}
}
}
/* (non-Javadoc)
* @see org.evosuite.testcase.ExecutionObserver#beforeStatement(org.evosuite.testcase.StatementInterface, org.evosuite.testcase.Scope)
*/
@Override
public void beforeStatement(Statement statement, Scope scope) {
// Do nothing
}
/* (non-Javadoc)
* @see org.evosuite.testcase.ExecutionObserver#clear()
*/
/**
* {@inheritDoc}
*/
@Override
public void clear() {
ContractChecker.invalid.clear();
// ContractChecker.valid = true;
}
@Override
public void testExecutionFinished(ExecutionResult r, Scope s) {
// do nothing
}
}
| EvoSuite/evosuite | client/src/main/java/org/evosuite/contracts/ContractChecker.java | 2,354 | //ContractChecker.valid = false; | line_comment | nl | /*
* Copyright (C) 2010-2018 Gordon Fraser, Andrea Arcuri and EvoSuite
* contributors
*
* This file is part of EvoSuite.
*
* EvoSuite 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.0 of the License, or
* (at your option) any later version.
*
* EvoSuite 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>.
*/
package org.evosuite.contracts;
import org.evosuite.Properties;
import org.evosuite.TestGenerationContext;
import org.evosuite.testcase.TestCase;
import org.evosuite.testcase.execution.ExecutionObserver;
import org.evosuite.testcase.execution.ExecutionResult;
import org.evosuite.testcase.execution.Scope;
import org.evosuite.testcase.statements.Statement;
import org.evosuite.utils.generic.GenericMethod;
import org.junit.experimental.theories.Theory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import java.util.Set;
/**
* <p>
* ContractChecker class.
* </p>
*
* @author Gordon Fraser
*/
public class ContractChecker extends ExecutionObserver {
private static final Logger logger = LoggerFactory.getLogger(ContractChecker.class);
private final Set<Contract> contracts = new HashSet<>();
/*
* Maybe it was not a problem, but it all depends on when Properties.CHECK_CONTRACTS_END
* is initialized. Maybe best to just call it directly
*/
//private static final boolean checkAtEnd = Properties.CHECK_CONTRACTS_END;
private static final Set<Contract> invalid = new HashSet<>();
//private static boolean valid = true;
private static boolean active = true;
/**
* <p>
* Constructor for ContractChecker.
* </p>
*/
public ContractChecker() {
// Default from EvoSuite
contracts.add(new UndeclaredExceptionContract());
contracts.add(new JCrasherExceptionContract());
// Defaults from Randoop paper
contracts.add(new NullPointerExceptionContract());
contracts.add(new AssertionErrorContract());
contracts.add(new EqualsContract());
contracts.add(new ToStringReturnsNormallyContract());
contracts.add(new HashCodeReturnsNormallyContract());
// Further Randoop contracts, not in paper
contracts.add(new EqualsHashcodeContract());
contracts.add(new EqualsNullContract());
contracts.add(new EqualsSymmetricContract());
loadJUnitTheories();
}
private void loadJUnitTheories() {
if (Properties.JUNIT_THEORIES.isEmpty())
return;
for (String theoryName : Properties.JUNIT_THEORIES.split(":")) {
try {
Class<?> theory = TestGenerationContext.getInstance().getClassLoaderForSUT().loadClass(theoryName);
Constructor<?> constructor = theory.getConstructor();
if (!Modifier.isPublic(constructor.getModifiers())) {
logger.info("Theory class does not have public default constructor");
continue;
}
for (Method method : theory.getDeclaredMethods()) {
if (method.isAnnotationPresent(Theory.class)) {
logger.info("Found theory method: " + method.getName());
if (method.getParameterTypes().length != 1) {
logger.info("Wrong number of arguments!");
continue;
}
try {
GenericMethod gm = new GenericMethod(method, theory);
JUnitTheoryContract contract = new JUnitTheoryContract(gm);
contracts.add(contract);
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} catch (ClassNotFoundException e) {
logger.warn("Could not load theory " + theoryName + ": " + e);
} catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
/**
* <p>
* Setter for the field <code>active</code>.
* </p>
*
* @param isActive a boolean.
*/
public static void setActive(boolean isActive) {
active = isActive;
}
/* (non-Javadoc)
* @see org.evosuite.testcase.ExecutionObserver#output(int, java.lang.String)
*/
/**
* {@inheritDoc}
*/
@Override
public void output(int position, String output) {
// TODO Auto-generated method stub
}
/**
* Set the current test case, on which we check oracles while it is executed
*
* @param test a {@link org.evosuite.testcase.TestCase} object.
*/
public static void currentTest(TestCase test) {
currentTest = test;
//ContractChecker.valid = true;
ContractChecker.invalid.clear();
// TODO: Keep track of objects that raised an exception, and exclude them from contract checking
}
/* (non-Javadoc)
* @see org.evosuite.testcase.ExecutionObserver#statement(int, org.evosuite.testcase.Scope, org.evosuite.testcase.VariableReference)
*/
/**
* {@inheritDoc}
*/
@Override
public void afterStatement(Statement statement, Scope scope,
Throwable exception) {
//if (!ContractChecker.valid) {
/*
* once we get a contract that is violated, no point in checking the following statements,
* because the internal state of the SUT is corrupted.
*
* TODO: at this point, for the fitness function we still consider the coverage given by the
* following statements. Maybe that should be changed? At the moment, we only stop if exceptions
*/
// logger.debug("Not checking contracts for invalid test");
// return;
//}
if (!ContractChecker.active) {
return;
}
if (Properties.CHECK_CONTRACTS_END
&& statement.getPosition() < (currentTest.size() - 1))
return;
for (Contract contract : contracts) {
if (invalid.contains(contract))
continue;
try {
logger.debug("Checking contract {}", contract);
ContractViolation violation = contract.check(statement, scope, exception);
if (violation != null) {
logger.debug("Contract failed: {} {}", contract, statement.getCode());
FailingTestSet.addFailingTest(violation);
/*
FailingTestSet.addFailingTest(currentTest, contract, statement,
exception);
*/
//ContractChecker.valid =<SUF>
invalid.add(contract);
//break;
}
} catch (Throwable t) {
logger.debug("Caught exception during contract checking: " + t);
for (StackTraceElement e : t.getStackTrace())
logger.info(e.toString());
}
}
}
/* (non-Javadoc)
* @see org.evosuite.testcase.ExecutionObserver#beforeStatement(org.evosuite.testcase.StatementInterface, org.evosuite.testcase.Scope)
*/
@Override
public void beforeStatement(Statement statement, Scope scope) {
// Do nothing
}
/* (non-Javadoc)
* @see org.evosuite.testcase.ExecutionObserver#clear()
*/
/**
* {@inheritDoc}
*/
@Override
public void clear() {
ContractChecker.invalid.clear();
// ContractChecker.valid = true;
}
@Override
public void testExecutionFinished(ExecutionResult r, Scope s) {
// do nothing
}
}
| False | 1,690 | 7 | 1,885 | 8 | 2,010 | 8 | 1,885 | 8 | 2,369 | 9 | false | false | false | false | false | true |
4,804 | 3160_2 | /*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* 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/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
package com.zerotier.sdk;
import android.util.Log;
import com.zerotier.sdk.util.StringUtils;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
/**
* Virtual network configuration
* <p>
* Defined in ZeroTierOne.h as ZT_VirtualNetworkConfig
*/
public class VirtualNetworkConfig implements Comparable<VirtualNetworkConfig> {
private final static String TAG = "VirtualNetworkConfig";
public static final int MAX_MULTICAST_SUBSCRIPTIONS = 4096;
public static final int ZT_MAX_ZT_ASSIGNED_ADDRESSES = 16;
private final long nwid;
private final long mac;
private final String name;
private final VirtualNetworkStatus status;
private final VirtualNetworkType type;
private final int mtu;
private final boolean dhcp;
private final boolean bridge;
private final boolean broadcastEnabled;
private final int portError;
private final long netconfRevision;
private final InetSocketAddress[] assignedAddresses;
private final VirtualNetworkRoute[] routes;
private final VirtualNetworkDNS dns;
public VirtualNetworkConfig(long nwid, long mac, String name, VirtualNetworkStatus status, VirtualNetworkType type, int mtu, boolean dhcp, boolean bridge, boolean broadcastEnabled, int portError, long netconfRevision, InetSocketAddress[] assignedAddresses, VirtualNetworkRoute[] routes, VirtualNetworkDNS dns) {
this.nwid = nwid;
this.mac = mac;
this.name = name;
this.status = status;
this.type = type;
if (mtu < 0) {
throw new RuntimeException("mtu < 0: " + mtu);
}
this.mtu = mtu;
this.dhcp = dhcp;
this.bridge = bridge;
this.broadcastEnabled = broadcastEnabled;
this.portError = portError;
if (netconfRevision < 0) {
throw new RuntimeException("netconfRevision < 0: " + netconfRevision);
}
this.netconfRevision = netconfRevision;
this.assignedAddresses = assignedAddresses;
this.routes = routes;
this.dns = dns;
}
@Override
public String toString() {
return "VirtualNetworkConfig(" + StringUtils.networkIdToString(nwid) + ", " + StringUtils.macAddressToString(mac) + ", " + name + ", " + status + ", " + type + ", " + mtu + ", " + dhcp + ", " + bridge + ", " + broadcastEnabled + ", " + portError + ", " + netconfRevision + ", " + Arrays.toString(assignedAddresses) + ", " + Arrays.toString(routes) + ", " + dns + ")";
}
@Override
public boolean equals(Object o) {
if (o == null) {
Log.i(TAG, "Old is null");
return false;
}
if (!(o instanceof VirtualNetworkConfig)) {
Log.i(TAG, "Old is not an instance of VirtualNetworkConfig: " + o);
return false;
}
VirtualNetworkConfig old = (VirtualNetworkConfig) o;
if (this.nwid != old.nwid) {
Log.i(TAG, "NetworkID Changed. New: " + StringUtils.networkIdToString(this.nwid) + " (" + this.nwid + "), " +
"Old: " + StringUtils.networkIdToString(old.nwid) + " (" + old.nwid + ")");
return false;
}
if (this.mac != old.mac) {
Log.i(TAG, "MAC Changed. New: " + StringUtils.macAddressToString(this.mac) + ", Old: " + StringUtils.macAddressToString(old.mac));
return false;
}
if (!this.name.equals(old.name)) {
Log.i(TAG, "Name Changed. New: " + this.name + ", Old: " + old.name);
return false;
}
if (this.status != old.status) {
Log.i(TAG, "Status Changed. New: " + this.status + ", Old: " + old.status);
return false;
}
if (this.type != old.type) {
Log.i(TAG, "Type changed. New: " + this.type + ", Old: " + old.type);
return false;
}
if (this.mtu != old.mtu) {
Log.i(TAG, "MTU Changed. New: " + this.mtu + ", Old: " + old.mtu);
return false;
}
if (this.dhcp != old.dhcp) {
Log.i(TAG, "DHCP Flag Changed. New: " + this.dhcp + ", Old: " + old.dhcp);
return false;
}
if (this.bridge != old.bridge) {
Log.i(TAG, "Bridge Flag Changed. New: " + this.bridge + ", Old: " + old.bridge);
return false;
}
if (this.broadcastEnabled != old.broadcastEnabled) {
Log.i(TAG, "Broadcast Flag Changed. New: "+ this.broadcastEnabled + ", Old: " + old.broadcastEnabled);
return false;
}
if (this.portError != old.portError) {
Log.i(TAG, "Port Error Changed. New: " + this.portError + ", Old: " + old.portError);
return false;
}
if (this.netconfRevision != old.netconfRevision) {
Log.i(TAG, "NetConfRevision Changed. New: " + this.netconfRevision + ", Old: " + old.netconfRevision);
return false;
}
if (!Arrays.equals(assignedAddresses, old.assignedAddresses)) {
ArrayList<String> aaNew = new ArrayList<>();
ArrayList<String> aaOld = new ArrayList<>();
for (InetSocketAddress s : assignedAddresses) {
aaNew.add(s.toString());
}
for (InetSocketAddress s : old.assignedAddresses) {
aaOld.add(s.toString());
}
Collections.sort(aaNew);
Collections.sort(aaOld);
Log.i(TAG, "Assigned Addresses Changed");
Log.i(TAG, "New:");
for (String s : aaNew) {
Log.i(TAG, " " + s);
}
Log.i(TAG, "");
Log.i(TAG, "Old:");
for (String s : aaOld) {
Log.i(TAG, " " +s);
}
Log.i(TAG, "");
return false;
}
if (!Arrays.equals(routes, old.routes)) {
ArrayList<String> rNew = new ArrayList<>();
ArrayList<String> rOld = new ArrayList<>();
for (VirtualNetworkRoute r : routes) {
rNew.add(r.toString());
}
for (VirtualNetworkRoute r : old.routes) {
rOld.add(r.toString());
}
Collections.sort(rNew);
Collections.sort(rOld);
Log.i(TAG, "Managed Routes Changed");
Log.i(TAG, "New:");
for (String s : rNew) {
Log.i(TAG, " " + s);
}
Log.i(TAG, "");
Log.i(TAG, "Old:");
for (String s : rOld) {
Log.i(TAG, " " + s);
}
Log.i(TAG, "");
return false;
}
boolean dnsEquals;
if (this.dns == null) {
//noinspection RedundantIfStatement
if (old.dns == null) {
dnsEquals = true;
} else {
dnsEquals = false;
}
} else {
if (old.dns == null) {
dnsEquals = false;
} else {
dnsEquals = this.dns.equals(old.dns);
}
}
if (!dnsEquals) {
Log.i(TAG, "DNS Changed. New: " + this.dns + ", Old: " + old.dns);
return false;
}
return true;
}
@Override
public int compareTo(VirtualNetworkConfig cfg) {
return Long.compare(this.nwid, cfg.nwid);
}
@Override
public int hashCode() {
int result = 17;
result = 37 * result + (int) (nwid ^ (nwid >>> 32));
result = 37 * result + (int) (mac ^ (mac >>> 32));
result = 37 * result + name.hashCode();
result = 37 * result + status.hashCode();
result = 37 * result + type.hashCode();
result = 37 * result + mtu;
result = 37 * result + (dhcp ? 1 : 0);
result = 37 * result + (bridge ? 1 : 0);
result = 37 * result + (broadcastEnabled ? 1 : 0);
result = 37 * result + portError;
result = 37 * result + (int) (netconfRevision ^ (netconfRevision >>> 32));
result = 37 * result + Arrays.hashCode(assignedAddresses);
result = 37 * result + Arrays.hashCode(routes);
result = 37 * result + (dns == null ? 0 : dns.hashCode());
return result;
}
/**
* 64-bit ZeroTier network ID
*/
public long getNwid() {
return nwid;
}
/**
* Ethernet MAC (48 bits) that should be assigned to port
*/
public long getMac() {
return mac;
}
/**
* Network name (from network configuration master)
*/
public String getName() {
return name;
}
/**
* Network configuration request status
*/
public VirtualNetworkStatus getStatus() {
return status;
}
/**
* Network type
*/
public VirtualNetworkType getType() {
return type;
}
/**
* Maximum interface MTU
*/
public int getMtu() {
return mtu;
}
/**
* If the network this port belongs to indicates DHCP availability
*
* <p>This is a suggestion. The underlying implementation is free to ignore it
* for security or other reasons. This is simply a netconf parameter that
* means 'DHCP is available on this network.'</p>
*/
public boolean isDhcp() {
return dhcp;
}
/**
* If this port is allowed to bridge to other networks
*
* <p>This is informational. If this is false, bridged packets will simply
* be dropped and bridging won't work.</p>
*/
public boolean isBridge() {
return bridge;
}
/**
* If true, this network supports and allows broadcast (ff:ff:ff:ff:ff:ff) traffic
*/
public boolean isBroadcastEnabled() {
return broadcastEnabled;
}
/**
* If the network is in PORT_ERROR state, this is the error most recently returned by the port config callback
*/
public int getPortError() {
return portError;
}
/**
* Network config revision as reported by netconf master
*
* <p>If this is zero, it means we're still waiting for our netconf.</p>
*/
public long getNetconfRevision() {
return netconfRevision;
}
/**
* ZeroTier-assigned addresses (in {@link InetSocketAddress} objects)
* <p>
* For IP, the port number of the sockaddr_XX structure contains the number
* of bits in the address netmask. Only the IP address and port are used.
* Other fields like interface number can be ignored.
* <p>
* This is only used for ZeroTier-managed address assignments sent by the
* virtual network's configuration master.
*/
public InetSocketAddress[] getAssignedAddresses() {
return assignedAddresses;
}
/**
* ZeroTier-assigned routes (in {@link VirtualNetworkRoute} objects)
*/
public VirtualNetworkRoute[] getRoutes() {
return routes;
}
/**
* Network specific DNS configuration
*/
public VirtualNetworkDNS getDns() {
return dns;
}
}
| zerotier/ZeroTierOne | java/src/com/zerotier/sdk/VirtualNetworkConfig.java | 3,594 | /**
* 64-bit ZeroTier network ID
*/ | block_comment | nl | /*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* 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/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
package com.zerotier.sdk;
import android.util.Log;
import com.zerotier.sdk.util.StringUtils;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
/**
* Virtual network configuration
* <p>
* Defined in ZeroTierOne.h as ZT_VirtualNetworkConfig
*/
public class VirtualNetworkConfig implements Comparable<VirtualNetworkConfig> {
private final static String TAG = "VirtualNetworkConfig";
public static final int MAX_MULTICAST_SUBSCRIPTIONS = 4096;
public static final int ZT_MAX_ZT_ASSIGNED_ADDRESSES = 16;
private final long nwid;
private final long mac;
private final String name;
private final VirtualNetworkStatus status;
private final VirtualNetworkType type;
private final int mtu;
private final boolean dhcp;
private final boolean bridge;
private final boolean broadcastEnabled;
private final int portError;
private final long netconfRevision;
private final InetSocketAddress[] assignedAddresses;
private final VirtualNetworkRoute[] routes;
private final VirtualNetworkDNS dns;
public VirtualNetworkConfig(long nwid, long mac, String name, VirtualNetworkStatus status, VirtualNetworkType type, int mtu, boolean dhcp, boolean bridge, boolean broadcastEnabled, int portError, long netconfRevision, InetSocketAddress[] assignedAddresses, VirtualNetworkRoute[] routes, VirtualNetworkDNS dns) {
this.nwid = nwid;
this.mac = mac;
this.name = name;
this.status = status;
this.type = type;
if (mtu < 0) {
throw new RuntimeException("mtu < 0: " + mtu);
}
this.mtu = mtu;
this.dhcp = dhcp;
this.bridge = bridge;
this.broadcastEnabled = broadcastEnabled;
this.portError = portError;
if (netconfRevision < 0) {
throw new RuntimeException("netconfRevision < 0: " + netconfRevision);
}
this.netconfRevision = netconfRevision;
this.assignedAddresses = assignedAddresses;
this.routes = routes;
this.dns = dns;
}
@Override
public String toString() {
return "VirtualNetworkConfig(" + StringUtils.networkIdToString(nwid) + ", " + StringUtils.macAddressToString(mac) + ", " + name + ", " + status + ", " + type + ", " + mtu + ", " + dhcp + ", " + bridge + ", " + broadcastEnabled + ", " + portError + ", " + netconfRevision + ", " + Arrays.toString(assignedAddresses) + ", " + Arrays.toString(routes) + ", " + dns + ")";
}
@Override
public boolean equals(Object o) {
if (o == null) {
Log.i(TAG, "Old is null");
return false;
}
if (!(o instanceof VirtualNetworkConfig)) {
Log.i(TAG, "Old is not an instance of VirtualNetworkConfig: " + o);
return false;
}
VirtualNetworkConfig old = (VirtualNetworkConfig) o;
if (this.nwid != old.nwid) {
Log.i(TAG, "NetworkID Changed. New: " + StringUtils.networkIdToString(this.nwid) + " (" + this.nwid + "), " +
"Old: " + StringUtils.networkIdToString(old.nwid) + " (" + old.nwid + ")");
return false;
}
if (this.mac != old.mac) {
Log.i(TAG, "MAC Changed. New: " + StringUtils.macAddressToString(this.mac) + ", Old: " + StringUtils.macAddressToString(old.mac));
return false;
}
if (!this.name.equals(old.name)) {
Log.i(TAG, "Name Changed. New: " + this.name + ", Old: " + old.name);
return false;
}
if (this.status != old.status) {
Log.i(TAG, "Status Changed. New: " + this.status + ", Old: " + old.status);
return false;
}
if (this.type != old.type) {
Log.i(TAG, "Type changed. New: " + this.type + ", Old: " + old.type);
return false;
}
if (this.mtu != old.mtu) {
Log.i(TAG, "MTU Changed. New: " + this.mtu + ", Old: " + old.mtu);
return false;
}
if (this.dhcp != old.dhcp) {
Log.i(TAG, "DHCP Flag Changed. New: " + this.dhcp + ", Old: " + old.dhcp);
return false;
}
if (this.bridge != old.bridge) {
Log.i(TAG, "Bridge Flag Changed. New: " + this.bridge + ", Old: " + old.bridge);
return false;
}
if (this.broadcastEnabled != old.broadcastEnabled) {
Log.i(TAG, "Broadcast Flag Changed. New: "+ this.broadcastEnabled + ", Old: " + old.broadcastEnabled);
return false;
}
if (this.portError != old.portError) {
Log.i(TAG, "Port Error Changed. New: " + this.portError + ", Old: " + old.portError);
return false;
}
if (this.netconfRevision != old.netconfRevision) {
Log.i(TAG, "NetConfRevision Changed. New: " + this.netconfRevision + ", Old: " + old.netconfRevision);
return false;
}
if (!Arrays.equals(assignedAddresses, old.assignedAddresses)) {
ArrayList<String> aaNew = new ArrayList<>();
ArrayList<String> aaOld = new ArrayList<>();
for (InetSocketAddress s : assignedAddresses) {
aaNew.add(s.toString());
}
for (InetSocketAddress s : old.assignedAddresses) {
aaOld.add(s.toString());
}
Collections.sort(aaNew);
Collections.sort(aaOld);
Log.i(TAG, "Assigned Addresses Changed");
Log.i(TAG, "New:");
for (String s : aaNew) {
Log.i(TAG, " " + s);
}
Log.i(TAG, "");
Log.i(TAG, "Old:");
for (String s : aaOld) {
Log.i(TAG, " " +s);
}
Log.i(TAG, "");
return false;
}
if (!Arrays.equals(routes, old.routes)) {
ArrayList<String> rNew = new ArrayList<>();
ArrayList<String> rOld = new ArrayList<>();
for (VirtualNetworkRoute r : routes) {
rNew.add(r.toString());
}
for (VirtualNetworkRoute r : old.routes) {
rOld.add(r.toString());
}
Collections.sort(rNew);
Collections.sort(rOld);
Log.i(TAG, "Managed Routes Changed");
Log.i(TAG, "New:");
for (String s : rNew) {
Log.i(TAG, " " + s);
}
Log.i(TAG, "");
Log.i(TAG, "Old:");
for (String s : rOld) {
Log.i(TAG, " " + s);
}
Log.i(TAG, "");
return false;
}
boolean dnsEquals;
if (this.dns == null) {
//noinspection RedundantIfStatement
if (old.dns == null) {
dnsEquals = true;
} else {
dnsEquals = false;
}
} else {
if (old.dns == null) {
dnsEquals = false;
} else {
dnsEquals = this.dns.equals(old.dns);
}
}
if (!dnsEquals) {
Log.i(TAG, "DNS Changed. New: " + this.dns + ", Old: " + old.dns);
return false;
}
return true;
}
@Override
public int compareTo(VirtualNetworkConfig cfg) {
return Long.compare(this.nwid, cfg.nwid);
}
@Override
public int hashCode() {
int result = 17;
result = 37 * result + (int) (nwid ^ (nwid >>> 32));
result = 37 * result + (int) (mac ^ (mac >>> 32));
result = 37 * result + name.hashCode();
result = 37 * result + status.hashCode();
result = 37 * result + type.hashCode();
result = 37 * result + mtu;
result = 37 * result + (dhcp ? 1 : 0);
result = 37 * result + (bridge ? 1 : 0);
result = 37 * result + (broadcastEnabled ? 1 : 0);
result = 37 * result + portError;
result = 37 * result + (int) (netconfRevision ^ (netconfRevision >>> 32));
result = 37 * result + Arrays.hashCode(assignedAddresses);
result = 37 * result + Arrays.hashCode(routes);
result = 37 * result + (dns == null ? 0 : dns.hashCode());
return result;
}
/**
* 64-bit ZeroTier network<SUF>*/
public long getNwid() {
return nwid;
}
/**
* Ethernet MAC (48 bits) that should be assigned to port
*/
public long getMac() {
return mac;
}
/**
* Network name (from network configuration master)
*/
public String getName() {
return name;
}
/**
* Network configuration request status
*/
public VirtualNetworkStatus getStatus() {
return status;
}
/**
* Network type
*/
public VirtualNetworkType getType() {
return type;
}
/**
* Maximum interface MTU
*/
public int getMtu() {
return mtu;
}
/**
* If the network this port belongs to indicates DHCP availability
*
* <p>This is a suggestion. The underlying implementation is free to ignore it
* for security or other reasons. This is simply a netconf parameter that
* means 'DHCP is available on this network.'</p>
*/
public boolean isDhcp() {
return dhcp;
}
/**
* If this port is allowed to bridge to other networks
*
* <p>This is informational. If this is false, bridged packets will simply
* be dropped and bridging won't work.</p>
*/
public boolean isBridge() {
return bridge;
}
/**
* If true, this network supports and allows broadcast (ff:ff:ff:ff:ff:ff) traffic
*/
public boolean isBroadcastEnabled() {
return broadcastEnabled;
}
/**
* If the network is in PORT_ERROR state, this is the error most recently returned by the port config callback
*/
public int getPortError() {
return portError;
}
/**
* Network config revision as reported by netconf master
*
* <p>If this is zero, it means we're still waiting for our netconf.</p>
*/
public long getNetconfRevision() {
return netconfRevision;
}
/**
* ZeroTier-assigned addresses (in {@link InetSocketAddress} objects)
* <p>
* For IP, the port number of the sockaddr_XX structure contains the number
* of bits in the address netmask. Only the IP address and port are used.
* Other fields like interface number can be ignored.
* <p>
* This is only used for ZeroTier-managed address assignments sent by the
* virtual network's configuration master.
*/
public InetSocketAddress[] getAssignedAddresses() {
return assignedAddresses;
}
/**
* ZeroTier-assigned routes (in {@link VirtualNetworkRoute} objects)
*/
public VirtualNetworkRoute[] getRoutes() {
return routes;
}
/**
* Network specific DNS configuration
*/
public VirtualNetworkDNS getDns() {
return dns;
}
}
| False | 2,849 | 14 | 3,078 | 14 | 3,342 | 16 | 3,079 | 14 | 3,691 | 17 | false | false | false | false | false | true |
2,031 | 116152_16 | package engine.core;
public class MarioLevelModel {
//start and end of the level
public static final char MARIO_START = 'M';
public static final char MARIO_EXIT = 'F';
public static final char EMPTY = '-';
//game tiles symbols
public static final char GROUND = 'X';
public static final char PYRAMID_BLOCK = '#';
public static final char NORMAL_BRICK = 'S';
public static final char COIN_BRICK = 'C';
public static final char LIFE_BRICK = 'L';
public static final char SPECIAL_BRICK = 'U';
public static final char SPECIAL_QUESTION_BLOCK = '@';
public static final char COIN_QUESTION_BLOCK = '!';
public static final char COIN_HIDDEN_BLOCK = '2';
public static final char LIFE_HIDDEN_BLOCK = '1';
public static final char USED_BLOCK = 'D';
public static final char COIN = 'o';
public static final char PIPE = 't';
public static final char PIPE_FLOWER = 'T';
public static final char BULLET_BILL = '*';
public static final char PLATFORM_BACKGROUND = '|';
public static final char PLATFORM = '%';
//enemies that can be in the level
public static final char GOOMBA = 'g';
public static final char GOOMBA_WINGED = 'G';
public static final char RED_KOOPA = 'r';
public static final char RED_KOOPA_WINGED = 'R';
public static final char GREEN_KOOPA = 'k';
public static final char GREEN_KOOPA_WINGED = 'K';
public static final char SPIKY = 'y';
public static final char SPIKY_WINGED = 'Y';
/**
* Get array of level tiles that can spawn enemies
*
* @return tiles that spawn enemies
*/
public static char[] getEnemyTiles() {
return new char[]{BULLET_BILL, PIPE_FLOWER};
}
/**
* list of tiles that can be bumped by the player
*
* @return list of tiles that can be bumped by the player
*/
public static char[] getBumpableTiles() {
return new char[]{NORMAL_BRICK, COIN_BRICK, LIFE_BRICK, SPECIAL_BRICK,
SPECIAL_QUESTION_BLOCK, COIN_QUESTION_BLOCK};
}
/**
* list all the tiles that can block the player movement
*
* @return array of all tiles that block player movement
*/
public static char[] getBlockTiles() {
return new char[]{GROUND, PYRAMID_BLOCK, USED_BLOCK,
NORMAL_BRICK, COIN_BRICK, LIFE_BRICK, SPECIAL_BRICK,
SPECIAL_QUESTION_BLOCK, COIN_QUESTION_BLOCK,
PIPE, PIPE_FLOWER, BULLET_BILL};
}
/**
* tiles that block the player and not interactive
*
* @return list of all solid tiles that don't interact
*/
public static char[] getBlockNonSpecialTiles() {
return new char[]{GROUND, PYRAMID_BLOCK, USED_BLOCK, PIPE};
}
/**
* list of all tiles that won't block the player movement
*
* @return list of all non blocking tiles
*/
public static char[] getNonBlockingTiles() {
return new char[]{COIN, COIN_HIDDEN_BLOCK, LIFE_HIDDEN_BLOCK, PLATFORM_BACKGROUND};
}
/**
* Get a list of all scene tiles that could produce something collected by the player
*
* @return list of all collectible scene tiles
*/
public static char[] getCollectablesTiles() {
return new char[]{COIN,
COIN_BRICK, LIFE_BRICK, SPECIAL_BRICK,
SPECIAL_QUESTION_BLOCK, COIN_QUESTION_BLOCK,
COIN_HIDDEN_BLOCK, LIFE_HIDDEN_BLOCK};
}
/**
* Get the correct version of the enemy char
*
* @param enemy the enemy character
* @param winged boolean to indicate if its a winged enemy
* @return correct character based on winged
*/
public static char getWingedEnemyVersion(char enemy, boolean winged) {
if (!winged) {
if (enemy == GOOMBA_WINGED) {
return GOOMBA;
}
if (enemy == GREEN_KOOPA_WINGED) {
return GREEN_KOOPA;
}
if (enemy == RED_KOOPA_WINGED) {
return RED_KOOPA;
}
if (enemy == SPIKY_WINGED) {
return SPIKY;
}
return enemy;
}
if (enemy == GOOMBA) {
return GOOMBA_WINGED;
}
if (enemy == GREEN_KOOPA) {
return GREEN_KOOPA_WINGED;
}
if (enemy == RED_KOOPA) {
return RED_KOOPA_WINGED;
}
if (enemy == SPIKY) {
return SPIKY_WINGED;
}
return enemy;
}
/**
* a list of all enemy characters
*
* @return array of all enemy characters
*/
public static char[] getEnemyCharacters() {
return new char[]{GOOMBA, GOOMBA_WINGED, RED_KOOPA, RED_KOOPA_WINGED,
GREEN_KOOPA, GREEN_KOOPA_WINGED, SPIKY, SPIKY_WINGED};
}
/**
* list of all enemy character based on wings
*
* @param wings true if the list contain winged enemies and false otherwise
* @return an array of all wings enemy or not winged
*/
public static char[] getEnemyCharacters(boolean wings) {
if (wings) {
return new char[]{GOOMBA_WINGED, RED_KOOPA_WINGED, GREEN_KOOPA_WINGED, SPIKY_WINGED};
}
return new char[]{GOOMBA, RED_KOOPA, GREEN_KOOPA, SPIKY};
}
/**
* map object for helping
*/
private char[][] map;
/**
* create the Level Model
*
* @param levelWidth the width of the level
* @param levelHeight the height of the level
*/
public MarioLevelModel(int levelWidth, int levelHeight) {
this.map = new char[levelWidth][levelHeight];
}
/**
* create a similar clone to the current map
*/
public MarioLevelModel clone() {
MarioLevelModel model = new MarioLevelModel(this.getWidth(), this.getHeight());
for (int x = 0; x < model.getWidth(); x++) {
for (int y = 0; y < model.getHeight(); y++) {
model.map[x][y] = this.map[x][y];
}
}
return model;
}
/**
* get map width
*
* @return map width
*/
public int getWidth() {
return this.map.length;
}
/**
* get map height
*
* @return map height
*/
public int getHeight() {
return this.map[0].length;
}
/**
* get the value of the tile in certain location
*
* @param x x tile position
* @param y y tile position
* @return the tile value
*/
public char getBlock(int x, int y) {
int currentX = x;
int currentY = y;
if (x < 0) currentX = 0;
if (y < 0) currentY = 0;
if (x > this.map.length - 1) currentX = this.map.length - 1;
if (y > this.map[0].length - 1) currentY = this.map[0].length - 1;
return this.map[currentX][currentY];
}
/**
* set a tile on the map with certain value
*
* @param x the x tile position
* @param y the y tile position
* @param value the tile value to be set
*/
public void setBlock(int x, int y, char value) {
if (x < 0 || y < 0 || x > this.map.length - 1 || y > this.map[0].length - 1) return;
this.map[x][y] = value;
}
/**
* set a rectangle area of the map with a certain tile value
*
* @param startX the x tile position of the left upper corner
* @param startY the y tile position of the left upper corner
* @param width the width of the rectangle
* @param height the height of the rectangle
* @param value the tile value
*/
public void setRectangle(int startX, int startY, int width, int height, char value) {
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
this.setBlock(startX + x, startY + y, value);
}
}
}
/**
* Copy the string level to the current map
*
* @param level the input string level
*/
public void copyFromString(String level) {
this.copyFromString(0, 0, 0, 0, this.getWidth(), this.getHeight(), level);
}
/**
* Copy portion from string to the current map
*
* @param targetX the x of the target location
* @param targetY the y of the target location
* @param sourceX the x from the level string
* @param sourceY the y from the level string
* @param width the width of the copied portion
* @param height the height of the copied protion
* @param level the level string
*/
public void copyFromString(int targetX, int targetY, int sourceX, int sourceY, int width, int height, String level) {
String[] lines = level.split("\n");
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int maxWidth = lines[0].length();
int maxHeight = lines.length;
this.setBlock(x + targetX, y + targetY, lines[Math.min(y + sourceY, maxHeight - 1)].charAt(Math.min(x + sourceX, maxWidth - 1)));
}
}
}
/**
* clear the whole map
*/
public void clearMap() {
this.setRectangle(0, 0, this.getWidth(), this.getHeight(), EMPTY);
}
/**
* get the string value of the map
*
* @return the map in form of string
*/
public String getMap() {
String result = "";
for (int y = 0; y < map[0].length; y++) {
for (int x = 0; x < map.length; x++) {
result += map[x][y];
}
result += "\n";
}
return result;
}
/**
* test the current level using a specific agent
*
* @param agent agent to test the level
* @param timer amount of time allowed to test that level
* @return statistical results about the level
*/
public MarioResult testALevelWithAgent(MarioAgent agent, int timer) {
MarioGame game = new MarioGame();
return game.runGame(agent, this.getMap(), timer);
}
}
| amidos2006/Mario-AI-Framework | src/engine/core/MarioLevelModel.java | 3,190 | /**
* get map height
*
* @return map height
*/ | block_comment | nl | package engine.core;
public class MarioLevelModel {
//start and end of the level
public static final char MARIO_START = 'M';
public static final char MARIO_EXIT = 'F';
public static final char EMPTY = '-';
//game tiles symbols
public static final char GROUND = 'X';
public static final char PYRAMID_BLOCK = '#';
public static final char NORMAL_BRICK = 'S';
public static final char COIN_BRICK = 'C';
public static final char LIFE_BRICK = 'L';
public static final char SPECIAL_BRICK = 'U';
public static final char SPECIAL_QUESTION_BLOCK = '@';
public static final char COIN_QUESTION_BLOCK = '!';
public static final char COIN_HIDDEN_BLOCK = '2';
public static final char LIFE_HIDDEN_BLOCK = '1';
public static final char USED_BLOCK = 'D';
public static final char COIN = 'o';
public static final char PIPE = 't';
public static final char PIPE_FLOWER = 'T';
public static final char BULLET_BILL = '*';
public static final char PLATFORM_BACKGROUND = '|';
public static final char PLATFORM = '%';
//enemies that can be in the level
public static final char GOOMBA = 'g';
public static final char GOOMBA_WINGED = 'G';
public static final char RED_KOOPA = 'r';
public static final char RED_KOOPA_WINGED = 'R';
public static final char GREEN_KOOPA = 'k';
public static final char GREEN_KOOPA_WINGED = 'K';
public static final char SPIKY = 'y';
public static final char SPIKY_WINGED = 'Y';
/**
* Get array of level tiles that can spawn enemies
*
* @return tiles that spawn enemies
*/
public static char[] getEnemyTiles() {
return new char[]{BULLET_BILL, PIPE_FLOWER};
}
/**
* list of tiles that can be bumped by the player
*
* @return list of tiles that can be bumped by the player
*/
public static char[] getBumpableTiles() {
return new char[]{NORMAL_BRICK, COIN_BRICK, LIFE_BRICK, SPECIAL_BRICK,
SPECIAL_QUESTION_BLOCK, COIN_QUESTION_BLOCK};
}
/**
* list all the tiles that can block the player movement
*
* @return array of all tiles that block player movement
*/
public static char[] getBlockTiles() {
return new char[]{GROUND, PYRAMID_BLOCK, USED_BLOCK,
NORMAL_BRICK, COIN_BRICK, LIFE_BRICK, SPECIAL_BRICK,
SPECIAL_QUESTION_BLOCK, COIN_QUESTION_BLOCK,
PIPE, PIPE_FLOWER, BULLET_BILL};
}
/**
* tiles that block the player and not interactive
*
* @return list of all solid tiles that don't interact
*/
public static char[] getBlockNonSpecialTiles() {
return new char[]{GROUND, PYRAMID_BLOCK, USED_BLOCK, PIPE};
}
/**
* list of all tiles that won't block the player movement
*
* @return list of all non blocking tiles
*/
public static char[] getNonBlockingTiles() {
return new char[]{COIN, COIN_HIDDEN_BLOCK, LIFE_HIDDEN_BLOCK, PLATFORM_BACKGROUND};
}
/**
* Get a list of all scene tiles that could produce something collected by the player
*
* @return list of all collectible scene tiles
*/
public static char[] getCollectablesTiles() {
return new char[]{COIN,
COIN_BRICK, LIFE_BRICK, SPECIAL_BRICK,
SPECIAL_QUESTION_BLOCK, COIN_QUESTION_BLOCK,
COIN_HIDDEN_BLOCK, LIFE_HIDDEN_BLOCK};
}
/**
* Get the correct version of the enemy char
*
* @param enemy the enemy character
* @param winged boolean to indicate if its a winged enemy
* @return correct character based on winged
*/
public static char getWingedEnemyVersion(char enemy, boolean winged) {
if (!winged) {
if (enemy == GOOMBA_WINGED) {
return GOOMBA;
}
if (enemy == GREEN_KOOPA_WINGED) {
return GREEN_KOOPA;
}
if (enemy == RED_KOOPA_WINGED) {
return RED_KOOPA;
}
if (enemy == SPIKY_WINGED) {
return SPIKY;
}
return enemy;
}
if (enemy == GOOMBA) {
return GOOMBA_WINGED;
}
if (enemy == GREEN_KOOPA) {
return GREEN_KOOPA_WINGED;
}
if (enemy == RED_KOOPA) {
return RED_KOOPA_WINGED;
}
if (enemy == SPIKY) {
return SPIKY_WINGED;
}
return enemy;
}
/**
* a list of all enemy characters
*
* @return array of all enemy characters
*/
public static char[] getEnemyCharacters() {
return new char[]{GOOMBA, GOOMBA_WINGED, RED_KOOPA, RED_KOOPA_WINGED,
GREEN_KOOPA, GREEN_KOOPA_WINGED, SPIKY, SPIKY_WINGED};
}
/**
* list of all enemy character based on wings
*
* @param wings true if the list contain winged enemies and false otherwise
* @return an array of all wings enemy or not winged
*/
public static char[] getEnemyCharacters(boolean wings) {
if (wings) {
return new char[]{GOOMBA_WINGED, RED_KOOPA_WINGED, GREEN_KOOPA_WINGED, SPIKY_WINGED};
}
return new char[]{GOOMBA, RED_KOOPA, GREEN_KOOPA, SPIKY};
}
/**
* map object for helping
*/
private char[][] map;
/**
* create the Level Model
*
* @param levelWidth the width of the level
* @param levelHeight the height of the level
*/
public MarioLevelModel(int levelWidth, int levelHeight) {
this.map = new char[levelWidth][levelHeight];
}
/**
* create a similar clone to the current map
*/
public MarioLevelModel clone() {
MarioLevelModel model = new MarioLevelModel(this.getWidth(), this.getHeight());
for (int x = 0; x < model.getWidth(); x++) {
for (int y = 0; y < model.getHeight(); y++) {
model.map[x][y] = this.map[x][y];
}
}
return model;
}
/**
* get map width
*
* @return map width
*/
public int getWidth() {
return this.map.length;
}
/**
* get map height<SUF>*/
public int getHeight() {
return this.map[0].length;
}
/**
* get the value of the tile in certain location
*
* @param x x tile position
* @param y y tile position
* @return the tile value
*/
public char getBlock(int x, int y) {
int currentX = x;
int currentY = y;
if (x < 0) currentX = 0;
if (y < 0) currentY = 0;
if (x > this.map.length - 1) currentX = this.map.length - 1;
if (y > this.map[0].length - 1) currentY = this.map[0].length - 1;
return this.map[currentX][currentY];
}
/**
* set a tile on the map with certain value
*
* @param x the x tile position
* @param y the y tile position
* @param value the tile value to be set
*/
public void setBlock(int x, int y, char value) {
if (x < 0 || y < 0 || x > this.map.length - 1 || y > this.map[0].length - 1) return;
this.map[x][y] = value;
}
/**
* set a rectangle area of the map with a certain tile value
*
* @param startX the x tile position of the left upper corner
* @param startY the y tile position of the left upper corner
* @param width the width of the rectangle
* @param height the height of the rectangle
* @param value the tile value
*/
public void setRectangle(int startX, int startY, int width, int height, char value) {
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
this.setBlock(startX + x, startY + y, value);
}
}
}
/**
* Copy the string level to the current map
*
* @param level the input string level
*/
public void copyFromString(String level) {
this.copyFromString(0, 0, 0, 0, this.getWidth(), this.getHeight(), level);
}
/**
* Copy portion from string to the current map
*
* @param targetX the x of the target location
* @param targetY the y of the target location
* @param sourceX the x from the level string
* @param sourceY the y from the level string
* @param width the width of the copied portion
* @param height the height of the copied protion
* @param level the level string
*/
public void copyFromString(int targetX, int targetY, int sourceX, int sourceY, int width, int height, String level) {
String[] lines = level.split("\n");
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int maxWidth = lines[0].length();
int maxHeight = lines.length;
this.setBlock(x + targetX, y + targetY, lines[Math.min(y + sourceY, maxHeight - 1)].charAt(Math.min(x + sourceX, maxWidth - 1)));
}
}
}
/**
* clear the whole map
*/
public void clearMap() {
this.setRectangle(0, 0, this.getWidth(), this.getHeight(), EMPTY);
}
/**
* get the string value of the map
*
* @return the map in form of string
*/
public String getMap() {
String result = "";
for (int y = 0; y < map[0].length; y++) {
for (int x = 0; x < map.length; x++) {
result += map[x][y];
}
result += "\n";
}
return result;
}
/**
* test the current level using a specific agent
*
* @param agent agent to test the level
* @param timer amount of time allowed to test that level
* @return statistical results about the level
*/
public MarioResult testALevelWithAgent(MarioAgent agent, int timer) {
MarioGame game = new MarioGame();
return game.runGame(agent, this.getMap(), timer);
}
}
| False | 2,541 | 18 | 2,661 | 16 | 2,847 | 20 | 2,661 | 16 | 3,238 | 20 | false | false | false | false | false | true |
2,155 | 106820_0 | package be.intecbrussel;
import java.util.Scanner;
public class MainApp {
public static void main(String[] args) {
// Lees een bedrag in van een factuur
Scanner myScan = new Scanner(System.in);
double amount = myScan.nextDouble();
Product product = new Product(amount);
double result = product.getTotalAmount();
if (result > product.minimumExpense) {
System.out.println("the original price was: " + amount + " ,and after discount it's: " + result +
" ,total discount: " + product.discount);
} else {
System.out.println("total price: " + amount);
}
// Indien het bedrag groter is dan 5000 euro, dan wordt er een korting van 5 % toegestaan
}
} | avifeld99/exercise-berlin | src/be/intecbrussel/MainApp.java | 218 | // Lees een bedrag in van een factuur | line_comment | nl | package be.intecbrussel;
import java.util.Scanner;
public class MainApp {
public static void main(String[] args) {
// Lees een<SUF>
Scanner myScan = new Scanner(System.in);
double amount = myScan.nextDouble();
Product product = new Product(amount);
double result = product.getTotalAmount();
if (result > product.minimumExpense) {
System.out.println("the original price was: " + amount + " ,and after discount it's: " + result +
" ,total discount: " + product.discount);
} else {
System.out.println("total price: " + amount);
}
// Indien het bedrag groter is dan 5000 euro, dan wordt er een korting van 5 % toegestaan
}
} | True | 176 | 11 | 198 | 12 | 200 | 9 | 198 | 12 | 226 | 11 | false | false | false | false | false | true |
2,478 | 180031_0 | package units;
import java.util.HashSet;
import java.util.Set;
import java.util.HashMap;
public class PowerProduct implements Unit {
private HashMap<Base,Integer> powers;
private Number factor;
public PowerProduct(){
powers = new HashMap<Base,Integer>();
factor = 1;
}
public PowerProduct(Base base){
powers = new HashMap<Base,Integer>();
powers.put(base, 1);
factor = 1;
}
private PowerProduct(HashMap<Base,Integer> map){
powers = map;
factor = 1;
}
public Set<Base> bases() {
Set<Base> bases = new HashSet<Base>();
for (Base base: powers.keySet()) {
if (power(base) != 0) {
bases.add(base);
}
}
return bases;
}
public int power(Base base) {
Integer value = powers.get(base);
return (value == null ? 0 : value);
}
public Number factor() {
return factor;
}
public static Unit normal(Unit unit) {
Set<Base> bases = unit.bases();
if (unit.factor().doubleValue() == 1 && bases.size() == 1) {
Base base = (Base) bases.toArray()[0];
if (unit.power(base) == 1) {
return base;
} else {
return unit;
}
} else {
return unit;
}
}
public int hashCode() {
return powers.hashCode();
}
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (! (other instanceof Unit)) {
return false;
}
Unit otherUnit = (Unit) other;
if (factor.doubleValue() != otherUnit.factor().doubleValue()) {
return false;
}
for (Base base: bases()){
if (power(base) != otherUnit.power(base)) {
return false;
}
}
for (Base base: otherUnit.bases()){
if (power(base) != otherUnit.power(base)) {
return false;
}
}
return true;
}
public Unit multiply(Number factor){
HashMap<Base,Integer> hash = new HashMap<Base,Integer>();
for (Base base: bases()){
hash.put(base, power(base));
}
PowerProduct scaled = new PowerProduct(hash);
scaled.factor = this.factor.doubleValue() * factor.doubleValue();
return scaled;
}
public Unit multiply(Unit other){
HashMap<Base,Integer> hash = new HashMap<Base,Integer>();
for (Base base: bases()){
hash.put(base, power(base));
}
for (Base base: other.bases()){
hash.put(base, other.power(base) + power(base));
}
PowerProduct multiplied = new PowerProduct(hash);
multiplied.factor = other.factor().doubleValue() * factor.doubleValue();
return multiplied;
}
public Unit raise(int power) {
HashMap<Base,Integer> hash = new HashMap<Base,Integer>();
for (Base base: bases()){
hash.put(base, power(base) * power);
}
PowerProduct raised = new PowerProduct(hash);
raised.factor = Math.pow(factor.doubleValue(), power);
return raised;
}
public Unit flat() {
Unit newUnit = new PowerProduct().multiply(factor());
for (Base base: bases()){
Unit flattened = base.flat().raise(power(base));
newUnit = newUnit.multiply(flattened);
}
return newUnit;
}
public String pprint() {
// Geen schoonheidsprijs :)
String symbolic = factor().toString();
String sep = "·";
if (factor().doubleValue() == 1) {
symbolic = ""; // to avoid the annoying 1.0 of doubles. todo: reconsider numeric type
sep = "";
}
for (Base base: bases()){
int power = power(base);
if (0 < power) {
symbolic = symbolic.concat(sep);
sep = "·";
symbolic = symbolic.concat(base.pprint());
if (power != 1) {
symbolic = symbolic.concat("^");
symbolic = symbolic.concat(Integer.toString(power));
}
}
}
sep = "/";
for (Base base: bases()){
int power = power(base);
if (power < 0) {
power = -power;
symbolic = symbolic.concat(sep);
sep = "·";
symbolic = symbolic.concat(base.pprint());
if (power != 1) {
symbolic = symbolic.concat("^");
symbolic = symbolic.concat(Integer.toString(power));
}
}
}
if (symbolic == "") {
return "1";
}
return symbolic;
}
} | cwi-swat/pacioli | java/units/src/units/PowerProduct.java | 1,367 | // Geen schoonheidsprijs :) | line_comment | nl | package units;
import java.util.HashSet;
import java.util.Set;
import java.util.HashMap;
public class PowerProduct implements Unit {
private HashMap<Base,Integer> powers;
private Number factor;
public PowerProduct(){
powers = new HashMap<Base,Integer>();
factor = 1;
}
public PowerProduct(Base base){
powers = new HashMap<Base,Integer>();
powers.put(base, 1);
factor = 1;
}
private PowerProduct(HashMap<Base,Integer> map){
powers = map;
factor = 1;
}
public Set<Base> bases() {
Set<Base> bases = new HashSet<Base>();
for (Base base: powers.keySet()) {
if (power(base) != 0) {
bases.add(base);
}
}
return bases;
}
public int power(Base base) {
Integer value = powers.get(base);
return (value == null ? 0 : value);
}
public Number factor() {
return factor;
}
public static Unit normal(Unit unit) {
Set<Base> bases = unit.bases();
if (unit.factor().doubleValue() == 1 && bases.size() == 1) {
Base base = (Base) bases.toArray()[0];
if (unit.power(base) == 1) {
return base;
} else {
return unit;
}
} else {
return unit;
}
}
public int hashCode() {
return powers.hashCode();
}
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (! (other instanceof Unit)) {
return false;
}
Unit otherUnit = (Unit) other;
if (factor.doubleValue() != otherUnit.factor().doubleValue()) {
return false;
}
for (Base base: bases()){
if (power(base) != otherUnit.power(base)) {
return false;
}
}
for (Base base: otherUnit.bases()){
if (power(base) != otherUnit.power(base)) {
return false;
}
}
return true;
}
public Unit multiply(Number factor){
HashMap<Base,Integer> hash = new HashMap<Base,Integer>();
for (Base base: bases()){
hash.put(base, power(base));
}
PowerProduct scaled = new PowerProduct(hash);
scaled.factor = this.factor.doubleValue() * factor.doubleValue();
return scaled;
}
public Unit multiply(Unit other){
HashMap<Base,Integer> hash = new HashMap<Base,Integer>();
for (Base base: bases()){
hash.put(base, power(base));
}
for (Base base: other.bases()){
hash.put(base, other.power(base) + power(base));
}
PowerProduct multiplied = new PowerProduct(hash);
multiplied.factor = other.factor().doubleValue() * factor.doubleValue();
return multiplied;
}
public Unit raise(int power) {
HashMap<Base,Integer> hash = new HashMap<Base,Integer>();
for (Base base: bases()){
hash.put(base, power(base) * power);
}
PowerProduct raised = new PowerProduct(hash);
raised.factor = Math.pow(factor.doubleValue(), power);
return raised;
}
public Unit flat() {
Unit newUnit = new PowerProduct().multiply(factor());
for (Base base: bases()){
Unit flattened = base.flat().raise(power(base));
newUnit = newUnit.multiply(flattened);
}
return newUnit;
}
public String pprint() {
// Geen schoonheidsprijs<SUF>
String symbolic = factor().toString();
String sep = "·";
if (factor().doubleValue() == 1) {
symbolic = ""; // to avoid the annoying 1.0 of doubles. todo: reconsider numeric type
sep = "";
}
for (Base base: bases()){
int power = power(base);
if (0 < power) {
symbolic = symbolic.concat(sep);
sep = "·";
symbolic = symbolic.concat(base.pprint());
if (power != 1) {
symbolic = symbolic.concat("^");
symbolic = symbolic.concat(Integer.toString(power));
}
}
}
sep = "/";
for (Base base: bases()){
int power = power(base);
if (power < 0) {
power = -power;
symbolic = symbolic.concat(sep);
sep = "·";
symbolic = symbolic.concat(base.pprint());
if (power != 1) {
symbolic = symbolic.concat("^");
symbolic = symbolic.concat(Integer.toString(power));
}
}
}
if (symbolic == "") {
return "1";
}
return symbolic;
}
} | True | 1,057 | 10 | 1,277 | 12 | 1,272 | 8 | 1,273 | 12 | 1,554 | 10 | false | false | false | false | false | true |
2,905 | 85041_3 | /*-
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2024 Smile CDR, 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.
* #L%
*/
package ca.uhn.fhir.util;
import ca.uhn.fhir.context.phonetic.ApacheEncoder;
import ca.uhn.fhir.context.phonetic.IPhoneticEncoder;
import ca.uhn.fhir.context.phonetic.NumericEncoder;
import ca.uhn.fhir.context.phonetic.PhoneticEncoderEnum;
import org.apache.commons.codec.language.Caverphone1;
import org.apache.commons.codec.language.Caverphone2;
import org.apache.commons.codec.language.ColognePhonetic;
import org.apache.commons.codec.language.DoubleMetaphone;
import org.apache.commons.codec.language.MatchRatingApproachEncoder;
import org.apache.commons.codec.language.Metaphone;
import org.apache.commons.codec.language.Nysiis;
import org.apache.commons.codec.language.RefinedSoundex;
import org.apache.commons.codec.language.Soundex;
import org.apache.commons.lang3.EnumUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class PhoneticEncoderUtil {
// embedded class only for parameter returns
private static class ParsedValues {
private final Integer maxCodeLength;
private final String encoderString;
public ParsedValues(String theString, Integer theMaxCode) {
maxCodeLength = theMaxCode;
encoderString = theString;
}
public Integer getMaxCodeLength() {
return maxCodeLength;
}
public String getEncoderString() {
return encoderString;
}
}
private static final Logger ourLog = LoggerFactory.getLogger(PhoneticEncoderUtil.class);
private PhoneticEncoderUtil() {}
/**
* Creates the phonetic encoder wrapper from
* an input string.
*
* <p>
* String must be in the format of...
* </p>
*
* PhoneticEncoderEnum(MAX_LENGTH)
*
* @return The IPhoneticEncoder
*/
public static IPhoneticEncoder getEncoder(String theString) {
ParsedValues values = parseIntValue(theString);
String encoderType = values.getEncoderString();
Integer encoderMaxString = values.getMaxCodeLength();
IPhoneticEncoder encoder = getEncoderFromString(encoderType, encoderMaxString);
if (encoder != null) {
return encoder;
} else {
ourLog.warn("Invalid phonetic param string " + theString);
return null;
}
}
private static ParsedValues parseIntValue(String theString) {
String encoderType = null;
Integer encoderMaxString = null;
int braceIndex = theString.indexOf("(");
if (braceIndex != -1) {
int len = theString.length();
if (theString.charAt(len - 1) == ')') {
encoderType = theString.substring(0, braceIndex);
String num = theString.substring(braceIndex + 1, len - 1);
try {
encoderMaxString = Integer.parseInt(num);
} catch (NumberFormatException ex) {
// invalid number parse error
}
if (encoderMaxString == null || encoderMaxString < 0) {
// parse error
ourLog.error("Invalid encoder max character length: " + num);
encoderType = null;
}
}
// else - parse error
} else {
encoderType = theString;
}
return new ParsedValues(encoderType, encoderMaxString);
}
private static IPhoneticEncoder getEncoderFromString(String theName, Integer theMax) {
IPhoneticEncoder encoder = null;
PhoneticEncoderEnum enumVal = EnumUtils.getEnum(PhoneticEncoderEnum.class, theName);
if (enumVal != null) {
switch (enumVal) {
case CAVERPHONE1:
Caverphone1 caverphone1 = new Caverphone1();
encoder = new ApacheEncoder(theName, caverphone1);
break;
case CAVERPHONE2:
Caverphone2 caverphone2 = new Caverphone2();
encoder = new ApacheEncoder(theName, caverphone2);
break;
case COLOGNE:
ColognePhonetic colognePhonetic = new ColognePhonetic();
encoder = new ApacheEncoder(theName, colognePhonetic);
break;
case DOUBLE_METAPHONE:
DoubleMetaphone doubleMetaphone = new DoubleMetaphone();
if (theMax != null) {
doubleMetaphone.setMaxCodeLen(theMax);
}
encoder = new ApacheEncoder(theName, doubleMetaphone);
break;
case MATCH_RATING_APPROACH:
MatchRatingApproachEncoder matchRatingApproachEncoder = new MatchRatingApproachEncoder();
encoder = new ApacheEncoder(theName, matchRatingApproachEncoder);
break;
case METAPHONE:
Metaphone metaphone = new Metaphone();
if (theMax != null) {
metaphone.setMaxCodeLen(theMax);
}
encoder = new ApacheEncoder(theName, metaphone);
break;
case NYSIIS:
Nysiis nysiis = new Nysiis();
encoder = new ApacheEncoder(theName, nysiis);
break;
case NYSIIS_LONG:
Nysiis nysiis1_long = new Nysiis(false);
encoder = new ApacheEncoder(theName, nysiis1_long);
break;
case REFINED_SOUNDEX:
RefinedSoundex refinedSoundex = new RefinedSoundex();
encoder = new ApacheEncoder(theName, refinedSoundex);
break;
case SOUNDEX:
Soundex soundex = new Soundex();
// soundex has deprecated setting the max size
encoder = new ApacheEncoder(theName, soundex);
break;
case NUMERIC:
encoder = new NumericEncoder();
break;
default:
// we don't ever expect to be here
// this log message is purely for devs who update this
// enum, but not this method
ourLog.error("Unhandled PhoneticParamEnum value " + enumVal.name());
break;
}
}
return encoder;
}
}
| hapifhir/hapi-fhir | hapi-fhir-base/src/main/java/ca/uhn/fhir/util/PhoneticEncoderUtil.java | 1,973 | // invalid number parse error | line_comment | nl | /*-
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2024 Smile CDR, 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.
* #L%
*/
package ca.uhn.fhir.util;
import ca.uhn.fhir.context.phonetic.ApacheEncoder;
import ca.uhn.fhir.context.phonetic.IPhoneticEncoder;
import ca.uhn.fhir.context.phonetic.NumericEncoder;
import ca.uhn.fhir.context.phonetic.PhoneticEncoderEnum;
import org.apache.commons.codec.language.Caverphone1;
import org.apache.commons.codec.language.Caverphone2;
import org.apache.commons.codec.language.ColognePhonetic;
import org.apache.commons.codec.language.DoubleMetaphone;
import org.apache.commons.codec.language.MatchRatingApproachEncoder;
import org.apache.commons.codec.language.Metaphone;
import org.apache.commons.codec.language.Nysiis;
import org.apache.commons.codec.language.RefinedSoundex;
import org.apache.commons.codec.language.Soundex;
import org.apache.commons.lang3.EnumUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class PhoneticEncoderUtil {
// embedded class only for parameter returns
private static class ParsedValues {
private final Integer maxCodeLength;
private final String encoderString;
public ParsedValues(String theString, Integer theMaxCode) {
maxCodeLength = theMaxCode;
encoderString = theString;
}
public Integer getMaxCodeLength() {
return maxCodeLength;
}
public String getEncoderString() {
return encoderString;
}
}
private static final Logger ourLog = LoggerFactory.getLogger(PhoneticEncoderUtil.class);
private PhoneticEncoderUtil() {}
/**
* Creates the phonetic encoder wrapper from
* an input string.
*
* <p>
* String must be in the format of...
* </p>
*
* PhoneticEncoderEnum(MAX_LENGTH)
*
* @return The IPhoneticEncoder
*/
public static IPhoneticEncoder getEncoder(String theString) {
ParsedValues values = parseIntValue(theString);
String encoderType = values.getEncoderString();
Integer encoderMaxString = values.getMaxCodeLength();
IPhoneticEncoder encoder = getEncoderFromString(encoderType, encoderMaxString);
if (encoder != null) {
return encoder;
} else {
ourLog.warn("Invalid phonetic param string " + theString);
return null;
}
}
private static ParsedValues parseIntValue(String theString) {
String encoderType = null;
Integer encoderMaxString = null;
int braceIndex = theString.indexOf("(");
if (braceIndex != -1) {
int len = theString.length();
if (theString.charAt(len - 1) == ')') {
encoderType = theString.substring(0, braceIndex);
String num = theString.substring(braceIndex + 1, len - 1);
try {
encoderMaxString = Integer.parseInt(num);
} catch (NumberFormatException ex) {
// invalid number<SUF>
}
if (encoderMaxString == null || encoderMaxString < 0) {
// parse error
ourLog.error("Invalid encoder max character length: " + num);
encoderType = null;
}
}
// else - parse error
} else {
encoderType = theString;
}
return new ParsedValues(encoderType, encoderMaxString);
}
private static IPhoneticEncoder getEncoderFromString(String theName, Integer theMax) {
IPhoneticEncoder encoder = null;
PhoneticEncoderEnum enumVal = EnumUtils.getEnum(PhoneticEncoderEnum.class, theName);
if (enumVal != null) {
switch (enumVal) {
case CAVERPHONE1:
Caverphone1 caverphone1 = new Caverphone1();
encoder = new ApacheEncoder(theName, caverphone1);
break;
case CAVERPHONE2:
Caverphone2 caverphone2 = new Caverphone2();
encoder = new ApacheEncoder(theName, caverphone2);
break;
case COLOGNE:
ColognePhonetic colognePhonetic = new ColognePhonetic();
encoder = new ApacheEncoder(theName, colognePhonetic);
break;
case DOUBLE_METAPHONE:
DoubleMetaphone doubleMetaphone = new DoubleMetaphone();
if (theMax != null) {
doubleMetaphone.setMaxCodeLen(theMax);
}
encoder = new ApacheEncoder(theName, doubleMetaphone);
break;
case MATCH_RATING_APPROACH:
MatchRatingApproachEncoder matchRatingApproachEncoder = new MatchRatingApproachEncoder();
encoder = new ApacheEncoder(theName, matchRatingApproachEncoder);
break;
case METAPHONE:
Metaphone metaphone = new Metaphone();
if (theMax != null) {
metaphone.setMaxCodeLen(theMax);
}
encoder = new ApacheEncoder(theName, metaphone);
break;
case NYSIIS:
Nysiis nysiis = new Nysiis();
encoder = new ApacheEncoder(theName, nysiis);
break;
case NYSIIS_LONG:
Nysiis nysiis1_long = new Nysiis(false);
encoder = new ApacheEncoder(theName, nysiis1_long);
break;
case REFINED_SOUNDEX:
RefinedSoundex refinedSoundex = new RefinedSoundex();
encoder = new ApacheEncoder(theName, refinedSoundex);
break;
case SOUNDEX:
Soundex soundex = new Soundex();
// soundex has deprecated setting the max size
encoder = new ApacheEncoder(theName, soundex);
break;
case NUMERIC:
encoder = new NumericEncoder();
break;
default:
// we don't ever expect to be here
// this log message is purely for devs who update this
// enum, but not this method
ourLog.error("Unhandled PhoneticParamEnum value " + enumVal.name());
break;
}
}
return encoder;
}
}
| False | 1,498 | 5 | 1,760 | 5 | 1,689 | 5 | 1,760 | 5 | 2,254 | 5 | false | false | false | false | false | true |
3,808 | 37488_2 | /*
* Copyright 2018 Google LLC
*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. The ASF licenses this
* file to you under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.plaidapp.core.ui.widget;
import android.content.Context;
import androidx.dynamicanimation.animation.DynamicAnimation;
import androidx.dynamicanimation.animation.SpringAnimation;
import androidx.dynamicanimation.animation.SpringForce;
import androidx.annotation.NonNull;
import androidx.core.view.ViewCompat;
import androidx.customview.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import io.plaidapp.core.util.ViewOffsetHelper;
/**
* A {@link FrameLayout} whose content can be dragged downward to be dismissed (either directly or
* via a nested scrolling child). It must contain a single child view and exposes {@link Callbacks}
* to respond to it's movement & dismissal.
*
* Only implements the modal bottom sheet behavior from the material spec, not the persistent
* behavior (yet).
*/
public class BottomSheet extends FrameLayout {
// constants
private static final float SETTLE_STIFFNESS = 800f;
private static final int MIN_FLING_DISMISS_VELOCITY = 500; // dp/s
private final int SCALED_MIN_FLING_DISMISS_VELOCITY; // px/s
// child views & helpers
View sheet;
ViewOffsetHelper sheetOffsetHelper;
private ViewDragHelper sheetDragHelper;
// state
int sheetExpandedTop;
int sheetBottom;
int dismissOffset;
boolean settling = false;
boolean initialHeightChecked = false;
boolean hasInteractedWithSheet = false;
private int nestedScrollInitialTop;
private boolean isNestedScrolling = false;
private List<Callbacks> callbacks;
public BottomSheet(Context context) {
this(context, null, 0);
}
public BottomSheet(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public BottomSheet(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
SCALED_MIN_FLING_DISMISS_VELOCITY =
(int) (context.getResources().getDisplayMetrics().density * MIN_FLING_DISMISS_VELOCITY);
}
/**
* Callbacks for responding to interactions with the bottom sheet.
*/
public static abstract class Callbacks {
public void onSheetDismissed() { }
public void onSheetPositionChanged(int sheetTop, boolean userInteracted) { }
}
public void registerCallback(Callbacks callback) {
if (callbacks == null) {
callbacks = new CopyOnWriteArrayList<>();
}
callbacks.add(callback);
}
public void unregisterCallback(Callbacks callback) {
if (callbacks != null && !callbacks.isEmpty()) {
callbacks.remove(callback);
}
}
public void dismiss() {
animateSettle(dismissOffset, 0);
}
public void expand() {
animateSettle(0, 0);
}
public boolean isExpanded() {
return sheet.getTop() == sheetExpandedTop;
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
if (sheet != null) {
throw new UnsupportedOperationException("BottomSheet must only have 1 child view");
}
sheet = child;
sheetOffsetHelper = new ViewOffsetHelper(sheet);
sheet.addOnLayoutChangeListener(sheetLayout);
// force the sheet contents to be gravity bottom. This ain't a top sheet.
((LayoutParams) params).gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
super.addView(child, index, params);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
hasInteractedWithSheet = true;
if (isNestedScrolling) return false; /* prefer nested scrolling to dragging */
final int action = ev.getAction();
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
sheetDragHelper.cancel();
return false;
}
return isDraggableViewUnder((int) ev.getX(), (int) ev.getY())
&& (sheetDragHelper.shouldInterceptTouchEvent(ev));
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
sheetDragHelper.processTouchEvent(ev);
return sheetDragHelper.getCapturedView() != null || super.onTouchEvent(ev);
}
@Override
public void computeScroll() {
if (sheetDragHelper.continueSettling(true)) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
@Override
public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
if ((nestedScrollAxes & View.SCROLL_AXIS_VERTICAL) != 0) {
isNestedScrolling = true;
nestedScrollInitialTop = sheet.getTop();
return true;
}
return false;
}
@Override
public void onNestedScroll(View target, int dxConsumed, int dyConsumed,
int dxUnconsumed, int dyUnconsumed) {
// if scrolling downward, use any unconsumed (i.e. not used by the scrolling child)
// to drag the sheet downward
if (dyUnconsumed < 0) {
sheetOffsetHelper.offsetTopAndBottom(-dyUnconsumed);
dispatchPositionChangedCallback();
}
}
@Override
public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) {
// if scrolling upward & the sheet has been dragged downward
// then drag back into place before allowing scrolls
if (dy > 0) {
final int upwardDragRange = sheet.getTop() - sheetExpandedTop;
if (upwardDragRange > 0) {
final int consume = Math.min(upwardDragRange, dy);
sheetOffsetHelper.offsetTopAndBottom(-consume);
dispatchPositionChangedCallback();
consumed[1] = consume;
}
}
}
@Override
public void onStopNestedScroll(View child) {
isNestedScrolling = false;
if (!settling /* fling might have occurred */
&& sheet.getTop() != nestedScrollInitialTop) { /* don't expand after a tap */
expand();
}
}
@Override
public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
if (velocityY <= -SCALED_MIN_FLING_DISMISS_VELOCITY /* flinging downward */
&& !target.canScrollVertically(-1)) { /* nested scrolling child can't scroll up */
animateSettle(dismissOffset, velocityY);
return true;
} else if (velocityY > 0 && !isExpanded()) {
animateSettle(0, velocityY);
}
return false;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
sheetDragHelper = ViewDragHelper.create(this, dragHelperCallbacks);
}
private boolean isDraggableViewUnder(int x, int y) {
return getVisibility() == VISIBLE && sheetDragHelper.isViewUnder(this, x, y);
}
void animateSettle(int targetOffset, float initialVelocity) {
if (settling) return;
if (sheetOffsetHelper.getTopAndBottomOffset() == targetOffset) {
if (targetOffset >= dismissOffset) {
dispatchDismissCallback();
}
return;
}
settling = true;
final boolean dismissing = targetOffset == dismissOffset;
// if we're dismissing, we don't want the view to decelerate as it reaches the bottom
// so set a target position that actually overshoots a little
final float finalPosition = dismissing ? dismissOffset * 1.1f : targetOffset;
SpringAnimation anim = new SpringAnimation(
sheetOffsetHelper, ViewOffsetHelper.OFFSET_Y, finalPosition)
.setStartValue(sheetOffsetHelper.getTopAndBottomOffset())
.setStartVelocity(initialVelocity)
.setMinimumVisibleChange(DynamicAnimation.MIN_VISIBLE_CHANGE_PIXELS);
anim.getSpring()
.setStiffness(SETTLE_STIFFNESS)
.setDampingRatio(SpringForce.DAMPING_RATIO_NO_BOUNCY);
anim.addEndListener((animation, canceled, value, velocity) -> {
dispatchPositionChangedCallback();
if (dismissing) {
dispatchDismissCallback();
}
settling = false;
});
if (callbacks != null && !callbacks.isEmpty()) {
anim.addUpdateListener((animation, value, velocity) -> dispatchPositionChangedCallback());
}
anim.start();
}
private final ViewDragHelper.Callback dragHelperCallbacks = new ViewDragHelper.Callback() {
@Override
public boolean tryCaptureView(@NonNull View child, int pointerId) {
return child == sheet;
}
@Override
public int clampViewPositionVertical(@NonNull View child, int top, int dy) {
return Math.min(Math.max(top, sheetExpandedTop), sheetBottom);
}
@Override
public int clampViewPositionHorizontal(@NonNull View child, int left, int dx) {
return sheet.getLeft();
}
@Override
public int getViewVerticalDragRange(@NonNull View child) {
return sheetBottom - sheetExpandedTop;
}
@Override
public void onViewPositionChanged(@NonNull View child, int left, int top, int dx, int dy) {
// notify the offset helper that the sheets offsets have been changed externally
sheetOffsetHelper.resyncOffsets();
dispatchPositionChangedCallback();
}
@Override
public void onViewReleased(@NonNull View releasedChild, float velocityX, float velocityY) {
// dismiss on downward fling, otherwise settle back to expanded position
final boolean dismiss = velocityY >= SCALED_MIN_FLING_DISMISS_VELOCITY;
animateSettle(dismiss ? dismissOffset : 0, velocityY);
}
};
private final OnLayoutChangeListener sheetLayout = new OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
sheetExpandedTop = top;
sheetBottom = bottom;
dismissOffset = bottom - top;
sheetOffsetHelper.onViewLayout();
// modal bottom sheet content should not initially be taller than the 16:9 keyline
if (!initialHeightChecked) {
applySheetInitialHeightOffset(false, -1);
initialHeightChecked = true;
} else if (!hasInteractedWithSheet
&& (oldBottom - oldTop) != (bottom - top)) { /* sheet height changed */
/* if the sheet content's height changes before the user has interacted with it
then consider this still in the 'initial' state and apply the height constraint,
but in this case, animate to it */
applySheetInitialHeightOffset(true, oldTop - sheetExpandedTop);
}
}
};
void applySheetInitialHeightOffset(boolean animateChange, int previousOffset) {
final int minimumGap = sheet.getMeasuredWidth() / 16 * 9;
if (sheet.getTop() < minimumGap) {
final int offset = minimumGap - sheet.getTop();
if (animateChange) {
sheetOffsetHelper.setTopAndBottomOffset(previousOffset);
animateSettle(offset, 0);
} else {
sheetOffsetHelper.setTopAndBottomOffset(offset);
}
}
}
void dispatchDismissCallback() {
if (callbacks != null && !callbacks.isEmpty()) {
for (Callbacks callback : callbacks) {
callback.onSheetDismissed();
}
}
}
void dispatchPositionChangedCallback() {
if (callbacks != null && !callbacks.isEmpty()) {
for (Callbacks callback : callbacks) {
callback.onSheetPositionChanged(sheet.getTop(), hasInteractedWithSheet);
}
}
}
}
| nickbutcher/plaid | core/src/main/java/io/plaidapp/core/ui/widget/BottomSheet.java | 3,515 | // child views & helpers | line_comment | nl | /*
* Copyright 2018 Google LLC
*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. The ASF licenses this
* file to you under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.plaidapp.core.ui.widget;
import android.content.Context;
import androidx.dynamicanimation.animation.DynamicAnimation;
import androidx.dynamicanimation.animation.SpringAnimation;
import androidx.dynamicanimation.animation.SpringForce;
import androidx.annotation.NonNull;
import androidx.core.view.ViewCompat;
import androidx.customview.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import io.plaidapp.core.util.ViewOffsetHelper;
/**
* A {@link FrameLayout} whose content can be dragged downward to be dismissed (either directly or
* via a nested scrolling child). It must contain a single child view and exposes {@link Callbacks}
* to respond to it's movement & dismissal.
*
* Only implements the modal bottom sheet behavior from the material spec, not the persistent
* behavior (yet).
*/
public class BottomSheet extends FrameLayout {
// constants
private static final float SETTLE_STIFFNESS = 800f;
private static final int MIN_FLING_DISMISS_VELOCITY = 500; // dp/s
private final int SCALED_MIN_FLING_DISMISS_VELOCITY; // px/s
// child views<SUF>
View sheet;
ViewOffsetHelper sheetOffsetHelper;
private ViewDragHelper sheetDragHelper;
// state
int sheetExpandedTop;
int sheetBottom;
int dismissOffset;
boolean settling = false;
boolean initialHeightChecked = false;
boolean hasInteractedWithSheet = false;
private int nestedScrollInitialTop;
private boolean isNestedScrolling = false;
private List<Callbacks> callbacks;
public BottomSheet(Context context) {
this(context, null, 0);
}
public BottomSheet(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public BottomSheet(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
SCALED_MIN_FLING_DISMISS_VELOCITY =
(int) (context.getResources().getDisplayMetrics().density * MIN_FLING_DISMISS_VELOCITY);
}
/**
* Callbacks for responding to interactions with the bottom sheet.
*/
public static abstract class Callbacks {
public void onSheetDismissed() { }
public void onSheetPositionChanged(int sheetTop, boolean userInteracted) { }
}
public void registerCallback(Callbacks callback) {
if (callbacks == null) {
callbacks = new CopyOnWriteArrayList<>();
}
callbacks.add(callback);
}
public void unregisterCallback(Callbacks callback) {
if (callbacks != null && !callbacks.isEmpty()) {
callbacks.remove(callback);
}
}
public void dismiss() {
animateSettle(dismissOffset, 0);
}
public void expand() {
animateSettle(0, 0);
}
public boolean isExpanded() {
return sheet.getTop() == sheetExpandedTop;
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
if (sheet != null) {
throw new UnsupportedOperationException("BottomSheet must only have 1 child view");
}
sheet = child;
sheetOffsetHelper = new ViewOffsetHelper(sheet);
sheet.addOnLayoutChangeListener(sheetLayout);
// force the sheet contents to be gravity bottom. This ain't a top sheet.
((LayoutParams) params).gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
super.addView(child, index, params);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
hasInteractedWithSheet = true;
if (isNestedScrolling) return false; /* prefer nested scrolling to dragging */
final int action = ev.getAction();
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
sheetDragHelper.cancel();
return false;
}
return isDraggableViewUnder((int) ev.getX(), (int) ev.getY())
&& (sheetDragHelper.shouldInterceptTouchEvent(ev));
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
sheetDragHelper.processTouchEvent(ev);
return sheetDragHelper.getCapturedView() != null || super.onTouchEvent(ev);
}
@Override
public void computeScroll() {
if (sheetDragHelper.continueSettling(true)) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
@Override
public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
if ((nestedScrollAxes & View.SCROLL_AXIS_VERTICAL) != 0) {
isNestedScrolling = true;
nestedScrollInitialTop = sheet.getTop();
return true;
}
return false;
}
@Override
public void onNestedScroll(View target, int dxConsumed, int dyConsumed,
int dxUnconsumed, int dyUnconsumed) {
// if scrolling downward, use any unconsumed (i.e. not used by the scrolling child)
// to drag the sheet downward
if (dyUnconsumed < 0) {
sheetOffsetHelper.offsetTopAndBottom(-dyUnconsumed);
dispatchPositionChangedCallback();
}
}
@Override
public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) {
// if scrolling upward & the sheet has been dragged downward
// then drag back into place before allowing scrolls
if (dy > 0) {
final int upwardDragRange = sheet.getTop() - sheetExpandedTop;
if (upwardDragRange > 0) {
final int consume = Math.min(upwardDragRange, dy);
sheetOffsetHelper.offsetTopAndBottom(-consume);
dispatchPositionChangedCallback();
consumed[1] = consume;
}
}
}
@Override
public void onStopNestedScroll(View child) {
isNestedScrolling = false;
if (!settling /* fling might have occurred */
&& sheet.getTop() != nestedScrollInitialTop) { /* don't expand after a tap */
expand();
}
}
@Override
public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
if (velocityY <= -SCALED_MIN_FLING_DISMISS_VELOCITY /* flinging downward */
&& !target.canScrollVertically(-1)) { /* nested scrolling child can't scroll up */
animateSettle(dismissOffset, velocityY);
return true;
} else if (velocityY > 0 && !isExpanded()) {
animateSettle(0, velocityY);
}
return false;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
sheetDragHelper = ViewDragHelper.create(this, dragHelperCallbacks);
}
private boolean isDraggableViewUnder(int x, int y) {
return getVisibility() == VISIBLE && sheetDragHelper.isViewUnder(this, x, y);
}
void animateSettle(int targetOffset, float initialVelocity) {
if (settling) return;
if (sheetOffsetHelper.getTopAndBottomOffset() == targetOffset) {
if (targetOffset >= dismissOffset) {
dispatchDismissCallback();
}
return;
}
settling = true;
final boolean dismissing = targetOffset == dismissOffset;
// if we're dismissing, we don't want the view to decelerate as it reaches the bottom
// so set a target position that actually overshoots a little
final float finalPosition = dismissing ? dismissOffset * 1.1f : targetOffset;
SpringAnimation anim = new SpringAnimation(
sheetOffsetHelper, ViewOffsetHelper.OFFSET_Y, finalPosition)
.setStartValue(sheetOffsetHelper.getTopAndBottomOffset())
.setStartVelocity(initialVelocity)
.setMinimumVisibleChange(DynamicAnimation.MIN_VISIBLE_CHANGE_PIXELS);
anim.getSpring()
.setStiffness(SETTLE_STIFFNESS)
.setDampingRatio(SpringForce.DAMPING_RATIO_NO_BOUNCY);
anim.addEndListener((animation, canceled, value, velocity) -> {
dispatchPositionChangedCallback();
if (dismissing) {
dispatchDismissCallback();
}
settling = false;
});
if (callbacks != null && !callbacks.isEmpty()) {
anim.addUpdateListener((animation, value, velocity) -> dispatchPositionChangedCallback());
}
anim.start();
}
private final ViewDragHelper.Callback dragHelperCallbacks = new ViewDragHelper.Callback() {
@Override
public boolean tryCaptureView(@NonNull View child, int pointerId) {
return child == sheet;
}
@Override
public int clampViewPositionVertical(@NonNull View child, int top, int dy) {
return Math.min(Math.max(top, sheetExpandedTop), sheetBottom);
}
@Override
public int clampViewPositionHorizontal(@NonNull View child, int left, int dx) {
return sheet.getLeft();
}
@Override
public int getViewVerticalDragRange(@NonNull View child) {
return sheetBottom - sheetExpandedTop;
}
@Override
public void onViewPositionChanged(@NonNull View child, int left, int top, int dx, int dy) {
// notify the offset helper that the sheets offsets have been changed externally
sheetOffsetHelper.resyncOffsets();
dispatchPositionChangedCallback();
}
@Override
public void onViewReleased(@NonNull View releasedChild, float velocityX, float velocityY) {
// dismiss on downward fling, otherwise settle back to expanded position
final boolean dismiss = velocityY >= SCALED_MIN_FLING_DISMISS_VELOCITY;
animateSettle(dismiss ? dismissOffset : 0, velocityY);
}
};
private final OnLayoutChangeListener sheetLayout = new OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
sheetExpandedTop = top;
sheetBottom = bottom;
dismissOffset = bottom - top;
sheetOffsetHelper.onViewLayout();
// modal bottom sheet content should not initially be taller than the 16:9 keyline
if (!initialHeightChecked) {
applySheetInitialHeightOffset(false, -1);
initialHeightChecked = true;
} else if (!hasInteractedWithSheet
&& (oldBottom - oldTop) != (bottom - top)) { /* sheet height changed */
/* if the sheet content's height changes before the user has interacted with it
then consider this still in the 'initial' state and apply the height constraint,
but in this case, animate to it */
applySheetInitialHeightOffset(true, oldTop - sheetExpandedTop);
}
}
};
void applySheetInitialHeightOffset(boolean animateChange, int previousOffset) {
final int minimumGap = sheet.getMeasuredWidth() / 16 * 9;
if (sheet.getTop() < minimumGap) {
final int offset = minimumGap - sheet.getTop();
if (animateChange) {
sheetOffsetHelper.setTopAndBottomOffset(previousOffset);
animateSettle(offset, 0);
} else {
sheetOffsetHelper.setTopAndBottomOffset(offset);
}
}
}
void dispatchDismissCallback() {
if (callbacks != null && !callbacks.isEmpty()) {
for (Callbacks callback : callbacks) {
callback.onSheetDismissed();
}
}
}
void dispatchPositionChangedCallback() {
if (callbacks != null && !callbacks.isEmpty()) {
for (Callbacks callback : callbacks) {
callback.onSheetPositionChanged(sheet.getTop(), hasInteractedWithSheet);
}
}
}
}
| False | 2,715 | 5 | 2,950 | 5 | 3,114 | 5 | 2,949 | 5 | 3,503 | 6 | false | false | false | false | false | true |
1,518 | 22110_3 | package fontys.observer;
import java.beans.*;
import java.rmi.RemoteException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2010</p>
*
* <p>Company: Fontys Hogeschool ICT</p>
*
* @author Frank Peeters
* @version 1.4 Usage of Publisher-interface is removed because this interface is
* Remote and objects of this class work locally within the same virtual
* machine;
*/
public class BasicPublisher implements RemotePublisher {
/**
* de listeners die onder de null-String staan geregistreerd zijn listeners
* die op alle properties zijn geabonneerd
*/
private HashMap<String, Set<RemotePropertyListener>> listenersTable;
/**
* als een listener zich bij een onbekende property registreert wordt de
* lijst met bekende properties in een RuntimeException meegegeven (zie
* codering checkInBehalfOfProgrammer)
*/
private String propertiesString;
/**
* er wordt een basicpublisher gecreeerd die voor de meegegeven properties
* remote propertylisteners kan registeren en hen op de hoogte zal houden in
* geval van wijziging; de basicpublisher houdt ook een lijstje met remote
* propertylisteners bij die zich op alle properties hebben geabonneerd.
*
* @param properties
*/
public BasicPublisher(String[] properties) {
listenersTable = new HashMap<>();
listenersTable.put(null, new HashSet<>());
for (String s : properties) {
listenersTable.put(s, new HashSet<>());
}
setPropertiesString();
}
/**
* listener abonneert zich op PropertyChangeEvent's zodra property is
* gewijzigd
*
* @param listener
* @param property mag null zijn, dan abonneert listener zich op alle
* properties; property moet wel een eigenschap zijn waarop je je kunt
* abonneren
*/
@Override
public void addListener(RemotePropertyListener listener, String property) {
checkInBehalfOfProgrammer(property);
listenersTable.get(property).add(listener);
}
/**
* het abonnement van listener voor PropertyChangeEvent's mbt property wordt
* opgezegd
*
* @param listener PropertyListener
* @param property mag null zijn, dan worden alle abonnementen van listener
* opgezegd
*/
@Override
public void removeListener(RemotePropertyListener listener, String property) {
if (property != null) {
Set<RemotePropertyListener> propertyListeners = listenersTable.get(property);
if (propertyListeners != null) {
propertyListeners.remove(listener);
listenersTable.get(null).remove(listener);
}
} else { //property == null, dus alle abonnementen van listener verwijderen
Set<String> keyset = listenersTable.keySet();
for (String key : keyset) {
listenersTable.get(key).remove(listener);
}
}
}
/**
* alle listeners voor property en de listeners met een algemeen abonnement
* krijgen een aanroep van propertyChange
*
* @param source de publisher
* @param property een geregistreerde eigenschap van de publisher (null is
* toegestaan, in dat geval krijgen alle listeners een aanroep van
* propertyChange)
* @param oldValue oorspronkelijke waarde van de property van de publisher
* (mag null zijn)
* @param newValue nieuwe waarde van de property van de publisher
*/
public void inform(Object source, String property, Object oldValue, Object newValue) {
checkInBehalfOfProgrammer(property);
Set<RemotePropertyListener> alertable;
alertable = listenersTable.get(property);
if (property != null) {
alertable.addAll(listenersTable.get(null));
} else {
Set<String> keyset = listenersTable.keySet();
for (String key : keyset) {
alertable.addAll(listenersTable.get(key));
}
}
for (RemotePropertyListener listener : alertable) {
PropertyChangeEvent evt = new PropertyChangeEvent(
source, property, oldValue, newValue);
try {
listener.propertyChange(evt);
} catch (RemoteException ex) {
removeListener(listener, null);
Logger.getLogger(BasicPublisher.class.getName()).log(Level.SEVERE, null, ex);
break;
}
}
}
/**
* property wordt alsnog bij publisher geregistreerd; voortaan kunnen alle
* propertylisteners zich op wijziging van deze property abonneren; als
* property al bij deze basicpublisher bekend is, verandert er niets
*
* @param property niet de lege string
*/
public void addProperty(String property) {
if (property.equals("")) {
throw new RuntimeException("a property cannot be an empty string");
}
if (listenersTable.containsKey(property)) {
return;
}
listenersTable.put(property, new HashSet<RemotePropertyListener>());
setPropertiesString();
}
/**
* property wordt bij publisher gederegistreerd; alle propertylisteners die
* zich op wijziging van deze property hadden geabonneerd worden voortaan
* niet meer op de hoogte gehouden; als property=null worden alle properties
* (ongelijk aan null) gederegistreerd;
*
* @param property is geregistreerde property bij deze basicpublisher
*/
public void removeProperty(String property) {
checkInBehalfOfProgrammer(property);
if (property != null) {
listenersTable.remove(property);
} else {
Set<String> keyset = listenersTable.keySet();
for (String key : keyset) {
if (key != null) {
listenersTable.remove(key);
}
}
}
setPropertiesString();
}
private void setPropertiesString() {
StringBuilder sb = new StringBuilder();
sb.append("{ ");
Iterator<String> it = listenersTable.keySet().iterator();
sb.append(it.next());
while (it.hasNext()) {
sb.append(", ").append(it.next());
}
sb.append(" }");
propertiesString = sb.toString();
}
private void checkInBehalfOfProgrammer(String property)
throws RuntimeException {
if (!listenersTable.containsKey(property)) {
throw new RuntimeException("property " + property + " is not a "
+ "published property, please make a choice out of: "
+ propertiesString);
}
}
/**
*
* @return alle properties inclusief de null-property
*/
public Iterator<String> getProperties() {
return listenersTable.keySet().iterator();
}
}
| SHEePYTaGGeRNeP/ProftaakS32B | BreakingPong/src/fontys/observer/BasicPublisher.java | 1,859 | /**
* er wordt een basicpublisher gecreeerd die voor de meegegeven properties
* remote propertylisteners kan registeren en hen op de hoogte zal houden in
* geval van wijziging; de basicpublisher houdt ook een lijstje met remote
* propertylisteners bij die zich op alle properties hebben geabonneerd.
*
* @param properties
*/ | block_comment | nl | package fontys.observer;
import java.beans.*;
import java.rmi.RemoteException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2010</p>
*
* <p>Company: Fontys Hogeschool ICT</p>
*
* @author Frank Peeters
* @version 1.4 Usage of Publisher-interface is removed because this interface is
* Remote and objects of this class work locally within the same virtual
* machine;
*/
public class BasicPublisher implements RemotePublisher {
/**
* de listeners die onder de null-String staan geregistreerd zijn listeners
* die op alle properties zijn geabonneerd
*/
private HashMap<String, Set<RemotePropertyListener>> listenersTable;
/**
* als een listener zich bij een onbekende property registreert wordt de
* lijst met bekende properties in een RuntimeException meegegeven (zie
* codering checkInBehalfOfProgrammer)
*/
private String propertiesString;
/**
* er wordt een<SUF>*/
public BasicPublisher(String[] properties) {
listenersTable = new HashMap<>();
listenersTable.put(null, new HashSet<>());
for (String s : properties) {
listenersTable.put(s, new HashSet<>());
}
setPropertiesString();
}
/**
* listener abonneert zich op PropertyChangeEvent's zodra property is
* gewijzigd
*
* @param listener
* @param property mag null zijn, dan abonneert listener zich op alle
* properties; property moet wel een eigenschap zijn waarop je je kunt
* abonneren
*/
@Override
public void addListener(RemotePropertyListener listener, String property) {
checkInBehalfOfProgrammer(property);
listenersTable.get(property).add(listener);
}
/**
* het abonnement van listener voor PropertyChangeEvent's mbt property wordt
* opgezegd
*
* @param listener PropertyListener
* @param property mag null zijn, dan worden alle abonnementen van listener
* opgezegd
*/
@Override
public void removeListener(RemotePropertyListener listener, String property) {
if (property != null) {
Set<RemotePropertyListener> propertyListeners = listenersTable.get(property);
if (propertyListeners != null) {
propertyListeners.remove(listener);
listenersTable.get(null).remove(listener);
}
} else { //property == null, dus alle abonnementen van listener verwijderen
Set<String> keyset = listenersTable.keySet();
for (String key : keyset) {
listenersTable.get(key).remove(listener);
}
}
}
/**
* alle listeners voor property en de listeners met een algemeen abonnement
* krijgen een aanroep van propertyChange
*
* @param source de publisher
* @param property een geregistreerde eigenschap van de publisher (null is
* toegestaan, in dat geval krijgen alle listeners een aanroep van
* propertyChange)
* @param oldValue oorspronkelijke waarde van de property van de publisher
* (mag null zijn)
* @param newValue nieuwe waarde van de property van de publisher
*/
public void inform(Object source, String property, Object oldValue, Object newValue) {
checkInBehalfOfProgrammer(property);
Set<RemotePropertyListener> alertable;
alertable = listenersTable.get(property);
if (property != null) {
alertable.addAll(listenersTable.get(null));
} else {
Set<String> keyset = listenersTable.keySet();
for (String key : keyset) {
alertable.addAll(listenersTable.get(key));
}
}
for (RemotePropertyListener listener : alertable) {
PropertyChangeEvent evt = new PropertyChangeEvent(
source, property, oldValue, newValue);
try {
listener.propertyChange(evt);
} catch (RemoteException ex) {
removeListener(listener, null);
Logger.getLogger(BasicPublisher.class.getName()).log(Level.SEVERE, null, ex);
break;
}
}
}
/**
* property wordt alsnog bij publisher geregistreerd; voortaan kunnen alle
* propertylisteners zich op wijziging van deze property abonneren; als
* property al bij deze basicpublisher bekend is, verandert er niets
*
* @param property niet de lege string
*/
public void addProperty(String property) {
if (property.equals("")) {
throw new RuntimeException("a property cannot be an empty string");
}
if (listenersTable.containsKey(property)) {
return;
}
listenersTable.put(property, new HashSet<RemotePropertyListener>());
setPropertiesString();
}
/**
* property wordt bij publisher gederegistreerd; alle propertylisteners die
* zich op wijziging van deze property hadden geabonneerd worden voortaan
* niet meer op de hoogte gehouden; als property=null worden alle properties
* (ongelijk aan null) gederegistreerd;
*
* @param property is geregistreerde property bij deze basicpublisher
*/
public void removeProperty(String property) {
checkInBehalfOfProgrammer(property);
if (property != null) {
listenersTable.remove(property);
} else {
Set<String> keyset = listenersTable.keySet();
for (String key : keyset) {
if (key != null) {
listenersTable.remove(key);
}
}
}
setPropertiesString();
}
private void setPropertiesString() {
StringBuilder sb = new StringBuilder();
sb.append("{ ");
Iterator<String> it = listenersTable.keySet().iterator();
sb.append(it.next());
while (it.hasNext()) {
sb.append(", ").append(it.next());
}
sb.append(" }");
propertiesString = sb.toString();
}
private void checkInBehalfOfProgrammer(String property)
throws RuntimeException {
if (!listenersTable.containsKey(property)) {
throw new RuntimeException("property " + property + " is not a "
+ "published property, please make a choice out of: "
+ propertiesString);
}
}
/**
*
* @return alle properties inclusief de null-property
*/
public Iterator<String> getProperties() {
return listenersTable.keySet().iterator();
}
}
| True | 1,506 | 89 | 1,608 | 95 | 1,671 | 82 | 1,608 | 95 | 1,869 | 97 | false | false | false | false | false | true |
2,896 | 25973_3 | package treeTraversal;_x000D_
_x000D_
// Klasse voor een knoop voor een binaire boom_x000D_
// Met boomwandelingen pre-order en level-order_x000D_
import java.util.*;_x000D_
_x000D_
public class BinNode<E> {_x000D_
_x000D_
private BinNode<E> parent, leftChild, rightChild;_x000D_
private E userObject;_x000D_
private static StringBuffer buffer;_x000D_
private Queue<BinNode<E>> q; // queue voor level-order wandeling_x000D_
_x000D_
public static final int LEFT = 0; // public constanten voor het _x000D_
public static final int RIGHT = 1; // toevoegen van linker- of rechterkind_x000D_
_x000D_
// Constructors_x000D_
public BinNode() {_x000D_
this(null);_x000D_
}_x000D_
_x000D_
public BinNode(E userObject) {_x000D_
parent = null;_x000D_
leftChild = null;_x000D_
rightChild = null;_x000D_
this.userObject = userObject;_x000D_
}_x000D_
_x000D_
public String preOrderToString() {_x000D_
buffer = new StringBuffer();_x000D_
preOrder(); // roep recursieve methode aan_x000D_
return buffer.toString();_x000D_
}_x000D_
_x000D_
private void preOrder() {_x000D_
buffer.append(userObject.toString()); //bezoek van de node_x000D_
if (leftChild != null) {_x000D_
leftChild.preOrder();_x000D_
}_x000D_
if (rightChild != null) {_x000D_
rightChild.preOrder();_x000D_
}_x000D_
}_x000D_
_x000D_
public String postOrderToString() {_x000D_
buffer = new StringBuffer();_x000D_
postOrder(); // roep recursieve methode aan_x000D_
return buffer.toString();_x000D_
}_x000D_
_x000D_
private void postOrder() {_x000D_
if (leftChild != null) {_x000D_
leftChild.postOrder();_x000D_
}_x000D_
if (rightChild != null) {_x000D_
rightChild.postOrder();_x000D_
}_x000D_
buffer.append(userObject.toString());_x000D_
}_x000D_
_x000D_
public String inOrderToString() {_x000D_
buffer = new StringBuffer();_x000D_
inOrder(); // roep recursieve methode aan_x000D_
return buffer.toString();_x000D_
}_x000D_
_x000D_
private void inOrder() {_x000D_
if (leftChild != null) {_x000D_
leftChild.inOrder();_x000D_
}_x000D_
buffer.append(userObject.toString());_x000D_
if (rightChild != null) {_x000D_
rightChild.inOrder();_x000D_
}_x000D_
}_x000D_
_x000D_
public String levelOrderToString() {_x000D_
buffer = new StringBuffer();_x000D_
q = new LinkedList<BinNode<E>>();_x000D_
q.add(this);_x000D_
levelOrder();_x000D_
return buffer.toString();_x000D_
}_x000D_
_x000D_
private void levelOrder() {_x000D_
while (!q.isEmpty()) {_x000D_
BinNode<E> knoop = q.remove();_x000D_
buffer.append(knoop.userObject.toString());_x000D_
if (knoop.leftChild != null) {_x000D_
q.add(knoop.leftChild);_x000D_
}_x000D_
if (knoop.rightChild != null) {_x000D_
q.add(knoop.rightChild);_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
public void add(BinNode<E> newChild) {_x000D_
if (leftChild == null) {_x000D_
insert(newChild, LEFT);_x000D_
} else if (rightChild == null) {_x000D_
insert(newChild, RIGHT);_x000D_
} else {_x000D_
throw new IllegalArgumentException(_x000D_
"Meer dan 2 kinderen");_x000D_
}_x000D_
}_x000D_
_x000D_
public E get() {_x000D_
return userObject;_x000D_
}_x000D_
_x000D_
public BinNode<E> getLeftChild() {_x000D_
return leftChild;_x000D_
}_x000D_
_x000D_
public BinNode<E> getRightChild() {_x000D_
return rightChild;_x000D_
}_x000D_
_x000D_
public BinNode<E> getParent() {_x000D_
return parent;_x000D_
}_x000D_
_x000D_
public void insert(BinNode<E> newChild, int childIndex) {_x000D_
if (isAncestor(newChild)) {_x000D_
throw new IllegalArgumentException(_x000D_
"Nieuw kind is voorouder");_x000D_
}_x000D_
if (childIndex != LEFT_x000D_
&& childIndex != RIGHT) {_x000D_
throw new IllegalArgumentException(_x000D_
"Index moet 0 of 1 zijn");_x000D_
}_x000D_
if (newChild != null) {_x000D_
BinNode<E> oldParent = newChild.getParent();_x000D_
if (oldParent != null) {_x000D_
oldParent.remove(newChild);_x000D_
}_x000D_
}_x000D_
newChild.parent = this;_x000D_
if (childIndex == LEFT) {_x000D_
leftChild = newChild;_x000D_
} else {_x000D_
rightChild = newChild;_x000D_
}_x000D_
}_x000D_
_x000D_
public boolean isChild(BinNode<E> aNode) {_x000D_
return aNode == null_x000D_
? false_x000D_
: aNode.getParent() == this;_x000D_
}_x000D_
_x000D_
public boolean isAncestor(BinNode<E> aNode) {_x000D_
BinNode<E> ancestor = this;_x000D_
while (ancestor != null && ancestor != aNode) {_x000D_
ancestor = ancestor.getParent();_x000D_
}_x000D_
return ancestor != null;_x000D_
}_x000D_
_x000D_
public void remove(BinNode<E> aChild) {_x000D_
if (aChild == null) {_x000D_
throw new IllegalArgumentException(_x000D_
"Argument is null");_x000D_
}_x000D_
_x000D_
if (!isChild(aChild)) {_x000D_
throw new IllegalArgumentException(_x000D_
"Argument is geen kind");_x000D_
}_x000D_
_x000D_
if (aChild == leftChild) {_x000D_
leftChild.parent = null;_x000D_
leftChild = null;_x000D_
} else {_x000D_
rightChild.parent = null;_x000D_
rightChild = null;_x000D_
}_x000D_
}_x000D_
_x000D_
public String toString() {_x000D_
return userObject.toString();_x000D_
}_x000D_
}_x000D_
| hanbioinformatica/owe6a | Week4_Trees/src/treeTraversal/BinNode.java | 1,407 | // public constanten voor het _x000D_ | line_comment | nl | package treeTraversal;_x000D_
_x000D_
// Klasse voor een knoop voor een binaire boom_x000D_
// Met boomwandelingen pre-order en level-order_x000D_
import java.util.*;_x000D_
_x000D_
public class BinNode<E> {_x000D_
_x000D_
private BinNode<E> parent, leftChild, rightChild;_x000D_
private E userObject;_x000D_
private static StringBuffer buffer;_x000D_
private Queue<BinNode<E>> q; // queue voor level-order wandeling_x000D_
_x000D_
public static final int LEFT = 0; // public constanten<SUF>
public static final int RIGHT = 1; // toevoegen van linker- of rechterkind_x000D_
_x000D_
// Constructors_x000D_
public BinNode() {_x000D_
this(null);_x000D_
}_x000D_
_x000D_
public BinNode(E userObject) {_x000D_
parent = null;_x000D_
leftChild = null;_x000D_
rightChild = null;_x000D_
this.userObject = userObject;_x000D_
}_x000D_
_x000D_
public String preOrderToString() {_x000D_
buffer = new StringBuffer();_x000D_
preOrder(); // roep recursieve methode aan_x000D_
return buffer.toString();_x000D_
}_x000D_
_x000D_
private void preOrder() {_x000D_
buffer.append(userObject.toString()); //bezoek van de node_x000D_
if (leftChild != null) {_x000D_
leftChild.preOrder();_x000D_
}_x000D_
if (rightChild != null) {_x000D_
rightChild.preOrder();_x000D_
}_x000D_
}_x000D_
_x000D_
public String postOrderToString() {_x000D_
buffer = new StringBuffer();_x000D_
postOrder(); // roep recursieve methode aan_x000D_
return buffer.toString();_x000D_
}_x000D_
_x000D_
private void postOrder() {_x000D_
if (leftChild != null) {_x000D_
leftChild.postOrder();_x000D_
}_x000D_
if (rightChild != null) {_x000D_
rightChild.postOrder();_x000D_
}_x000D_
buffer.append(userObject.toString());_x000D_
}_x000D_
_x000D_
public String inOrderToString() {_x000D_
buffer = new StringBuffer();_x000D_
inOrder(); // roep recursieve methode aan_x000D_
return buffer.toString();_x000D_
}_x000D_
_x000D_
private void inOrder() {_x000D_
if (leftChild != null) {_x000D_
leftChild.inOrder();_x000D_
}_x000D_
buffer.append(userObject.toString());_x000D_
if (rightChild != null) {_x000D_
rightChild.inOrder();_x000D_
}_x000D_
}_x000D_
_x000D_
public String levelOrderToString() {_x000D_
buffer = new StringBuffer();_x000D_
q = new LinkedList<BinNode<E>>();_x000D_
q.add(this);_x000D_
levelOrder();_x000D_
return buffer.toString();_x000D_
}_x000D_
_x000D_
private void levelOrder() {_x000D_
while (!q.isEmpty()) {_x000D_
BinNode<E> knoop = q.remove();_x000D_
buffer.append(knoop.userObject.toString());_x000D_
if (knoop.leftChild != null) {_x000D_
q.add(knoop.leftChild);_x000D_
}_x000D_
if (knoop.rightChild != null) {_x000D_
q.add(knoop.rightChild);_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
public void add(BinNode<E> newChild) {_x000D_
if (leftChild == null) {_x000D_
insert(newChild, LEFT);_x000D_
} else if (rightChild == null) {_x000D_
insert(newChild, RIGHT);_x000D_
} else {_x000D_
throw new IllegalArgumentException(_x000D_
"Meer dan 2 kinderen");_x000D_
}_x000D_
}_x000D_
_x000D_
public E get() {_x000D_
return userObject;_x000D_
}_x000D_
_x000D_
public BinNode<E> getLeftChild() {_x000D_
return leftChild;_x000D_
}_x000D_
_x000D_
public BinNode<E> getRightChild() {_x000D_
return rightChild;_x000D_
}_x000D_
_x000D_
public BinNode<E> getParent() {_x000D_
return parent;_x000D_
}_x000D_
_x000D_
public void insert(BinNode<E> newChild, int childIndex) {_x000D_
if (isAncestor(newChild)) {_x000D_
throw new IllegalArgumentException(_x000D_
"Nieuw kind is voorouder");_x000D_
}_x000D_
if (childIndex != LEFT_x000D_
&& childIndex != RIGHT) {_x000D_
throw new IllegalArgumentException(_x000D_
"Index moet 0 of 1 zijn");_x000D_
}_x000D_
if (newChild != null) {_x000D_
BinNode<E> oldParent = newChild.getParent();_x000D_
if (oldParent != null) {_x000D_
oldParent.remove(newChild);_x000D_
}_x000D_
}_x000D_
newChild.parent = this;_x000D_
if (childIndex == LEFT) {_x000D_
leftChild = newChild;_x000D_
} else {_x000D_
rightChild = newChild;_x000D_
}_x000D_
}_x000D_
_x000D_
public boolean isChild(BinNode<E> aNode) {_x000D_
return aNode == null_x000D_
? false_x000D_
: aNode.getParent() == this;_x000D_
}_x000D_
_x000D_
public boolean isAncestor(BinNode<E> aNode) {_x000D_
BinNode<E> ancestor = this;_x000D_
while (ancestor != null && ancestor != aNode) {_x000D_
ancestor = ancestor.getParent();_x000D_
}_x000D_
return ancestor != null;_x000D_
}_x000D_
_x000D_
public void remove(BinNode<E> aChild) {_x000D_
if (aChild == null) {_x000D_
throw new IllegalArgumentException(_x000D_
"Argument is null");_x000D_
}_x000D_
_x000D_
if (!isChild(aChild)) {_x000D_
throw new IllegalArgumentException(_x000D_
"Argument is geen kind");_x000D_
}_x000D_
_x000D_
if (aChild == leftChild) {_x000D_
leftChild.parent = null;_x000D_
leftChild = null;_x000D_
} else {_x000D_
rightChild.parent = null;_x000D_
rightChild = null;_x000D_
}_x000D_
}_x000D_
_x000D_
public String toString() {_x000D_
return userObject.toString();_x000D_
}_x000D_
}_x000D_
| True | 2,260 | 13 | 2,384 | 13 | 2,501 | 13 | 2,384 | 13 | 2,666 | 13 | false | false | false | false | false | true |
2,334 | 100588_2 | package Q17_13_ReSpace;_x000D_
_x000D_
import java.util.HashSet;_x000D_
_x000D_
import CtCILibrary.AssortedMethods;_x000D_
public class QuestionA { _x000D_
public static String bestSplit(HashSet<String> dictionary, String sentence) {_x000D_
ParseResult r = split(dictionary, sentence, 0);_x000D_
return r == null ? null : r.parsed;_x000D_
}_x000D_
_x000D_
public static ParseResult split(HashSet<String> dictionary, String sentence, int start) {_x000D_
if (start >= sentence.length()) {_x000D_
return new ParseResult(0, "");_x000D_
} _x000D_
_x000D_
int bestInvalid = Integer.MAX_VALUE;_x000D_
String bestParsing = null;_x000D_
_x000D_
String partial = "";_x000D_
int index = start;_x000D_
while (index < sentence.length()) {_x000D_
char c = sentence.charAt(index);_x000D_
partial += c;_x000D_
int invalid = dictionary.contains(partial) ? 0 : _x000D_
partial.length();_x000D_
if (invalid < bestInvalid) { // Short circuit_x000D_
/* Recurse, putting a space after this character. If this_x000D_
* is better than the current best option, replace the best_x000D_
* option. */_x000D_
ParseResult result = split(dictionary, sentence, index + 1);_x000D_
if (invalid + result.invalid < bestInvalid) {_x000D_
bestInvalid = invalid + result.invalid;_x000D_
bestParsing = partial + " " + result.parsed;_x000D_
if (bestInvalid == 0) break;_x000D_
}_x000D_
}_x000D_
_x000D_
index++;_x000D_
}_x000D_
return new ParseResult(bestInvalid, bestParsing);_x000D_
}_x000D_
_x000D_
_x000D_
public static String clean(String str) {_x000D_
char[] punctuation = {',', '"', '!', '.', '\'', '?', ','};_x000D_
for (char c : punctuation) {_x000D_
str = str.replace(c, ' ');_x000D_
}_x000D_
return str.replace(" ", "").toLowerCase();_x000D_
}_x000D_
_x000D_
public static void main(String[] args) {_x000D_
HashSet<String> dictionary = AssortedMethods.getWordListAsHashSet();_x000D_
String sentence = "As one of the top companies in the world, Google"; // will surely attract the attention of computer gurus. This does not, however, mean the company is for everyone.";_x000D_
sentence = clean(sentence);_x000D_
System.out.println(sentence);_x000D_
//Result v = parse(0, 0, new HashMap<Integer, Result>());_x000D_
//System.out.println(v.parsed);_x000D_
System.out.println(bestSplit(dictionary, sentence));_x000D_
}_x000D_
_x000D_
}_x000D_
| careercup/CtCI-6th-Edition | Java/Ch 17. Hard/Q17_13_ReSpace/QuestionA.java | 654 | //Result v = parse(0, 0, new HashMap<Integer, Result>());_x000D_ | line_comment | nl | package Q17_13_ReSpace;_x000D_
_x000D_
import java.util.HashSet;_x000D_
_x000D_
import CtCILibrary.AssortedMethods;_x000D_
public class QuestionA { _x000D_
public static String bestSplit(HashSet<String> dictionary, String sentence) {_x000D_
ParseResult r = split(dictionary, sentence, 0);_x000D_
return r == null ? null : r.parsed;_x000D_
}_x000D_
_x000D_
public static ParseResult split(HashSet<String> dictionary, String sentence, int start) {_x000D_
if (start >= sentence.length()) {_x000D_
return new ParseResult(0, "");_x000D_
} _x000D_
_x000D_
int bestInvalid = Integer.MAX_VALUE;_x000D_
String bestParsing = null;_x000D_
_x000D_
String partial = "";_x000D_
int index = start;_x000D_
while (index < sentence.length()) {_x000D_
char c = sentence.charAt(index);_x000D_
partial += c;_x000D_
int invalid = dictionary.contains(partial) ? 0 : _x000D_
partial.length();_x000D_
if (invalid < bestInvalid) { // Short circuit_x000D_
/* Recurse, putting a space after this character. If this_x000D_
* is better than the current best option, replace the best_x000D_
* option. */_x000D_
ParseResult result = split(dictionary, sentence, index + 1);_x000D_
if (invalid + result.invalid < bestInvalid) {_x000D_
bestInvalid = invalid + result.invalid;_x000D_
bestParsing = partial + " " + result.parsed;_x000D_
if (bestInvalid == 0) break;_x000D_
}_x000D_
}_x000D_
_x000D_
index++;_x000D_
}_x000D_
return new ParseResult(bestInvalid, bestParsing);_x000D_
}_x000D_
_x000D_
_x000D_
public static String clean(String str) {_x000D_
char[] punctuation = {',', '"', '!', '.', '\'', '?', ','};_x000D_
for (char c : punctuation) {_x000D_
str = str.replace(c, ' ');_x000D_
}_x000D_
return str.replace(" ", "").toLowerCase();_x000D_
}_x000D_
_x000D_
public static void main(String[] args) {_x000D_
HashSet<String> dictionary = AssortedMethods.getWordListAsHashSet();_x000D_
String sentence = "As one of the top companies in the world, Google"; // will surely attract the attention of computer gurus. This does not, however, mean the company is for everyone.";_x000D_
sentence = clean(sentence);_x000D_
System.out.println(sentence);_x000D_
//Result v<SUF>
//System.out.println(v.parsed);_x000D_
System.out.println(bestSplit(dictionary, sentence));_x000D_
}_x000D_
_x000D_
}_x000D_
| False | 907 | 25 | 1,004 | 25 | 1,007 | 25 | 1,002 | 25 | 1,127 | 26 | false | false | false | false | false | true |
4,490 | 69088_0 | import domain.*;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import javax.persistence.metamodel.EntityType;
import javax.persistence.metamodel.Metamodel;
import java.sql.SQLException;
import java.util.List;
/**
* Testklasse - deze klasse test alle andere klassen in deze package.
*
* System.out.println() is alleen in deze klasse toegestaan (behalve voor exceptions).
*
* @author [email protected]
*/
public class Main {
// Creëer een factory voor Hibernate sessions.
private static final SessionFactory factory;
static {
try {
// Create a Hibernate session factory
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
/**
* Retouneer een Hibernate session.
*
* @return Hibernate session
* @throws HibernateException
*/
private static Session getSession() throws HibernateException {
return factory.openSession();
}
public static void main(String[] args) throws SQLException {
testDAOHibernate();
}
/**
* P6. Haal alle (geannoteerde) entiteiten uit de database.
*/
private static void testFetchAll() {
Session session = getSession();
try {
Metamodel metamodel = session.getSessionFactory().getMetamodel();
for (EntityType<?> entityType : metamodel.getEntities()) {
Query query = session.createQuery("from " + entityType.getName());
System.out.println("[Test] Alle objecten van type " + entityType.getName() + " uit database:");
for (Object o : query.list()) {
System.out.println(" " + o);
}
System.out.println();
}
} finally {
session.close();
}
}
public static void testDAOHibernate() {
AdresDAOHibernate adao = new AdresDAOHibernate(getSession());
ReizigerDAOHibernate rdao = new ReizigerDAOHibernate(getSession());
OVChipkaartDAOHibernate odao = new OVChipkaartDAOHibernate(getSession());
ProductDAOHibernate pdao = new ProductDAOHibernate(getSession());
Reiziger reiziger = new Reiziger(15, "M", "", "Dol", java.sql.Date.valueOf("2001-02-03"));
Adres adres = new Adres(15, "2968GB", "15", "Waal", "Waal", 15);
OVChipkaart ovChipkaart = new OVChipkaart(11115, java.sql.Date.valueOf("2029-09-10"), 3, 1010.10f, 15);
Product product = new Product(15, "TEST DP7", "TEST PRODUCT VOOR DP7", 10.00f);
System.out.println("------ REIZIGER -----");
System.out.println("--- save + findAll ---");
System.out.println(rdao.findAll());
rdao.save(reiziger);
System.out.println(rdao.findAll());
System.out.println("--- update + findById ---");
System.out.println(rdao.findById(reiziger.getId()));
System.out.println("\n\n------ ADRES -----");
System.out.println("--- save + findAll ---");
System.out.println(adao.findAll());
adao.save(adres);
System.out.println(adao.findAll());
System.out.println("--- update + findByReiziger ---");
adres.setHuisnummer("15a");
adao.update(adres);
System.out.println(adao.findByReiziger(reiziger));
System.out.println("--- delete ---");
adao.delete(adres);
System.out.println(adao.findAll());
System.out.println("\n\n------ PRODUCT -----");
System.out.println("--- save + findAll ---");
System.out.println(pdao.findAll());
pdao.save(product);
System.out.println(pdao.findAll());
System.out.println("--- update ---");
product.setPrijs(20.00f);
System.out.println(pdao.findAll());
System.out.println("\n\n------ OVCHIPKAART + findByReiziger -----");
System.out.println("--- save ---");
odao.save(ovChipkaart);
System.out.println(odao.findByReiziger(reiziger));
System.out.println("--- update ---");
ovChipkaart.setSaldo(2020.20f);
odao.update(ovChipkaart);
System.out.println(odao.findByReiziger(reiziger));
// System.out.println("--- wijs product toe ---");
// ovChipkaart.getProductList().add(product);
// odao.update(ovChipkaart);
// System.out.println(odao.findByReiziger(reiziger));
System.out.println("\n\n----- DELETE ALLE -----");
System.out.println("--- delete ovchipkaart ---");
odao.delete(ovChipkaart);
System.out.println("--- delete product ---");
pdao.delete(product);
System.out.println(pdao.findAll());
System.out.println("---- delete reiziger ----");
rdao.delete(reiziger);
System.out.println(rdao.findById(reiziger.getId()));
}
}
| thijmon/hibernateDAO | src/main/java/Main.java | 1,592 | /**
* Testklasse - deze klasse test alle andere klassen in deze package.
*
* System.out.println() is alleen in deze klasse toegestaan (behalve voor exceptions).
*
* @author [email protected]
*/ | block_comment | nl | import domain.*;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import javax.persistence.metamodel.EntityType;
import javax.persistence.metamodel.Metamodel;
import java.sql.SQLException;
import java.util.List;
/**
* Testklasse - deze<SUF>*/
public class Main {
// Creëer een factory voor Hibernate sessions.
private static final SessionFactory factory;
static {
try {
// Create a Hibernate session factory
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
/**
* Retouneer een Hibernate session.
*
* @return Hibernate session
* @throws HibernateException
*/
private static Session getSession() throws HibernateException {
return factory.openSession();
}
public static void main(String[] args) throws SQLException {
testDAOHibernate();
}
/**
* P6. Haal alle (geannoteerde) entiteiten uit de database.
*/
private static void testFetchAll() {
Session session = getSession();
try {
Metamodel metamodel = session.getSessionFactory().getMetamodel();
for (EntityType<?> entityType : metamodel.getEntities()) {
Query query = session.createQuery("from " + entityType.getName());
System.out.println("[Test] Alle objecten van type " + entityType.getName() + " uit database:");
for (Object o : query.list()) {
System.out.println(" " + o);
}
System.out.println();
}
} finally {
session.close();
}
}
public static void testDAOHibernate() {
AdresDAOHibernate adao = new AdresDAOHibernate(getSession());
ReizigerDAOHibernate rdao = new ReizigerDAOHibernate(getSession());
OVChipkaartDAOHibernate odao = new OVChipkaartDAOHibernate(getSession());
ProductDAOHibernate pdao = new ProductDAOHibernate(getSession());
Reiziger reiziger = new Reiziger(15, "M", "", "Dol", java.sql.Date.valueOf("2001-02-03"));
Adres adres = new Adres(15, "2968GB", "15", "Waal", "Waal", 15);
OVChipkaart ovChipkaart = new OVChipkaart(11115, java.sql.Date.valueOf("2029-09-10"), 3, 1010.10f, 15);
Product product = new Product(15, "TEST DP7", "TEST PRODUCT VOOR DP7", 10.00f);
System.out.println("------ REIZIGER -----");
System.out.println("--- save + findAll ---");
System.out.println(rdao.findAll());
rdao.save(reiziger);
System.out.println(rdao.findAll());
System.out.println("--- update + findById ---");
System.out.println(rdao.findById(reiziger.getId()));
System.out.println("\n\n------ ADRES -----");
System.out.println("--- save + findAll ---");
System.out.println(adao.findAll());
adao.save(adres);
System.out.println(adao.findAll());
System.out.println("--- update + findByReiziger ---");
adres.setHuisnummer("15a");
adao.update(adres);
System.out.println(adao.findByReiziger(reiziger));
System.out.println("--- delete ---");
adao.delete(adres);
System.out.println(adao.findAll());
System.out.println("\n\n------ PRODUCT -----");
System.out.println("--- save + findAll ---");
System.out.println(pdao.findAll());
pdao.save(product);
System.out.println(pdao.findAll());
System.out.println("--- update ---");
product.setPrijs(20.00f);
System.out.println(pdao.findAll());
System.out.println("\n\n------ OVCHIPKAART + findByReiziger -----");
System.out.println("--- save ---");
odao.save(ovChipkaart);
System.out.println(odao.findByReiziger(reiziger));
System.out.println("--- update ---");
ovChipkaart.setSaldo(2020.20f);
odao.update(ovChipkaart);
System.out.println(odao.findByReiziger(reiziger));
// System.out.println("--- wijs product toe ---");
// ovChipkaart.getProductList().add(product);
// odao.update(ovChipkaart);
// System.out.println(odao.findByReiziger(reiziger));
System.out.println("\n\n----- DELETE ALLE -----");
System.out.println("--- delete ovchipkaart ---");
odao.delete(ovChipkaart);
System.out.println("--- delete product ---");
pdao.delete(product);
System.out.println(pdao.findAll());
System.out.println("---- delete reiziger ----");
rdao.delete(reiziger);
System.out.println(rdao.findById(reiziger.getId()));
}
}
| True | 1,135 | 56 | 1,355 | 65 | 1,382 | 58 | 1,355 | 65 | 1,592 | 66 | false | false | false | false | false | true |
779 | 23529_0 | package usb14.themeCourse.ee.application;
import java.util.SortedMap;
import java.util.TreeMap;
import usb14.themeCourse.ee.framework.Appliance;
import usb14.themeCourse.ee.framework.Controller;
import usb14.themeCourse.ee.framework.CostFunction;
public class Fridge extends Appliance{
public enum State {
ON, OFF
}
private State state;
private double temp;
private int time;
private int currentPrice;
private final int usage = 200;
private final int maxCost = CostFunction.MAX_COST;
// Constructor
public Fridge(String name) {
super(name);
this.state = State.OFF;
this.temp = 4;
this.time = 0;
SortedMap<Integer, Integer> function = new TreeMap<Integer, Integer>();
function.put(usage, 0);
super.setCostFunction(new CostFunction(function));
updateCostFunction();
}
// Queries
@Override
public int getCurrentUsage() {
return super.getCostFunction().getDemandByCost(currentPrice);
}
public State getState() {
return state;
}
public double getTemp(){
return temp;
}
// Commands
private void updateCostFunction(){
int cost;
if(time > 0 && time < 20)
cost = maxCost;
else
// Met deze functie zou de temperatuur tussen 3 en 7 graden moeten schommelen.
// Bij een prijs van 500 blijkt het tussen de 4 en 5 te blijven, dus er is wat
// marge om warmer of kouder te worden bij een hogere of lagere energieprijs.
cost = (int) Math.round(((temp-3.0)/4.0) * (float)maxCost);
if (cost < 0 ) cost = 0;
super.getCostFunction().updateCostForDemand(cost, usage);
}
@Override
public void updateState(){
int t = Controller.getInstance().getIntervalDuration();
// update temperature and time running
if(this.state == State.ON){
temp -= 0.05*t;
this.time += t;
} else {
temp += 0.025*t;
this.time = 0;
}
// update costfunction based on the new temperature and time running
this.updateCostFunction();
}
@Override
public void updatePrice(int price){
this.currentPrice = price;
// update state based on the current price
if(getCurrentUsage() == 0)
this.state = State.OFF;
else
this.state = State.ON;
setChanged();
notifyObservers();
}
}
| JElsinga/ThemeCourse | Framework/src/usb14/themeCourse/ee/application/Fridge.java | 774 | // Met deze functie zou de temperatuur tussen 3 en 7 graden moeten schommelen. | line_comment | nl | package usb14.themeCourse.ee.application;
import java.util.SortedMap;
import java.util.TreeMap;
import usb14.themeCourse.ee.framework.Appliance;
import usb14.themeCourse.ee.framework.Controller;
import usb14.themeCourse.ee.framework.CostFunction;
public class Fridge extends Appliance{
public enum State {
ON, OFF
}
private State state;
private double temp;
private int time;
private int currentPrice;
private final int usage = 200;
private final int maxCost = CostFunction.MAX_COST;
// Constructor
public Fridge(String name) {
super(name);
this.state = State.OFF;
this.temp = 4;
this.time = 0;
SortedMap<Integer, Integer> function = new TreeMap<Integer, Integer>();
function.put(usage, 0);
super.setCostFunction(new CostFunction(function));
updateCostFunction();
}
// Queries
@Override
public int getCurrentUsage() {
return super.getCostFunction().getDemandByCost(currentPrice);
}
public State getState() {
return state;
}
public double getTemp(){
return temp;
}
// Commands
private void updateCostFunction(){
int cost;
if(time > 0 && time < 20)
cost = maxCost;
else
// Met deze<SUF>
// Bij een prijs van 500 blijkt het tussen de 4 en 5 te blijven, dus er is wat
// marge om warmer of kouder te worden bij een hogere of lagere energieprijs.
cost = (int) Math.round(((temp-3.0)/4.0) * (float)maxCost);
if (cost < 0 ) cost = 0;
super.getCostFunction().updateCostForDemand(cost, usage);
}
@Override
public void updateState(){
int t = Controller.getInstance().getIntervalDuration();
// update temperature and time running
if(this.state == State.ON){
temp -= 0.05*t;
this.time += t;
} else {
temp += 0.025*t;
this.time = 0;
}
// update costfunction based on the new temperature and time running
this.updateCostFunction();
}
@Override
public void updatePrice(int price){
this.currentPrice = price;
// update state based on the current price
if(getCurrentUsage() == 0)
this.state = State.OFF;
else
this.state = State.ON;
setChanged();
notifyObservers();
}
}
| True | 607 | 23 | 727 | 29 | 738 | 19 | 727 | 29 | 852 | 24 | false | false | false | false | false | true |
316 | 82214_8 | /*
* Copyright (C) 2012-2019 Jorrit "Chainfire" Jongma
*
* 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 eu.chainfire.libsuperuser;
import android.content.Context;
import android.os.Handler;
import android.widget.Toast;
import androidx.annotation.AnyThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/**
* Base application class to extend from, solving some issues with
* toasts and AsyncTasks you are likely to run into
*/
@SuppressWarnings("WeakerAccess")
public class Application extends android.app.Application {
/**
* Shows a toast message
*
* @param context Any context belonging to this application
* @param message The message to show
*/
@AnyThread
public static void toast(@Nullable Context context, @NonNull String message) {
// this is a static method so it is easier to call,
// as the context checking and casting is done for you
if (context == null) return;
if (!(context instanceof Application)) {
context = context.getApplicationContext();
}
if (context instanceof Application) {
final Context c = context;
final String m = message;
((Application) context).runInApplicationThread(new Runnable() {
@Override
public void run() {
Toast.makeText(c, m, Toast.LENGTH_LONG).show();
}
});
}
}
private static final Handler mApplicationHandler = new Handler();
/**
* Run a runnable in the main application thread
*
* @param r Runnable to run
*/
@AnyThread
public void runInApplicationThread(@NonNull Runnable r) {
mApplicationHandler.post(r);
}
@Override
public void onCreate() {
super.onCreate();
try {
// workaround bug in AsyncTask, can show up (for example) when you toast from a service
// this makes sure AsyncTask's internal handler is created from the right (main) thread
Class.forName("android.os.AsyncTask");
} catch (ClassNotFoundException e) {
// will never happen
}
}
}
| Chainfire/libsuperuser | libsuperuser/src/eu/chainfire/libsuperuser/Application.java | 689 | // will never happen | line_comment | nl | /*
* Copyright (C) 2012-2019 Jorrit "Chainfire" Jongma
*
* 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 eu.chainfire.libsuperuser;
import android.content.Context;
import android.os.Handler;
import android.widget.Toast;
import androidx.annotation.AnyThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/**
* Base application class to extend from, solving some issues with
* toasts and AsyncTasks you are likely to run into
*/
@SuppressWarnings("WeakerAccess")
public class Application extends android.app.Application {
/**
* Shows a toast message
*
* @param context Any context belonging to this application
* @param message The message to show
*/
@AnyThread
public static void toast(@Nullable Context context, @NonNull String message) {
// this is a static method so it is easier to call,
// as the context checking and casting is done for you
if (context == null) return;
if (!(context instanceof Application)) {
context = context.getApplicationContext();
}
if (context instanceof Application) {
final Context c = context;
final String m = message;
((Application) context).runInApplicationThread(new Runnable() {
@Override
public void run() {
Toast.makeText(c, m, Toast.LENGTH_LONG).show();
}
});
}
}
private static final Handler mApplicationHandler = new Handler();
/**
* Run a runnable in the main application thread
*
* @param r Runnable to run
*/
@AnyThread
public void runInApplicationThread(@NonNull Runnable r) {
mApplicationHandler.post(r);
}
@Override
public void onCreate() {
super.onCreate();
try {
// workaround bug in AsyncTask, can show up (for example) when you toast from a service
// this makes sure AsyncTask's internal handler is created from the right (main) thread
Class.forName("android.os.AsyncTask");
} catch (ClassNotFoundException e) {
// will never<SUF>
}
}
}
| False | 553 | 4 | 602 | 4 | 643 | 4 | 602 | 4 | 713 | 4 | false | false | false | false | false | true |
331 | 18966_0 | package com.groep15.amazonsim.models.worldobject;
/*
* Deze interface beschrijft wat een onderdeel van het model moet kunnen om deze
* te kunnen updaten. In de lijst met objecten in de wereld (zie class World) zitten
* objecten die geupdate kunnen worden. Er wordt gecontroleerd of een object deze
* interface implementeerd. Als dat zo is, wordt het object geupdate wanneer de
* wereld update.
*/
public interface Updatable {
boolean update();
} | ClawmanCat/WarehouseSim | src/main/java/com/groep15/amazonsim/models/worldobject/Updatable.java | 125 | /*
* Deze interface beschrijft wat een onderdeel van het model moet kunnen om deze
* te kunnen updaten. In de lijst met objecten in de wereld (zie class World) zitten
* objecten die geupdate kunnen worden. Er wordt gecontroleerd of een object deze
* interface implementeerd. Als dat zo is, wordt het object geupdate wanneer de
* wereld update.
*/ | block_comment | nl | package com.groep15.amazonsim.models.worldobject;
/*
* Deze interface beschrijft<SUF>*/
public interface Updatable {
boolean update();
} | True | 115 | 90 | 132 | 101 | 114 | 85 | 132 | 101 | 126 | 92 | false | false | false | false | false | true |
2,471 | 38235_25 | /**
*
*/
package salas.vos;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import common.Constants;
import common.util.DateUtils;
import common.vos.BaseVO;
import common.vos.IKeyValue;
/**
* @author Iecisa
* @version $Revision$
*
*/
public class UsuarioSalasConsultaVO extends BaseVO implements IKeyValue {
private static final long serialVersionUID = 1L;
private String id;
private Integer tipoDocIdentificacion;
private String numDocIdentificacion;
private String nombre;
private String apellidos;
private String nacionalidad;
private String telefonos;
private String email;
private String direccion;
private Date fechaAlta;
private String vigente;
private String idscausr;
private String nombreCompletoUsuarioAplicacion;
/**
* Lista de Archivos a los que pertenece el usuario
*/
private List listaArchivos = new ArrayList();
/**
* Archivos a los que pertenece el usuario.
*/
private String[] idsArchivos = new String[0];
private String nombreArchivo;
private String nombreTema;
/**
* @return el id
*/
public String getId() {
return id;
}
/**
* @param id
* el id a fijar
*/
public void setId(String id) {
this.id = id;
}
/**
* @return el tipoDocIdentificacion
*/
public Integer getTipoDocIdentificacion() {
return tipoDocIdentificacion;
}
/**
* @param tipoDocIdentificacion
* el tipoDocIdentificacion a fijar
*/
public void setTipoDocIdentificacion(Integer tipoDocIdentificacion) {
this.tipoDocIdentificacion = tipoDocIdentificacion;
}
/**
* @return el numDocIdentificacion
*/
public String getNumDocIdentificacion() {
return numDocIdentificacion;
}
/**
* @param numDocIdentificacion
* el numDocIdentificacion a fijar
*/
public void setNumDocIdentificacion(String numDocIdentificacion) {
this.numDocIdentificacion = numDocIdentificacion;
}
/**
* @return el nombre
*/
public String getNombre() {
return nombre;
}
/**
* @param nombre
* el nombre a fijar
*/
public void setNombre(String nombre) {
this.nombre = nombre;
}
/**
* @return el apellidos
*/
public String getApellidos() {
return apellidos;
}
/**
* @param apellidos
* el apellidos a fijar
*/
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}
/**
* @return el nacionalidad
*/
public String getNacionalidad() {
return nacionalidad;
}
/**
* @param nacionalidad
* el nacionalidad a fijar
*/
public void setNacionalidad(String nacionalidad) {
this.nacionalidad = nacionalidad;
}
/**
* @return el telefonos
*/
public String getTelefonos() {
return telefonos;
}
/**
* @param telefonos
* el telefonos a fijar
*/
public void setTelefonos(String telefonos) {
this.telefonos = telefonos;
}
/**
* @return el email
*/
public String getEmail() {
return email;
}
/**
* @param email
* el email a fijar
*/
public void setEmail(String email) {
this.email = email;
}
/**
* @return el direccion
*/
public String getDireccion() {
return direccion;
}
/**
* @param direccion
* el direccion a fijar
*/
public void setDireccion(String direccion) {
this.direccion = direccion;
}
/**
* @return el fAlta
*/
public Date getFechaAlta() {
return fechaAlta;
}
/**
* @return el fAlta
*/
public String getFechaAltaString() {
return DateUtils.formatDate(fechaAlta);
}
/**
* @param fAlta
* el fAlta a fijar
*/
public void setFechaAlta(Date fechaAlta) {
this.fechaAlta = fechaAlta;
}
/**
* @return el vigente
*/
public String getVigente() {
return vigente;
}
/**
* @param vigente
* el vigente a fijar
*/
public void setVigente(String vigente) {
this.vigente = vigente;
}
/**
* @return el idscausr
*/
public String getIdscausr() {
return idscausr;
}
/**
* @param idscausr
* el idscausr a fijar
*/
public void setIdscausr(String idscausr) {
this.idscausr = idscausr;
}
public void setListaArchivos(List listaArchivos) {
this.listaArchivos = listaArchivos;
}
public List getListaArchivos() {
return listaArchivos;
}
public void setIdsArchivos(String[] idsArchivos) {
this.idsArchivos = idsArchivos;
}
public String[] getIdsArchivos() {
return idsArchivos;
}
public void setNombreCompletoUsuarioAplicacion(
String nombreCompletoUsuarioAplicacion) {
this.nombreCompletoUsuarioAplicacion = nombreCompletoUsuarioAplicacion;
}
public String getNombreCompletoUsuarioAplicacion() {
return nombreCompletoUsuarioAplicacion;
}
public String getNombreArchivo() {
return nombreArchivo;
}
public void setNombreArchivo(String nombreArchivo) {
this.nombreArchivo = nombreArchivo;
}
public String getNombreTema() {
return nombreTema;
}
public void setNombreTema(String nombreTema) {
this.nombreTema = nombreTema;
}
public String getNombreCompleto() {
StringBuffer nombreCompleto = new StringBuffer("");
if (StringUtils.isNotBlank(apellidos))
nombreCompleto.append(getApellidos()).append(", ");
if (StringUtils.isNotBlank(nombre)) {
nombreCompleto.append(getNombre());
}
return nombreCompleto.toString();
}
/**
* {@inheritDoc}
*
* @see common.vos.IKeyValue#getKey()
*/
public String getKey() {
if (StringUtils.isNotBlank(this.id)) {
return this.id;
} else {
return Constants.STRING_EMPTY;
}
}
/**
* {@inheritDoc}
*
* @see common.vos.IKeyValue#getValue()
*/
public String getValue() {
return getNombreCompleto();
}
}
| ctt-gob-es/SIGM-Community | archivo/archidoc/src/main/java/salas/vos/UsuarioSalasConsultaVO.java | 2,013 | /**
* @param vigente
* el vigente a fijar
*/ | block_comment | nl | /**
*
*/
package salas.vos;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import common.Constants;
import common.util.DateUtils;
import common.vos.BaseVO;
import common.vos.IKeyValue;
/**
* @author Iecisa
* @version $Revision$
*
*/
public class UsuarioSalasConsultaVO extends BaseVO implements IKeyValue {
private static final long serialVersionUID = 1L;
private String id;
private Integer tipoDocIdentificacion;
private String numDocIdentificacion;
private String nombre;
private String apellidos;
private String nacionalidad;
private String telefonos;
private String email;
private String direccion;
private Date fechaAlta;
private String vigente;
private String idscausr;
private String nombreCompletoUsuarioAplicacion;
/**
* Lista de Archivos a los que pertenece el usuario
*/
private List listaArchivos = new ArrayList();
/**
* Archivos a los que pertenece el usuario.
*/
private String[] idsArchivos = new String[0];
private String nombreArchivo;
private String nombreTema;
/**
* @return el id
*/
public String getId() {
return id;
}
/**
* @param id
* el id a fijar
*/
public void setId(String id) {
this.id = id;
}
/**
* @return el tipoDocIdentificacion
*/
public Integer getTipoDocIdentificacion() {
return tipoDocIdentificacion;
}
/**
* @param tipoDocIdentificacion
* el tipoDocIdentificacion a fijar
*/
public void setTipoDocIdentificacion(Integer tipoDocIdentificacion) {
this.tipoDocIdentificacion = tipoDocIdentificacion;
}
/**
* @return el numDocIdentificacion
*/
public String getNumDocIdentificacion() {
return numDocIdentificacion;
}
/**
* @param numDocIdentificacion
* el numDocIdentificacion a fijar
*/
public void setNumDocIdentificacion(String numDocIdentificacion) {
this.numDocIdentificacion = numDocIdentificacion;
}
/**
* @return el nombre
*/
public String getNombre() {
return nombre;
}
/**
* @param nombre
* el nombre a fijar
*/
public void setNombre(String nombre) {
this.nombre = nombre;
}
/**
* @return el apellidos
*/
public String getApellidos() {
return apellidos;
}
/**
* @param apellidos
* el apellidos a fijar
*/
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}
/**
* @return el nacionalidad
*/
public String getNacionalidad() {
return nacionalidad;
}
/**
* @param nacionalidad
* el nacionalidad a fijar
*/
public void setNacionalidad(String nacionalidad) {
this.nacionalidad = nacionalidad;
}
/**
* @return el telefonos
*/
public String getTelefonos() {
return telefonos;
}
/**
* @param telefonos
* el telefonos a fijar
*/
public void setTelefonos(String telefonos) {
this.telefonos = telefonos;
}
/**
* @return el email
*/
public String getEmail() {
return email;
}
/**
* @param email
* el email a fijar
*/
public void setEmail(String email) {
this.email = email;
}
/**
* @return el direccion
*/
public String getDireccion() {
return direccion;
}
/**
* @param direccion
* el direccion a fijar
*/
public void setDireccion(String direccion) {
this.direccion = direccion;
}
/**
* @return el fAlta
*/
public Date getFechaAlta() {
return fechaAlta;
}
/**
* @return el fAlta
*/
public String getFechaAltaString() {
return DateUtils.formatDate(fechaAlta);
}
/**
* @param fAlta
* el fAlta a fijar
*/
public void setFechaAlta(Date fechaAlta) {
this.fechaAlta = fechaAlta;
}
/**
* @return el vigente
*/
public String getVigente() {
return vigente;
}
/**
* @param vigente
<SUF>*/
public void setVigente(String vigente) {
this.vigente = vigente;
}
/**
* @return el idscausr
*/
public String getIdscausr() {
return idscausr;
}
/**
* @param idscausr
* el idscausr a fijar
*/
public void setIdscausr(String idscausr) {
this.idscausr = idscausr;
}
public void setListaArchivos(List listaArchivos) {
this.listaArchivos = listaArchivos;
}
public List getListaArchivos() {
return listaArchivos;
}
public void setIdsArchivos(String[] idsArchivos) {
this.idsArchivos = idsArchivos;
}
public String[] getIdsArchivos() {
return idsArchivos;
}
public void setNombreCompletoUsuarioAplicacion(
String nombreCompletoUsuarioAplicacion) {
this.nombreCompletoUsuarioAplicacion = nombreCompletoUsuarioAplicacion;
}
public String getNombreCompletoUsuarioAplicacion() {
return nombreCompletoUsuarioAplicacion;
}
public String getNombreArchivo() {
return nombreArchivo;
}
public void setNombreArchivo(String nombreArchivo) {
this.nombreArchivo = nombreArchivo;
}
public String getNombreTema() {
return nombreTema;
}
public void setNombreTema(String nombreTema) {
this.nombreTema = nombreTema;
}
public String getNombreCompleto() {
StringBuffer nombreCompleto = new StringBuffer("");
if (StringUtils.isNotBlank(apellidos))
nombreCompleto.append(getApellidos()).append(", ");
if (StringUtils.isNotBlank(nombre)) {
nombreCompleto.append(getNombre());
}
return nombreCompleto.toString();
}
/**
* {@inheritDoc}
*
* @see common.vos.IKeyValue#getKey()
*/
public String getKey() {
if (StringUtils.isNotBlank(this.id)) {
return this.id;
} else {
return Constants.STRING_EMPTY;
}
}
/**
* {@inheritDoc}
*
* @see common.vos.IKeyValue#getValue()
*/
public String getValue() {
return getNombreCompleto();
}
}
| False | 1,498 | 21 | 1,823 | 21 | 1,732 | 18 | 1,823 | 21 | 2,106 | 22 | false | false | false | false | false | true |
1,042 | 69555_5 | package be.domino;
import java.util.ArrayList;
import java.util.Optional;
/**
* @author Maarten Gielkens
* Ik heb ongeveer 12 uur gewerkt aan deze taak.
*/
public class Algoritme {
/**
* Methode die de ketting maakt en recursief kan worden opgeroepen.
* @param stenen De ArrayList van de stenen die meegegeven worden door de main
* @param geplaatsteStenen De stenen waarin de ketting wordt gelegd
* @param steenNummer De index die bijhoudt welke steen uit de originele lijst moeten geprobeerd toe te voegen
* @param aantalBacktracks Het aantal stenen die terug verwijderd zijn met backtracken
* @param volledigeBacktracks Het aantal keer dat het algoritme een nieuwe steen vooraan legt
* @return Recursief maakKetting opnieuw oproepen
*/
public Optional<ArrayList<Steen>> maakKetting(ArrayList<Steen> stenen, ArrayList<Steen> geplaatsteStenen, int steenNummer, int aantalBacktracks, int volledigeBacktracks) {
Steen huidigeSteen;
//controle die zorgt dat het algoritme stopt wanneer alle stenen op de eerste plaats hebben gelegen.
if (volledigeBacktracks > stenen.size() + geplaatsteStenen.size()) {
if(controleerSteen(geplaatsteStenen.get(geplaatsteStenen.size() - 1), geplaatsteStenen.get(0))) {
return Optional.of(geplaatsteStenen);
}
else {
return Optional.empty();
}
}
//Controle die zorgt dat het algoritme stopt wanneer alle te plaatsen stenen zijn opgebruikt
if (stenen.size() == 0) {
if(controleerSteen(geplaatsteStenen.get(geplaatsteStenen.size() - 1), geplaatsteStenen.get(0))) {
return Optional.of(geplaatsteStenen);
}
else {
return Optional.empty();
}
}
huidigeSteen = stenen.get(steenNummer);
//Vult de lege lijst met geplaatste stenen aan met het eerste element van de te plaatsen stenen.
if (geplaatsteStenen.isEmpty()) {
stenen.remove(huidigeSteen);
geplaatsteStenen.add(huidigeSteen);
return maakKetting(stenen, geplaatsteStenen, steenNummer, 0, volledigeBacktracks + 1);
}
Steen vorigeSteen = geplaatsteStenen.get(geplaatsteStenen.size()-1);
//Controleert als de volgende steen kan toegevoegd worden en doet dit ook indien mogelijk.
if (controleerSteen(vorigeSteen, huidigeSteen)) {
stenen.remove(steenNummer);
geplaatsteStenen.add(huidigeSteen);
steenNummer = 0;
return maakKetting(stenen, geplaatsteStenen, steenNummer, aantalBacktracks, volledigeBacktracks);
}
//Als er niet meer kan worden bijgeplaatst dan begint het volgende stuk met backtracken
else if (stenen.size() -1 - aantalBacktracks <= steenNummer){
if(controleerSteen(geplaatsteStenen.get(geplaatsteStenen.size() - 1), geplaatsteStenen.get(0))) {
return Optional.of(geplaatsteStenen);
}
controleerSteen(geplaatsteStenen.get(geplaatsteStenen.size() - 1), geplaatsteStenen.get(0));
geplaatsteStenen.remove(vorigeSteen);
stenen.add(vorigeSteen);
aantalBacktracks += 1;
return maakKetting(stenen, geplaatsteStenen, 0, aantalBacktracks, volledigeBacktracks);
}
else{
return maakKetting(stenen, geplaatsteStenen, steenNummer + 1, aantalBacktracks, volledigeBacktracks);
}
}
/**
* Methode die controleert als 2 stenen langs elkaar kunnen liggen, indien een steen geflipt moet worden dan doet deze methode dat ook.
* @param steen1 De eerste steen die gecontroleerd moet worden.
* @param steen2 De tweede steen die gecontroleerd moet worden
* @return Boolean om aan te geven als de stenen achter elkaar gelegd kunnen worden of niet.
*/
public boolean controleerSteen(Steen steen1, Steen steen2) {
if (steen1.getKleur() == steen2.getKleur()) {
return false;
}
if(steen1.getOgen2() != steen2.getOgen1()) {
if(steen1.getOgen2() == steen2.getOgen2()) {
steen2.flip();
return true;
}
else return false;
}
return true;
}
} | MaartenG18/TaakBacktracking | GielkensMaarten/src/main/java/be/domino/Algoritme.java | 1,424 | //Controleert als de volgende steen kan toegevoegd worden en doet dit ook indien mogelijk. | line_comment | nl | package be.domino;
import java.util.ArrayList;
import java.util.Optional;
/**
* @author Maarten Gielkens
* Ik heb ongeveer 12 uur gewerkt aan deze taak.
*/
public class Algoritme {
/**
* Methode die de ketting maakt en recursief kan worden opgeroepen.
* @param stenen De ArrayList van de stenen die meegegeven worden door de main
* @param geplaatsteStenen De stenen waarin de ketting wordt gelegd
* @param steenNummer De index die bijhoudt welke steen uit de originele lijst moeten geprobeerd toe te voegen
* @param aantalBacktracks Het aantal stenen die terug verwijderd zijn met backtracken
* @param volledigeBacktracks Het aantal keer dat het algoritme een nieuwe steen vooraan legt
* @return Recursief maakKetting opnieuw oproepen
*/
public Optional<ArrayList<Steen>> maakKetting(ArrayList<Steen> stenen, ArrayList<Steen> geplaatsteStenen, int steenNummer, int aantalBacktracks, int volledigeBacktracks) {
Steen huidigeSteen;
//controle die zorgt dat het algoritme stopt wanneer alle stenen op de eerste plaats hebben gelegen.
if (volledigeBacktracks > stenen.size() + geplaatsteStenen.size()) {
if(controleerSteen(geplaatsteStenen.get(geplaatsteStenen.size() - 1), geplaatsteStenen.get(0))) {
return Optional.of(geplaatsteStenen);
}
else {
return Optional.empty();
}
}
//Controle die zorgt dat het algoritme stopt wanneer alle te plaatsen stenen zijn opgebruikt
if (stenen.size() == 0) {
if(controleerSteen(geplaatsteStenen.get(geplaatsteStenen.size() - 1), geplaatsteStenen.get(0))) {
return Optional.of(geplaatsteStenen);
}
else {
return Optional.empty();
}
}
huidigeSteen = stenen.get(steenNummer);
//Vult de lege lijst met geplaatste stenen aan met het eerste element van de te plaatsen stenen.
if (geplaatsteStenen.isEmpty()) {
stenen.remove(huidigeSteen);
geplaatsteStenen.add(huidigeSteen);
return maakKetting(stenen, geplaatsteStenen, steenNummer, 0, volledigeBacktracks + 1);
}
Steen vorigeSteen = geplaatsteStenen.get(geplaatsteStenen.size()-1);
//Controleert als<SUF>
if (controleerSteen(vorigeSteen, huidigeSteen)) {
stenen.remove(steenNummer);
geplaatsteStenen.add(huidigeSteen);
steenNummer = 0;
return maakKetting(stenen, geplaatsteStenen, steenNummer, aantalBacktracks, volledigeBacktracks);
}
//Als er niet meer kan worden bijgeplaatst dan begint het volgende stuk met backtracken
else if (stenen.size() -1 - aantalBacktracks <= steenNummer){
if(controleerSteen(geplaatsteStenen.get(geplaatsteStenen.size() - 1), geplaatsteStenen.get(0))) {
return Optional.of(geplaatsteStenen);
}
controleerSteen(geplaatsteStenen.get(geplaatsteStenen.size() - 1), geplaatsteStenen.get(0));
geplaatsteStenen.remove(vorigeSteen);
stenen.add(vorigeSteen);
aantalBacktracks += 1;
return maakKetting(stenen, geplaatsteStenen, 0, aantalBacktracks, volledigeBacktracks);
}
else{
return maakKetting(stenen, geplaatsteStenen, steenNummer + 1, aantalBacktracks, volledigeBacktracks);
}
}
/**
* Methode die controleert als 2 stenen langs elkaar kunnen liggen, indien een steen geflipt moet worden dan doet deze methode dat ook.
* @param steen1 De eerste steen die gecontroleerd moet worden.
* @param steen2 De tweede steen die gecontroleerd moet worden
* @return Boolean om aan te geven als de stenen achter elkaar gelegd kunnen worden of niet.
*/
public boolean controleerSteen(Steen steen1, Steen steen2) {
if (steen1.getKleur() == steen2.getKleur()) {
return false;
}
if(steen1.getOgen2() != steen2.getOgen1()) {
if(steen1.getOgen2() == steen2.getOgen2()) {
steen2.flip();
return true;
}
else return false;
}
return true;
}
} | True | 1,213 | 26 | 1,339 | 28 | 1,198 | 18 | 1,339 | 28 | 1,439 | 27 | false | false | false | false | false | true |
1,550 | 210037_4 | package Forms;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
public class adminnform implements ActionListener {
JFrame frame;
JLabel id_lb = new JLabel("ID");
JLabel fname_lb = new JLabel("First name");
JLabel lname_lb = new JLabel("Last Name");
JLabel email_lb = new JLabel("Email");
JLabel telephone_lb = new JLabel("Telephone");
// JLabel gender_lb = new JLabel("Gender");
JTextField id_txf = new JTextField();
JTextField first_name_txf = new JTextField();
JTextField last_name_txf = new JTextField();
JTextField email_txf = new JTextField();
JTextField telephone_txf = new JTextField();
// String[] gender = {"Male", "Female"};
// JComboBox<String> genderBox = new JComboBox<>(gender);
JButton insert_btn = new JButton("Insert");
JButton read_btn = new JButton("Read");
JButton update_btn = new JButton("Update");
JButton delete_btn = new JButton("Delete");
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
public adminnform() {
createForm();
}
private void createForm() {
frame = new JFrame();
frame.setTitle("ADMIN FORM");
frame.setBounds(350, 100, 400, 350);
frame.getContentPane().setLayout(null);
frame.getContentPane().setBackground(Color.LIGHT_GRAY);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(true);
setLocationAndSize();
}
private void setLocationAndSize() {
id_lb.setBounds(10, 10, 100, 30);
fname_lb.setBounds(10, 50, 100, 30);
lname_lb.setBounds(10, 90, 100, 30);
email_lb.setBounds(10, 130, 100, 30);
telephone_lb.setBounds(10, 170, 100, 30);
// gender_lb.setBounds(10, 210, 100, 30);
id_txf.setBounds(160, 10, 130, 30);
first_name_txf.setBounds(160, 50, 130, 30);
last_name_txf.setBounds(160, 90, 130, 30);
email_txf.setBounds(160, 130, 130, 30);
telephone_txf.setBounds(160, 170, 130, 30);
// genderBox.setBounds(160, 210, 130, 30);
insert_btn.setBounds(10, 250, 85, 30);
read_btn.setBounds(100, 250, 85, 30);
update_btn.setBounds(190, 250, 85, 30);
delete_btn.setBounds(280, 250, 85, 30);
setFontForAll();
addComponentsForFrame();
}
private void setFontForAll() {
Font font = new Font("Georgia", Font.BOLD, 18);
id_lb.setFont(font);
fname_lb.setFont(font);
lname_lb.setFont(font);
email_lb.setFont(font);
telephone_lb.setFont(font);
// gender_lb.setFont(font);
id_txf.setFont(font);
first_name_txf.setFont(font);
last_name_txf.setFont(font);
email_txf.setFont(font);
telephone_txf.setFont(font);
// genderBox.setFont(font);
Font fonti = new Font("Georgia", Font.ITALIC, 12);
insert_btn.setFont(fonti);
read_btn.setFont(fonti);
update_btn.setFont(fonti);
delete_btn.setFont(fonti);
}
private void addComponentsForFrame() {
frame.add(id_lb);
frame.add(fname_lb);
frame.add(lname_lb);
frame.add(email_lb);
frame.add(telephone_lb);
// frame.add(gender_lb);
frame.add(id_txf);
frame.add(first_name_txf);
frame.add(last_name_txf);
frame.add(email_txf);
frame.add(telephone_txf);
// frame.add(genderBox);
frame.add(insert_btn);
frame.add(read_btn);
frame.add(update_btn);
frame.add(delete_btn);
insert_btn.addActionListener(this);
insert_btn.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection=DriverManager
.getConnection("jdbc:mysql://localhost:3306/revenuesystem","root","");
String query="INSERT INTO adminn VALUES(?,?,?,?,?)";
PreparedStatement pStatement=connection.prepareStatement(query);
pStatement.setInt(1,Integer.parseInt(id_txf.getText()));
pStatement.setString(2, first_name_txf.getText());
pStatement.setString(3, last_name_txf.getText());
pStatement.setString(4, email_txf.getText());
pStatement.setString(5, telephone_txf.getText());
// pStatement.setString(6, genderBox.getToolkit());
pStatement.executeUpdate();
JOptionPane.showMessageDialog(insert_btn, "data inserted well");
pStatement.close();
connection.close();
} catch (Exception e2) {
System.out.println(e2.getMessage());
}
}
});
read_btn.addActionListener(this);
update_btn.addActionListener(this);
update_btn.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/revenuesystem","root","");
String sql="UPDATE adminn SET first_name=?,last_name=?,email=?, telephone=? WHERE id=?";
PreparedStatement stm=connection.prepareStatement(sql);
stm.setString(1, first_name_txf.getText());
stm.setString(2, last_name_txf.getText());
stm.setString(3, email_txf.getText());
stm.setString(4, telephone_txf.getText());
stm.setInt(5,Integer.parseInt(id_txf.getText()));
stm.executeUpdate();
JOptionPane.showMessageDialog(update_btn, "update data!");
stm.close();
connection.close();
} catch (Exception e2) {
System.out.println(e2.getMessage());
}
}
});
delete_btn.addActionListener(this);
delete_btn.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/revenuesystem","root","");
String sql="DELETE FROM adminn WHERE id=?";
int brtxf=Integer.parseInt(JOptionPane.showInputDialog("Enter id to delete:"));
PreparedStatement stm=connection.prepareStatement(sql);
stm.setInt(1,brtxf);
JOptionPane.showMessageDialog(delete_btn, "recorded out!!!!!!!!!");
//Component delete;
stm.executeUpdate();
stm.close();
connection.close();
} catch (Exception e2) {
System.out.println(e2.getMessage());
}
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
}
public static void main(String[] args) {
new adminnform();
}
}
| SamuelNiyo/SamuelNiyo | niyomurengezi_samuel_222008677/src/Forms/adminnform.java | 2,603 | // genderBox.setBounds(160, 210, 130, 30);_x000D_ | line_comment | nl | package Forms;_x000D_
_x000D_
import java.awt.Color;_x000D_
import java.awt.Dimension;_x000D_
import java.awt.Font;_x000D_
import java.awt.Toolkit;_x000D_
import java.awt.event.ActionEvent;_x000D_
import java.awt.event.ActionListener;_x000D_
import java.sql.Connection;_x000D_
import java.sql.DriverManager;_x000D_
import java.sql.PreparedStatement;_x000D_
_x000D_
import javax.swing.JButton;_x000D_
import javax.swing.JFrame;_x000D_
import javax.swing.JLabel;_x000D_
import javax.swing.JTextField;_x000D_
import javax.swing.JOptionPane;_x000D_
_x000D_
public class adminnform implements ActionListener {_x000D_
JFrame frame;_x000D_
JLabel id_lb = new JLabel("ID");_x000D_
JLabel fname_lb = new JLabel("First name");_x000D_
JLabel lname_lb = new JLabel("Last Name");_x000D_
JLabel email_lb = new JLabel("Email");_x000D_
JLabel telephone_lb = new JLabel("Telephone");_x000D_
// JLabel gender_lb = new JLabel("Gender");_x000D_
_x000D_
JTextField id_txf = new JTextField();_x000D_
JTextField first_name_txf = new JTextField();_x000D_
JTextField last_name_txf = new JTextField();_x000D_
JTextField email_txf = new JTextField();_x000D_
JTextField telephone_txf = new JTextField();_x000D_
_x000D_
// String[] gender = {"Male", "Female"};_x000D_
// JComboBox<String> genderBox = new JComboBox<>(gender);_x000D_
_x000D_
JButton insert_btn = new JButton("Insert");_x000D_
JButton read_btn = new JButton("Read");_x000D_
JButton update_btn = new JButton("Update");_x000D_
JButton delete_btn = new JButton("Delete");_x000D_
_x000D_
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();_x000D_
_x000D_
public adminnform() {_x000D_
createForm();_x000D_
}_x000D_
_x000D_
private void createForm() {_x000D_
frame = new JFrame();_x000D_
frame.setTitle("ADMIN FORM");_x000D_
frame.setBounds(350, 100, 400, 350);_x000D_
frame.getContentPane().setLayout(null);_x000D_
frame.getContentPane().setBackground(Color.LIGHT_GRAY);_x000D_
frame.setVisible(true);_x000D_
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);_x000D_
frame.setResizable(true);_x000D_
setLocationAndSize();_x000D_
}_x000D_
_x000D_
private void setLocationAndSize() {_x000D_
id_lb.setBounds(10, 10, 100, 30);_x000D_
fname_lb.setBounds(10, 50, 100, 30);_x000D_
lname_lb.setBounds(10, 90, 100, 30);_x000D_
email_lb.setBounds(10, 130, 100, 30);_x000D_
telephone_lb.setBounds(10, 170, 100, 30);_x000D_
// gender_lb.setBounds(10, 210, 100, 30);_x000D_
_x000D_
id_txf.setBounds(160, 10, 130, 30);_x000D_
first_name_txf.setBounds(160, 50, 130, 30);_x000D_
last_name_txf.setBounds(160, 90, 130, 30);_x000D_
email_txf.setBounds(160, 130, 130, 30);_x000D_
telephone_txf.setBounds(160, 170, 130, 30);_x000D_
// genderBox.setBounds(160, 210,<SUF>
_x000D_
insert_btn.setBounds(10, 250, 85, 30);_x000D_
read_btn.setBounds(100, 250, 85, 30);_x000D_
update_btn.setBounds(190, 250, 85, 30);_x000D_
delete_btn.setBounds(280, 250, 85, 30);_x000D_
setFontForAll();_x000D_
addComponentsForFrame();_x000D_
}_x000D_
_x000D_
private void setFontForAll() {_x000D_
Font font = new Font("Georgia", Font.BOLD, 18);_x000D_
_x000D_
id_lb.setFont(font);_x000D_
fname_lb.setFont(font);_x000D_
lname_lb.setFont(font);_x000D_
email_lb.setFont(font);_x000D_
telephone_lb.setFont(font);_x000D_
// gender_lb.setFont(font);_x000D_
_x000D_
id_txf.setFont(font);_x000D_
first_name_txf.setFont(font);_x000D_
last_name_txf.setFont(font);_x000D_
email_txf.setFont(font);_x000D_
telephone_txf.setFont(font);_x000D_
// genderBox.setFont(font);_x000D_
_x000D_
Font fonti = new Font("Georgia", Font.ITALIC, 12);_x000D_
_x000D_
insert_btn.setFont(fonti);_x000D_
read_btn.setFont(fonti);_x000D_
update_btn.setFont(fonti);_x000D_
delete_btn.setFont(fonti);_x000D_
}_x000D_
_x000D_
private void addComponentsForFrame() {_x000D_
frame.add(id_lb);_x000D_
frame.add(fname_lb);_x000D_
frame.add(lname_lb);_x000D_
frame.add(email_lb);_x000D_
frame.add(telephone_lb);_x000D_
// frame.add(gender_lb);_x000D_
_x000D_
frame.add(id_txf);_x000D_
frame.add(first_name_txf);_x000D_
frame.add(last_name_txf);_x000D_
frame.add(email_txf);_x000D_
frame.add(telephone_txf);_x000D_
// frame.add(genderBox);_x000D_
_x000D_
frame.add(insert_btn);_x000D_
frame.add(read_btn);_x000D_
frame.add(update_btn);_x000D_
frame.add(delete_btn);_x000D_
_x000D_
insert_btn.addActionListener(this);_x000D_
insert_btn.addActionListener(new ActionListener() {_x000D_
_x000D_
public void actionPerformed(java.awt.event.ActionEvent e) {_x000D_
try {_x000D_
Class.forName("com.mysql.cj.jdbc.Driver"); _x000D_
Connection connection=DriverManager_x000D_
.getConnection("jdbc:mysql://localhost:3306/revenuesystem","root","");_x000D_
String query="INSERT INTO adminn VALUES(?,?,?,?,?)";_x000D_
PreparedStatement pStatement=connection.prepareStatement(query);_x000D_
pStatement.setInt(1,Integer.parseInt(id_txf.getText()));_x000D_
pStatement.setString(2, first_name_txf.getText());_x000D_
pStatement.setString(3, last_name_txf.getText());_x000D_
pStatement.setString(4, email_txf.getText());_x000D_
pStatement.setString(5, telephone_txf.getText());_x000D_
// pStatement.setString(6, genderBox.getToolkit());_x000D_
pStatement.executeUpdate();_x000D_
JOptionPane.showMessageDialog(insert_btn, "data inserted well");_x000D_
pStatement.close();_x000D_
connection.close(); _x000D_
} catch (Exception e2) {_x000D_
System.out.println(e2.getMessage());_x000D_
}_x000D_
_x000D_
}_x000D_
}); _x000D_
_x000D_
read_btn.addActionListener(this);_x000D_
update_btn.addActionListener(this);_x000D_
update_btn.addActionListener(new ActionListener() {_x000D_
_x000D_
public void actionPerformed(java.awt.event.ActionEvent e) {_x000D_
try {_x000D_
Class.forName("com.mysql.cj.jdbc.Driver"); _x000D_
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/revenuesystem","root","");_x000D_
String sql="UPDATE adminn SET first_name=?,last_name=?,email=?, telephone=? WHERE id=?";_x000D_
PreparedStatement stm=connection.prepareStatement(sql);_x000D_
_x000D_
stm.setString(1, first_name_txf.getText());_x000D_
stm.setString(2, last_name_txf.getText());_x000D_
stm.setString(3, email_txf.getText());_x000D_
stm.setString(4, telephone_txf.getText());_x000D_
stm.setInt(5,Integer.parseInt(id_txf.getText()));_x000D_
_x000D_
_x000D_
stm.executeUpdate();_x000D_
_x000D_
JOptionPane.showMessageDialog(update_btn, "update data!");_x000D_
stm.close();_x000D_
connection.close(); _x000D_
} catch (Exception e2) {_x000D_
System.out.println(e2.getMessage());_x000D_
}_x000D_
_x000D_
}_x000D_
});_x000D_
delete_btn.addActionListener(this);_x000D_
delete_btn.addActionListener(new ActionListener() {_x000D_
_x000D_
_x000D_
public void actionPerformed(java.awt.event.ActionEvent e) {_x000D_
try {_x000D_
Class.forName("com.mysql.cj.jdbc.Driver"); _x000D_
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/revenuesystem","root","");_x000D_
String sql="DELETE FROM adminn WHERE id=?";_x000D_
int brtxf=Integer.parseInt(JOptionPane.showInputDialog("Enter id to delete:"));_x000D_
_x000D_
_x000D_
PreparedStatement stm=connection.prepareStatement(sql);_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
stm.setInt(1,brtxf);_x000D_
_x000D_
JOptionPane.showMessageDialog(delete_btn, "recorded out!!!!!!!!!");_x000D_
//Component delete;_x000D_
stm.executeUpdate();_x000D_
stm.close();_x000D_
_x000D_
connection.close(); _x000D_
} catch (Exception e2) {_x000D_
System.out.println(e2.getMessage());_x000D_
}_x000D_
_x000D_
}_x000D_
});_x000D_
_x000D_
}_x000D_
_x000D_
@Override_x000D_
public void actionPerformed(ActionEvent e) {_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
public static void main(String[] args) {_x000D_
new adminnform();_x000D_
}_x000D_
}_x000D_
| False | 1,710 | 30 | 2,161 | 31 | 2,268 | 31 | 2,161 | 31 | 2,733 | 32 | false | false | false | false | false | true |
574 | 52524_1 | package be.intecbrussel;
import java.util.Random;
import java.util.Scanner; // package importeren !!!!!!
public class MainApp {
public static void main(String[] args) {
// maak instantie van de Scanner class, genaamd myScanner
// Scanner myScanner = new Scanner(System.in);
// System.out.print("Vul hier je naam in: ");
// String name = myScanner.nextLine();
//
// System.out.print("Vul uw familienaam in: ");
// String achternaam = myScanner.nextLine();
//
// System.out.print("Vul uw leeftijd in: ");
// int age = myScanner.nextInt();
//
// System.out.print("Ben je een man: ");
// boolean isMale = myScanner.nextBoolean();
//
// System.out.print("Wat is uw lengte in meters: ");
// double lenght = myScanner.nextDouble();
//
// System.out.print("Vul een long waarde in: ");
// long largeNumber = myScanner.nextLong();
// Math clas -> static class = altijd aanwezig
// abs methode
double x = -10.5;
double res = Math.abs(x);
System.out.println("Absolute waarde van x is: " + res);
// min max
double i = 10;
double j = 20;
double min = Math.min(i, j);
double max = Math.max(i, j);
System.out.println("de grootste waarde is: " + max);
System.out.println("de kleinste waarde is: " + min);
// round
x = 10.5;
res = Math.round(x);
System.out.println("Afgerond naar het dichtsbijzijnde gehele getal: " + res);
// ceil -> gaat altijd naar boven afronden
x = 10.1;
res = Math.ceil(x);
System.out.println("Afgerond naar boven : " + res);
// floor -> afronden naar beneden
x = 10.9;
res = Math.floor(x);
System.out.println("Afgerond naar benenden: " + res);
// random
Random random = new Random();
// int tussen 0 tot 100(exclusief)System.out.println("Random number: " + randonNumber);
int randonNumber = 0;
while (randonNumber != 1) {
randonNumber = random.nextInt(101);
System.out.println(randonNumber);
}
// random double
double randomDecimalNumber = random.nextDouble(10, 20);
System.out.println("Random decimal number: " + randomDecimalNumber);
// random float
float randonFloatNumber = random.nextFloat(5, 10);
System.out.println("Random float number: " + randonFloatNumber);
// random boolean
boolean randomBoolean = random.nextBoolean();
System.out.println("Random boolean: " + randomBoolean);
}
}
| Gabe-Alvess/ScannerMathRandom | src/be/intecbrussel/MainApp.java | 809 | // maak instantie van de Scanner class, genaamd myScanner | line_comment | nl | package be.intecbrussel;
import java.util.Random;
import java.util.Scanner; // package importeren !!!!!!
public class MainApp {
public static void main(String[] args) {
// maak instantie<SUF>
// Scanner myScanner = new Scanner(System.in);
// System.out.print("Vul hier je naam in: ");
// String name = myScanner.nextLine();
//
// System.out.print("Vul uw familienaam in: ");
// String achternaam = myScanner.nextLine();
//
// System.out.print("Vul uw leeftijd in: ");
// int age = myScanner.nextInt();
//
// System.out.print("Ben je een man: ");
// boolean isMale = myScanner.nextBoolean();
//
// System.out.print("Wat is uw lengte in meters: ");
// double lenght = myScanner.nextDouble();
//
// System.out.print("Vul een long waarde in: ");
// long largeNumber = myScanner.nextLong();
// Math clas -> static class = altijd aanwezig
// abs methode
double x = -10.5;
double res = Math.abs(x);
System.out.println("Absolute waarde van x is: " + res);
// min max
double i = 10;
double j = 20;
double min = Math.min(i, j);
double max = Math.max(i, j);
System.out.println("de grootste waarde is: " + max);
System.out.println("de kleinste waarde is: " + min);
// round
x = 10.5;
res = Math.round(x);
System.out.println("Afgerond naar het dichtsbijzijnde gehele getal: " + res);
// ceil -> gaat altijd naar boven afronden
x = 10.1;
res = Math.ceil(x);
System.out.println("Afgerond naar boven : " + res);
// floor -> afronden naar beneden
x = 10.9;
res = Math.floor(x);
System.out.println("Afgerond naar benenden: " + res);
// random
Random random = new Random();
// int tussen 0 tot 100(exclusief)System.out.println("Random number: " + randonNumber);
int randonNumber = 0;
while (randonNumber != 1) {
randonNumber = random.nextInt(101);
System.out.println(randonNumber);
}
// random double
double randomDecimalNumber = random.nextDouble(10, 20);
System.out.println("Random decimal number: " + randomDecimalNumber);
// random float
float randonFloatNumber = random.nextFloat(5, 10);
System.out.println("Random float number: " + randonFloatNumber);
// random boolean
boolean randomBoolean = random.nextBoolean();
System.out.println("Random boolean: " + randomBoolean);
}
}
| True | 666 | 15 | 773 | 15 | 758 | 13 | 773 | 15 | 838 | 16 | false | false | false | false | false | true |
783 | 14064_8 | package protocol;
public class Protocol {
/**
* @author Rosalyn.Sleurink
* @version 6
*/
/**
* Aanpassing versie 1 -> 2:
* Bij START worden de namen van de spelers niet meegegeven, dit is wel handig om te doen.
*
* Aanpassing versie 2 -> 3:
* - Version verdeeld in VERSION (String) en VERSIONNO (int)
* - Constantes BLACK en WHITE toegevoegd
*
* Aanpassing versie 3 -> 4:
* - Beide delimiters een String gemaakt en $ is //$ geworden.
*
* Aanpassing versie 4 -> 5:
* - Delimiter weer terugveranderd naar $.
* - Aan TURN zijn String FIRST en PASS toegevoegd
* - Tweede voorbeeld bij START is aangepast naar het format.
*
* Aanpassing versie 5 -> 6:
* - EXIT commando toegevoegd
* - Afspraak gemaakt dat bord grootte kan hebben van 5 t/m 19.
*/
/**
* OVERAL WAAR SPATIES STAAN KOMT DUS DELIMITER1 (in de voorbeelden en formats).
* OOK MOETEN ALLE COMMANDO'S EINDIGEN MET COMMAND_END.
*/
public static final int VERSION_NO = 6;
public static class Client {
/**
* Het eerste commando wat de client naar de server stuurt. Gaat om versie
* van het protocol. De volgorde van de extensions is als volgt:
* chat challenge leaderboard security 2+ simultaneous multiplemoves.<br>
* Format: NAME clientnaam VERSION versienummer EXTENSIONS boolean boolean boolean etc<br>
* Voorbeeld: NAME piet VERSION 2 EXTENSIONS 0 0 1 1 0 0 0
*/
public static final String NAME = "NAME";
public static final String VERSION = "VERSION";
public static final int VERSIONNO = VERSION_NO;
public static final String EXTENSIONS = "EXTENSIONS";
/**
* Om een move te communiceren. Bord begint linksboven met 0,0.<br>
* Format: MOVE rij_kolom of MOVE PASS<br>
* Voorbeeld: MOVE 1_3
*/
public static final String MOVE = "MOVE";
public static final String PASS = "PASS";
/**
* Als de server een START met aantal spelers heeft gestuurd mag je je voorkeur doorgeven
* voor kleur en grootte van het bord. Dit wordt gevraagd aan de speler die er als eerst
* was. Grootte van het bord mag van 5 t/m 19 zijn.<br>
* Format: SETTINGS kleur bordgrootte<br>
* Voorbeeld: SETTINGS BLACK 19
*/
public static final String SETTINGS = "SETTINGS";
/**
* Als je midden in een spel zit en wil stoppen. Je krijgt dan 0 punten.
* Wordt niet gestuurd als client abrupt.
* afgesloten wordt. Als je dit stuurt nadat je een REQUESTGAME hebt gedaan gebeurt er
* niks.<br>
* Format: QUIT<br>
* Voorbeeld: QUIT
*/
public static final String QUIT = "QUIT";
/**
* Kan gestuurd worden als je in een spel zit of in de lobby, betekent dat de Client
* helemaal weg gaat.<br>
* Format: EXIT<br>
* Voorbeeld: QUIT
*/
public static final String EXIT = "EXIT";
/**
* Sturen als je een spel wilt spelen. De eerste keer en als een spel afgelopen is opnieuw.
* Als je de Challenge extensie niet ondersteunt, stuur dan RANDOM in plaats van een naam.
* <br>
* Format: REQUESTGAME aantalspelers naamtegenspeler (RANDOM als je geen challenge doet)<br>
* Voorbeeld: REQUESTGAME 2 RANDOM of REQUESTGAME 2 piet
*/
public static final String REQUESTGAME = "REQUESTGAME";
public static final String RANDOM = "RANDOM";
// -------------- EXTENSIES ------------ //
/**
* Als je de uitdaging wil accepteren.<br>
* Format: ACCEPTGAME naamuitdager<br>
* Voorbeeld: ACCEPTGAME piet
*/
public static final String ACCEPTGAME = "ACCEPTGAME";
/**
* Als je de uitdaging niet accepteert.<br>
* Format: DECLINEGAME naamuitdager<br>
* Voorbeeld: DECLINEGAME piet
*/
public static final String DECLINEGAME = "DECLINEGAME";
/**
* Om op te vragen wie je allemaal kan uitdagen.<br>
* Format: LOBBY<br>
* Voorbeeld: LOBBY
*/
public static final String LOBBY = "LOBBY";
/**
* Om een chatbericht te sturen. Als je in een spel zit mogen alleen de spelers het zien.
* Als je in de lobby zit mag iedereen in de lobby het zien.<br>
* Format: CHAT bericht<br>
* Voorbeeld: CHAT hoi ik ben piet
*/
public static final String CHAT = "CHAT";
/**
* Om de leaderboard op te vragen. Overige queries moet je afspreken met anderen die ook
* leaderboard willen implementeren.<br>
* Format: LEADERBOARD<br>
* Voorbeeld: LEADERBOARD
*/
public static final String LEADERBOARD = "LEADERBOARD";
}
public static class Server {
/**
* Het eerste commando wat de server naar de client stuurt. Gaat om versie
* van het protocol. De volgorde van de extensions is als volgt:
* chat challenge leaderboard security 2+ simultaneous multiplemoves.<br>
* Format: NAME clientnaam VERSION versienummer EXTENSIONS boolean boolean boolean etc<br>
* Voorbeeld: NAME serverpiet VERSION 2 EXTENSIONS 0 0 1 1 0 0 0
*/
public static final String NAME = "NAME";
public static final String VERSION = "VERSION";
public static final int VERSIONNO = VERSION_NO;
public static final String EXTENSIONS = "EXTENSIONS";
/**
* Een spel starten. Dit stuur je naar de eerste speler. <br>
* Format: START aantalspelers (naar speler 1)<br>
* Format: START aantalspelers kleur bordgrootte speler1 speler2 (3, etc..)
* (naar alle spelers) Bordgrootte kan waarde hebben van 5 t/m 19.<br>
* Voorbeeld: START 2 of START 2 BLACK 19 jan piet
*/
public static final String START = "START";
/**
* Vertelt aan de spelers welke beurt er gedaan is. Speler1 is de speler die de beurt heeft
* gedaan, speler 2 de speler die nu aan de beurt is om een MOVE door te geven. Als dit de
* eerste beurt is zijn speler1 en speler2 allebei de speler die nu aan de beurt is, en dan
* stuur je FIRST i.p.v. de integers. Als de speler past geeft je PASS door ip.v. de
* integers.<br>
* Format: TURN speler1 rij_kolom speler2<br>
* Voorbeeld: TURN piet 1_3 jan of TURN piet FIRST piet
*/
public static final String TURN = "TURN";
public static final String FIRST = "FIRST";
public static final String PASS = "PASS";
/**
* Als het spel klaar is om welke reden dan ook. Reden kan zijn FINISHED (normaal einde),
* ABORTED (abrupt einde) of TIMEOUT (geen respons binnen redelijke tijd)<br>
* Format: ENDGAME reden winspeler score verliesspeler score<br>
* Voorbeeld: ENDGAME FINISHED piet 12 jan 10
*/
public static final String ENDGAME = "ENDGAME";
public static final String FINISHED = "FINISHED";
public static final String ABORTED = "ABORTED";
public static final String TIMEOUT = "TIMEOUT";
/**
* Errortypes die we gedefinieerd hebben: UNKNOWNCOMMAND, INVALIDMOVE, NAMETAKEN,
* INCOMPATIBLEPROTOCOL, OTHER.<br>
* Format: ERROR type bericht<br>
* Voorbeeld: ERROR NAMETAKEN de naam piet is al bezet
*/
public static final String ERROR = "ERROR";
public static final String UNKNOWN = "UNKNOWNCOMMAND";
public static final String INVALID = "INVALIDMOVE";
public static final String NAMETAKEN = "NAMETAKEN";
public static final String INCOMPATIBLEPROTOCOL = "INCOMPATIBLEPROTOCOL";
public static final String OTHER = "OTHER";
// -------------- EXTENSIES ------------ //
/**
* Stuurt aan één client wie hem heeft uitgedaagd.<br>
* Format: REQUESTGAME uitdager<br>
* Voorbeeld: REQUESTGAME piet
*/
public static final String REQUESTGAME = "REQUESTGAME";
/**
* Stuurt aan de uitdager dat de uitdaging is geweigerd en door wie.<br>
* Format: DECLINED uitgedaagde<br>
* Voorbeeld: DECLINED piet
*/
public static final String DECLINED = "DECLINED";
/**
* Reactie op LOBBY van de client. Stuurt alle spelers die uitgedaagd kunnen worden
* (in de lobby zitten).<br>
* Format: LOBBY naam1_naam2_naam3<br>
* Voorbeeld: LOBBY piet jan koos
*/
public static final String LOBBY = "LOBBY";
/**
* Stuurt chatbericht naar relevante clients (in spel of in lobby).<br>
* Format: CHAT naam bericht<br>
* Voorbeeld: CHAT piet hallo ik ben piet (Met correcte delimiter ziet dat er dus uit als:
* CHAT$piet$hallo ik ben piet)
*/
public static final String CHAT = "CHAT";
/**
* Reactie op LEADERBOARD van client. Stuurt de beste 10 scores naar één client.
* Overige queries moet je afspreken met anderen die ook
* leaderboard willen implementeren.<br>
* Format: LEADERBOARD naam1 score1 naam2 score2 naam3 score3 enz<br>
* Voorbeeld: LEADERBOARD piet 1834897 jan 2 koos 1
*/
public static final String LEADERBOARD = "LEADERBOARD";
}
public static class General {
/**
* ENCODING kun je ergens bij je printstream/bufferedreader/writer instellen (zie API).
*/
public static final String ENCODING = "UTF-8";
public static final int TIMEOUTSECONDS = 90;
public static final short DEFAULT_PORT = 5647;
public static final String DELIMITER1 = "$";
public static final String DELIMITER2 = "_";
public static final String COMMAND_END = "\n";
public static final String BLACK = "BLACK";
public static final String WHITE = "WHITE";
}
}
| JKleinRot/NedapUniversity_FinalAssignment | src/protocol/Protocol.java | 3,062 | /**
* Sturen als je een spel wilt spelen. De eerste keer en als een spel afgelopen is opnieuw.
* Als je de Challenge extensie niet ondersteunt, stuur dan RANDOM in plaats van een naam.
* <br>
* Format: REQUESTGAME aantalspelers naamtegenspeler (RANDOM als je geen challenge doet)<br>
* Voorbeeld: REQUESTGAME 2 RANDOM of REQUESTGAME 2 piet
*/ | block_comment | nl | package protocol;
public class Protocol {
/**
* @author Rosalyn.Sleurink
* @version 6
*/
/**
* Aanpassing versie 1 -> 2:
* Bij START worden de namen van de spelers niet meegegeven, dit is wel handig om te doen.
*
* Aanpassing versie 2 -> 3:
* - Version verdeeld in VERSION (String) en VERSIONNO (int)
* - Constantes BLACK en WHITE toegevoegd
*
* Aanpassing versie 3 -> 4:
* - Beide delimiters een String gemaakt en $ is //$ geworden.
*
* Aanpassing versie 4 -> 5:
* - Delimiter weer terugveranderd naar $.
* - Aan TURN zijn String FIRST en PASS toegevoegd
* - Tweede voorbeeld bij START is aangepast naar het format.
*
* Aanpassing versie 5 -> 6:
* - EXIT commando toegevoegd
* - Afspraak gemaakt dat bord grootte kan hebben van 5 t/m 19.
*/
/**
* OVERAL WAAR SPATIES STAAN KOMT DUS DELIMITER1 (in de voorbeelden en formats).
* OOK MOETEN ALLE COMMANDO'S EINDIGEN MET COMMAND_END.
*/
public static final int VERSION_NO = 6;
public static class Client {
/**
* Het eerste commando wat de client naar de server stuurt. Gaat om versie
* van het protocol. De volgorde van de extensions is als volgt:
* chat challenge leaderboard security 2+ simultaneous multiplemoves.<br>
* Format: NAME clientnaam VERSION versienummer EXTENSIONS boolean boolean boolean etc<br>
* Voorbeeld: NAME piet VERSION 2 EXTENSIONS 0 0 1 1 0 0 0
*/
public static final String NAME = "NAME";
public static final String VERSION = "VERSION";
public static final int VERSIONNO = VERSION_NO;
public static final String EXTENSIONS = "EXTENSIONS";
/**
* Om een move te communiceren. Bord begint linksboven met 0,0.<br>
* Format: MOVE rij_kolom of MOVE PASS<br>
* Voorbeeld: MOVE 1_3
*/
public static final String MOVE = "MOVE";
public static final String PASS = "PASS";
/**
* Als de server een START met aantal spelers heeft gestuurd mag je je voorkeur doorgeven
* voor kleur en grootte van het bord. Dit wordt gevraagd aan de speler die er als eerst
* was. Grootte van het bord mag van 5 t/m 19 zijn.<br>
* Format: SETTINGS kleur bordgrootte<br>
* Voorbeeld: SETTINGS BLACK 19
*/
public static final String SETTINGS = "SETTINGS";
/**
* Als je midden in een spel zit en wil stoppen. Je krijgt dan 0 punten.
* Wordt niet gestuurd als client abrupt.
* afgesloten wordt. Als je dit stuurt nadat je een REQUESTGAME hebt gedaan gebeurt er
* niks.<br>
* Format: QUIT<br>
* Voorbeeld: QUIT
*/
public static final String QUIT = "QUIT";
/**
* Kan gestuurd worden als je in een spel zit of in de lobby, betekent dat de Client
* helemaal weg gaat.<br>
* Format: EXIT<br>
* Voorbeeld: QUIT
*/
public static final String EXIT = "EXIT";
/**
* Sturen als je<SUF>*/
public static final String REQUESTGAME = "REQUESTGAME";
public static final String RANDOM = "RANDOM";
// -------------- EXTENSIES ------------ //
/**
* Als je de uitdaging wil accepteren.<br>
* Format: ACCEPTGAME naamuitdager<br>
* Voorbeeld: ACCEPTGAME piet
*/
public static final String ACCEPTGAME = "ACCEPTGAME";
/**
* Als je de uitdaging niet accepteert.<br>
* Format: DECLINEGAME naamuitdager<br>
* Voorbeeld: DECLINEGAME piet
*/
public static final String DECLINEGAME = "DECLINEGAME";
/**
* Om op te vragen wie je allemaal kan uitdagen.<br>
* Format: LOBBY<br>
* Voorbeeld: LOBBY
*/
public static final String LOBBY = "LOBBY";
/**
* Om een chatbericht te sturen. Als je in een spel zit mogen alleen de spelers het zien.
* Als je in de lobby zit mag iedereen in de lobby het zien.<br>
* Format: CHAT bericht<br>
* Voorbeeld: CHAT hoi ik ben piet
*/
public static final String CHAT = "CHAT";
/**
* Om de leaderboard op te vragen. Overige queries moet je afspreken met anderen die ook
* leaderboard willen implementeren.<br>
* Format: LEADERBOARD<br>
* Voorbeeld: LEADERBOARD
*/
public static final String LEADERBOARD = "LEADERBOARD";
}
public static class Server {
/**
* Het eerste commando wat de server naar de client stuurt. Gaat om versie
* van het protocol. De volgorde van de extensions is als volgt:
* chat challenge leaderboard security 2+ simultaneous multiplemoves.<br>
* Format: NAME clientnaam VERSION versienummer EXTENSIONS boolean boolean boolean etc<br>
* Voorbeeld: NAME serverpiet VERSION 2 EXTENSIONS 0 0 1 1 0 0 0
*/
public static final String NAME = "NAME";
public static final String VERSION = "VERSION";
public static final int VERSIONNO = VERSION_NO;
public static final String EXTENSIONS = "EXTENSIONS";
/**
* Een spel starten. Dit stuur je naar de eerste speler. <br>
* Format: START aantalspelers (naar speler 1)<br>
* Format: START aantalspelers kleur bordgrootte speler1 speler2 (3, etc..)
* (naar alle spelers) Bordgrootte kan waarde hebben van 5 t/m 19.<br>
* Voorbeeld: START 2 of START 2 BLACK 19 jan piet
*/
public static final String START = "START";
/**
* Vertelt aan de spelers welke beurt er gedaan is. Speler1 is de speler die de beurt heeft
* gedaan, speler 2 de speler die nu aan de beurt is om een MOVE door te geven. Als dit de
* eerste beurt is zijn speler1 en speler2 allebei de speler die nu aan de beurt is, en dan
* stuur je FIRST i.p.v. de integers. Als de speler past geeft je PASS door ip.v. de
* integers.<br>
* Format: TURN speler1 rij_kolom speler2<br>
* Voorbeeld: TURN piet 1_3 jan of TURN piet FIRST piet
*/
public static final String TURN = "TURN";
public static final String FIRST = "FIRST";
public static final String PASS = "PASS";
/**
* Als het spel klaar is om welke reden dan ook. Reden kan zijn FINISHED (normaal einde),
* ABORTED (abrupt einde) of TIMEOUT (geen respons binnen redelijke tijd)<br>
* Format: ENDGAME reden winspeler score verliesspeler score<br>
* Voorbeeld: ENDGAME FINISHED piet 12 jan 10
*/
public static final String ENDGAME = "ENDGAME";
public static final String FINISHED = "FINISHED";
public static final String ABORTED = "ABORTED";
public static final String TIMEOUT = "TIMEOUT";
/**
* Errortypes die we gedefinieerd hebben: UNKNOWNCOMMAND, INVALIDMOVE, NAMETAKEN,
* INCOMPATIBLEPROTOCOL, OTHER.<br>
* Format: ERROR type bericht<br>
* Voorbeeld: ERROR NAMETAKEN de naam piet is al bezet
*/
public static final String ERROR = "ERROR";
public static final String UNKNOWN = "UNKNOWNCOMMAND";
public static final String INVALID = "INVALIDMOVE";
public static final String NAMETAKEN = "NAMETAKEN";
public static final String INCOMPATIBLEPROTOCOL = "INCOMPATIBLEPROTOCOL";
public static final String OTHER = "OTHER";
// -------------- EXTENSIES ------------ //
/**
* Stuurt aan één client wie hem heeft uitgedaagd.<br>
* Format: REQUESTGAME uitdager<br>
* Voorbeeld: REQUESTGAME piet
*/
public static final String REQUESTGAME = "REQUESTGAME";
/**
* Stuurt aan de uitdager dat de uitdaging is geweigerd en door wie.<br>
* Format: DECLINED uitgedaagde<br>
* Voorbeeld: DECLINED piet
*/
public static final String DECLINED = "DECLINED";
/**
* Reactie op LOBBY van de client. Stuurt alle spelers die uitgedaagd kunnen worden
* (in de lobby zitten).<br>
* Format: LOBBY naam1_naam2_naam3<br>
* Voorbeeld: LOBBY piet jan koos
*/
public static final String LOBBY = "LOBBY";
/**
* Stuurt chatbericht naar relevante clients (in spel of in lobby).<br>
* Format: CHAT naam bericht<br>
* Voorbeeld: CHAT piet hallo ik ben piet (Met correcte delimiter ziet dat er dus uit als:
* CHAT$piet$hallo ik ben piet)
*/
public static final String CHAT = "CHAT";
/**
* Reactie op LEADERBOARD van client. Stuurt de beste 10 scores naar één client.
* Overige queries moet je afspreken met anderen die ook
* leaderboard willen implementeren.<br>
* Format: LEADERBOARD naam1 score1 naam2 score2 naam3 score3 enz<br>
* Voorbeeld: LEADERBOARD piet 1834897 jan 2 koos 1
*/
public static final String LEADERBOARD = "LEADERBOARD";
}
public static class General {
/**
* ENCODING kun je ergens bij je printstream/bufferedreader/writer instellen (zie API).
*/
public static final String ENCODING = "UTF-8";
public static final int TIMEOUTSECONDS = 90;
public static final short DEFAULT_PORT = 5647;
public static final String DELIMITER1 = "$";
public static final String DELIMITER2 = "_";
public static final String COMMAND_END = "\n";
public static final String BLACK = "BLACK";
public static final String WHITE = "WHITE";
}
}
| True | 2,693 | 105 | 2,927 | 119 | 2,709 | 97 | 2,927 | 119 | 3,454 | 128 | false | false | false | false | false | true |
1,195 | 12524_2 | /*
* (c) Copyright IBM Corp 2001, 2006
*/
package com.ibm.wsdl.util;
import java.util.*;
/**
* The <em>ObjectRegistry</em> is used to do name-to-object reference lookups.
* If an <em>ObjectRegistry</em> is passed as a constructor argument, then this
* <em>ObjectRegistry</em> will be a cascading registry: when a lookup is
* invoked, it will first look in its own table for a name, and if it's not
* there, it will cascade to the parent <em>ObjectRegistry</em>.
* All registration is always local. [??]
*
* @author Sanjiva Weerawarana
* @author Matthew J. Duftler
*/
public class ObjectRegistry {
Hashtable reg = new Hashtable ();
ObjectRegistry parent = null;
public ObjectRegistry () {
}
public ObjectRegistry (Map initialValues) {
if(initialValues != null)
{
Iterator itr = initialValues.keySet().iterator();
while(itr.hasNext())
{
String name = (String) itr.next();
register(name, initialValues.get(name));
}
}
}
public ObjectRegistry (ObjectRegistry parent) {
this.parent = parent;
}
// register an object
public void register (String name, Object obj) {
reg.put (name, obj);
}
// unregister an object (silent if unknown name)
public void unregister (String name) {
reg.remove (name);
}
// lookup an object: cascade up if needed
public Object lookup (String name) throws IllegalArgumentException {
Object obj = reg.get (name);
if (obj == null && parent != null) {
obj = parent.lookup (name);
}
if (obj == null) {
throw new IllegalArgumentException ("object '" + name + "' not in registry");
}
return obj;
}
} | NetSPI/Wsdler | src/main/java/com/ibm/wsdl/util/ObjectRegistry.java | 513 | // register an object | line_comment | nl | /*
* (c) Copyright IBM Corp 2001, 2006
*/
package com.ibm.wsdl.util;
import java.util.*;
/**
* The <em>ObjectRegistry</em> is used to do name-to-object reference lookups.
* If an <em>ObjectRegistry</em> is passed as a constructor argument, then this
* <em>ObjectRegistry</em> will be a cascading registry: when a lookup is
* invoked, it will first look in its own table for a name, and if it's not
* there, it will cascade to the parent <em>ObjectRegistry</em>.
* All registration is always local. [??]
*
* @author Sanjiva Weerawarana
* @author Matthew J. Duftler
*/
public class ObjectRegistry {
Hashtable reg = new Hashtable ();
ObjectRegistry parent = null;
public ObjectRegistry () {
}
public ObjectRegistry (Map initialValues) {
if(initialValues != null)
{
Iterator itr = initialValues.keySet().iterator();
while(itr.hasNext())
{
String name = (String) itr.next();
register(name, initialValues.get(name));
}
}
}
public ObjectRegistry (ObjectRegistry parent) {
this.parent = parent;
}
// register an<SUF>
public void register (String name, Object obj) {
reg.put (name, obj);
}
// unregister an object (silent if unknown name)
public void unregister (String name) {
reg.remove (name);
}
// lookup an object: cascade up if needed
public Object lookup (String name) throws IllegalArgumentException {
Object obj = reg.get (name);
if (obj == null && parent != null) {
obj = parent.lookup (name);
}
if (obj == null) {
throw new IllegalArgumentException ("object '" + name + "' not in registry");
}
return obj;
}
} | False | 418 | 4 | 451 | 4 | 476 | 4 | 451 | 4 | 524 | 4 | false | false | false | false | false | true |
4,710 | 181382_10 | /**
* This algorithm finds the center(s) of a tree.
*
* <p>Time complexity: O(V+E)
*
* @author Original author: Jeffrey Xiao, https://github.com/jeffrey-xiao
* @author Modifications by: William Fiset, [email protected]
*/
package com.williamfiset.algorithms.graphtheory.treealgorithms;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class TreeCenter {
public static List<Integer> findTreeCenters(List<List<Integer>> tree) {
final int n = tree.size();
int[] degree = new int[n];
// Find all leaf nodes
List<Integer> leaves = new ArrayList<>();
for (int i = 0; i < n; i++) {
List<Integer> edges = tree.get(i);
degree[i] = edges.size();
if (degree[i] <= 1) {
leaves.add(i);
degree[i] = 0;
}
}
int processedLeafs = leaves.size();
// Remove leaf nodes and decrease the degree of each node adding new leaf nodes progressively
// until only the centers remain.
while (processedLeafs < n) {
List<Integer> newLeaves = new ArrayList<>();
for (int node : leaves) {
for (int neighbor : tree.get(node)) {
if (--degree[neighbor] == 1) {
newLeaves.add(neighbor);
}
}
degree[node] = 0;
}
processedLeafs += newLeaves.size();
leaves = newLeaves;
}
return leaves;
}
/** ********** TESTING ********* */
// Create an empty tree as a adjacency list.
public static List<List<Integer>> createEmptyTree(int n) {
List<List<Integer>> tree = new ArrayList<>(n);
for (int i = 0; i < n; i++) tree.add(new LinkedList<>());
return tree;
}
public static void addUndirectedEdge(List<List<Integer>> tree, int from, int to) {
tree.get(from).add(to);
tree.get(to).add(from);
}
public static void main(String[] args) {
List<List<Integer>> graph = createEmptyTree(9);
addUndirectedEdge(graph, 0, 1);
addUndirectedEdge(graph, 2, 1);
addUndirectedEdge(graph, 2, 3);
addUndirectedEdge(graph, 3, 4);
addUndirectedEdge(graph, 5, 3);
addUndirectedEdge(graph, 2, 6);
addUndirectedEdge(graph, 6, 7);
addUndirectedEdge(graph, 6, 8);
// Centers are 2
System.out.println(findTreeCenters(graph));
// Centers are 0
List<List<Integer>> graph2 = createEmptyTree(1);
System.out.println(findTreeCenters(graph2));
// Centers are 0,1
List<List<Integer>> graph3 = createEmptyTree(2);
addUndirectedEdge(graph3, 0, 1);
System.out.println(findTreeCenters(graph3));
// Centers are 1
List<List<Integer>> graph4 = createEmptyTree(3);
addUndirectedEdge(graph4, 0, 1);
addUndirectedEdge(graph4, 1, 2);
System.out.println(findTreeCenters(graph4));
// Centers are 1,2
List<List<Integer>> graph5 = createEmptyTree(4);
addUndirectedEdge(graph5, 0, 1);
addUndirectedEdge(graph5, 1, 2);
addUndirectedEdge(graph5, 2, 3);
System.out.println(findTreeCenters(graph5));
// Centers are 2,3
List<List<Integer>> graph6 = createEmptyTree(7);
addUndirectedEdge(graph6, 0, 1);
addUndirectedEdge(graph6, 1, 2);
addUndirectedEdge(graph6, 2, 3);
addUndirectedEdge(graph6, 3, 4);
addUndirectedEdge(graph6, 4, 5);
addUndirectedEdge(graph6, 4, 6);
System.out.println(findTreeCenters(graph6));
}
}
| williamfiset/Algorithms | src/main/java/com/williamfiset/algorithms/graphtheory/treealgorithms/TreeCenter.java | 1,206 | // Centers are 2,3 | line_comment | nl | /**
* This algorithm finds the center(s) of a tree.
*
* <p>Time complexity: O(V+E)
*
* @author Original author: Jeffrey Xiao, https://github.com/jeffrey-xiao
* @author Modifications by: William Fiset, [email protected]
*/
package com.williamfiset.algorithms.graphtheory.treealgorithms;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class TreeCenter {
public static List<Integer> findTreeCenters(List<List<Integer>> tree) {
final int n = tree.size();
int[] degree = new int[n];
// Find all leaf nodes
List<Integer> leaves = new ArrayList<>();
for (int i = 0; i < n; i++) {
List<Integer> edges = tree.get(i);
degree[i] = edges.size();
if (degree[i] <= 1) {
leaves.add(i);
degree[i] = 0;
}
}
int processedLeafs = leaves.size();
// Remove leaf nodes and decrease the degree of each node adding new leaf nodes progressively
// until only the centers remain.
while (processedLeafs < n) {
List<Integer> newLeaves = new ArrayList<>();
for (int node : leaves) {
for (int neighbor : tree.get(node)) {
if (--degree[neighbor] == 1) {
newLeaves.add(neighbor);
}
}
degree[node] = 0;
}
processedLeafs += newLeaves.size();
leaves = newLeaves;
}
return leaves;
}
/** ********** TESTING ********* */
// Create an empty tree as a adjacency list.
public static List<List<Integer>> createEmptyTree(int n) {
List<List<Integer>> tree = new ArrayList<>(n);
for (int i = 0; i < n; i++) tree.add(new LinkedList<>());
return tree;
}
public static void addUndirectedEdge(List<List<Integer>> tree, int from, int to) {
tree.get(from).add(to);
tree.get(to).add(from);
}
public static void main(String[] args) {
List<List<Integer>> graph = createEmptyTree(9);
addUndirectedEdge(graph, 0, 1);
addUndirectedEdge(graph, 2, 1);
addUndirectedEdge(graph, 2, 3);
addUndirectedEdge(graph, 3, 4);
addUndirectedEdge(graph, 5, 3);
addUndirectedEdge(graph, 2, 6);
addUndirectedEdge(graph, 6, 7);
addUndirectedEdge(graph, 6, 8);
// Centers are 2
System.out.println(findTreeCenters(graph));
// Centers are 0
List<List<Integer>> graph2 = createEmptyTree(1);
System.out.println(findTreeCenters(graph2));
// Centers are 0,1
List<List<Integer>> graph3 = createEmptyTree(2);
addUndirectedEdge(graph3, 0, 1);
System.out.println(findTreeCenters(graph3));
// Centers are 1
List<List<Integer>> graph4 = createEmptyTree(3);
addUndirectedEdge(graph4, 0, 1);
addUndirectedEdge(graph4, 1, 2);
System.out.println(findTreeCenters(graph4));
// Centers are 1,2
List<List<Integer>> graph5 = createEmptyTree(4);
addUndirectedEdge(graph5, 0, 1);
addUndirectedEdge(graph5, 1, 2);
addUndirectedEdge(graph5, 2, 3);
System.out.println(findTreeCenters(graph5));
// Centers are<SUF>
List<List<Integer>> graph6 = createEmptyTree(7);
addUndirectedEdge(graph6, 0, 1);
addUndirectedEdge(graph6, 1, 2);
addUndirectedEdge(graph6, 2, 3);
addUndirectedEdge(graph6, 3, 4);
addUndirectedEdge(graph6, 4, 5);
addUndirectedEdge(graph6, 4, 6);
System.out.println(findTreeCenters(graph6));
}
}
| False | 941 | 7 | 1,074 | 8 | 1,124 | 7 | 1,074 | 8 | 1,218 | 8 | false | false | false | false | false | true |
2,833 | 621_35 | /**************************************************************************/
/* GodotLib.java */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
package org.godotengine.godot;
import org.godotengine.godot.gl.GodotRenderer;
import org.godotengine.godot.io.directory.DirectoryAccessHandler;
import org.godotengine.godot.io.file.FileAccessHandler;
import org.godotengine.godot.tts.GodotTTS;
import org.godotengine.godot.utils.GodotNetUtils;
import android.app.Activity;
import android.content.res.AssetManager;
import android.hardware.SensorEvent;
import android.view.Surface;
import javax.microedition.khronos.opengles.GL10;
/**
* Wrapper for native library
*/
public class GodotLib {
static {
System.loadLibrary("godot_android");
}
/**
* Invoked on the main thread to initialize Godot native layer.
*/
public static native boolean initialize(Activity activity,
Godot p_instance,
AssetManager p_asset_manager,
GodotIO godotIO,
GodotNetUtils netUtils,
DirectoryAccessHandler directoryAccessHandler,
FileAccessHandler fileAccessHandler,
boolean use_apk_expansion);
/**
* Invoked on the main thread to clean up Godot native layer.
* @see androidx.fragment.app.Fragment#onDestroy()
*/
public static native void ondestroy();
/**
* Invoked on the GL thread to complete setup for the Godot native layer logic.
* @param p_cmdline Command line arguments used to configure Godot native layer components.
*/
public static native boolean setup(String[] p_cmdline, GodotTTS tts);
/**
* Invoked on the GL thread when the underlying Android surface has changed size.
* @param p_surface
* @param p_width
* @param p_height
* @see org.godotengine.godot.gl.GLSurfaceView.Renderer#onSurfaceChanged(GL10, int, int)
*/
public static native void resize(Surface p_surface, int p_width, int p_height);
/**
* Invoked on the render thread when the underlying Android surface is created or recreated.
* @param p_surface
*/
public static native void newcontext(Surface p_surface);
/**
* Forward {@link Activity#onBackPressed()} event.
*/
public static native void back();
/**
* Invoked on the GL thread to draw the current frame.
* @see org.godotengine.godot.gl.GLSurfaceView.Renderer#onDrawFrame(GL10)
*/
public static native boolean step();
/**
* TTS callback.
*/
public static native void ttsCallback(int event, int id, int pos);
/**
* Forward touch events.
*/
public static native void dispatchTouchEvent(int event, int pointer, int pointerCount, float[] positions, boolean doubleTap);
/**
* Dispatch mouse events
*/
public static native void dispatchMouseEvent(int event, int buttonMask, float x, float y, float deltaX, float deltaY, boolean doubleClick, boolean sourceMouseRelative, float pressure, float tiltX, float tiltY);
public static native void magnify(float x, float y, float factor);
public static native void pan(float x, float y, float deltaX, float deltaY);
/**
* Forward accelerometer sensor events.
* @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent)
*/
public static native void accelerometer(float x, float y, float z);
/**
* Forward gravity sensor events.
* @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent)
*/
public static native void gravity(float x, float y, float z);
/**
* Forward magnetometer sensor events.
* @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent)
*/
public static native void magnetometer(float x, float y, float z);
/**
* Forward gyroscope sensor events.
* @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent)
*/
public static native void gyroscope(float x, float y, float z);
/**
* Forward regular key events.
*/
public static native void key(int p_physical_keycode, int p_unicode, int p_key_label, boolean p_pressed, boolean p_echo);
/**
* Forward game device's key events.
*/
public static native void joybutton(int p_device, int p_but, boolean p_pressed);
/**
* Forward joystick devices axis motion events.
*/
public static native void joyaxis(int p_device, int p_axis, float p_value);
/**
* Forward joystick devices hat motion events.
*/
public static native void joyhat(int p_device, int p_hat_x, int p_hat_y);
/**
* Fires when a joystick device is added or removed.
*/
public static native void joyconnectionchanged(int p_device, boolean p_connected, String p_name);
/**
* Invoked when the Android app resumes.
* @see androidx.fragment.app.Fragment#onResume()
*/
public static native void focusin();
/**
* Invoked when the Android app pauses.
* @see androidx.fragment.app.Fragment#onPause()
*/
public static native void focusout();
/**
* Used to access Godot global properties.
* @param p_key Property key
* @return String value of the property
*/
public static native String getGlobal(String p_key);
/**
* Used to access Godot's editor settings.
* @param settingKey Setting key
* @return String value of the setting
*/
public static native String getEditorSetting(String settingKey);
/**
* Invoke method |p_method| on the Godot object specified by |p_id|
* @param p_id Id of the Godot object to invoke
* @param p_method Name of the method to invoke
* @param p_params Parameters to use for method invocation
*/
public static native void callobject(long p_id, String p_method, Object[] p_params);
/**
* Invoke method |p_method| on the Godot object specified by |p_id| during idle time.
* @param p_id Id of the Godot object to invoke
* @param p_method Name of the method to invoke
* @param p_params Parameters to use for method invocation
*/
public static native void calldeferred(long p_id, String p_method, Object[] p_params);
/**
* Forward the results from a permission request.
* @see Activity#onRequestPermissionsResult(int, String[], int[])
* @param p_permission Request permission
* @param p_result True if the permission was granted, false otherwise
*/
public static native void requestPermissionResult(String p_permission, boolean p_result);
/**
* Invoked on the theme light/dark mode change.
*/
public static native void onNightModeChanged();
/**
* Invoked on the GL thread to configure the height of the virtual keyboard.
*/
public static native void setVirtualKeyboardHeight(int p_height);
/**
* Invoked on the GL thread when the {@link GodotRenderer} has been resumed.
* @see GodotRenderer#onActivityResumed()
*/
public static native void onRendererResumed();
/**
* Invoked on the GL thread when the {@link GodotRenderer} has been paused.
* @see GodotRenderer#onActivityPaused()
*/
public static native void onRendererPaused();
}
| godotengine/godot | platform/android/java/lib/src/org/godotengine/godot/GodotLib.java | 2,457 | /**
* Forward magnetometer sensor events.
* @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent)
*/ | block_comment | nl | /**************************************************************************/
/* GodotLib.java */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
package org.godotengine.godot;
import org.godotengine.godot.gl.GodotRenderer;
import org.godotengine.godot.io.directory.DirectoryAccessHandler;
import org.godotengine.godot.io.file.FileAccessHandler;
import org.godotengine.godot.tts.GodotTTS;
import org.godotengine.godot.utils.GodotNetUtils;
import android.app.Activity;
import android.content.res.AssetManager;
import android.hardware.SensorEvent;
import android.view.Surface;
import javax.microedition.khronos.opengles.GL10;
/**
* Wrapper for native library
*/
public class GodotLib {
static {
System.loadLibrary("godot_android");
}
/**
* Invoked on the main thread to initialize Godot native layer.
*/
public static native boolean initialize(Activity activity,
Godot p_instance,
AssetManager p_asset_manager,
GodotIO godotIO,
GodotNetUtils netUtils,
DirectoryAccessHandler directoryAccessHandler,
FileAccessHandler fileAccessHandler,
boolean use_apk_expansion);
/**
* Invoked on the main thread to clean up Godot native layer.
* @see androidx.fragment.app.Fragment#onDestroy()
*/
public static native void ondestroy();
/**
* Invoked on the GL thread to complete setup for the Godot native layer logic.
* @param p_cmdline Command line arguments used to configure Godot native layer components.
*/
public static native boolean setup(String[] p_cmdline, GodotTTS tts);
/**
* Invoked on the GL thread when the underlying Android surface has changed size.
* @param p_surface
* @param p_width
* @param p_height
* @see org.godotengine.godot.gl.GLSurfaceView.Renderer#onSurfaceChanged(GL10, int, int)
*/
public static native void resize(Surface p_surface, int p_width, int p_height);
/**
* Invoked on the render thread when the underlying Android surface is created or recreated.
* @param p_surface
*/
public static native void newcontext(Surface p_surface);
/**
* Forward {@link Activity#onBackPressed()} event.
*/
public static native void back();
/**
* Invoked on the GL thread to draw the current frame.
* @see org.godotengine.godot.gl.GLSurfaceView.Renderer#onDrawFrame(GL10)
*/
public static native boolean step();
/**
* TTS callback.
*/
public static native void ttsCallback(int event, int id, int pos);
/**
* Forward touch events.
*/
public static native void dispatchTouchEvent(int event, int pointer, int pointerCount, float[] positions, boolean doubleTap);
/**
* Dispatch mouse events
*/
public static native void dispatchMouseEvent(int event, int buttonMask, float x, float y, float deltaX, float deltaY, boolean doubleClick, boolean sourceMouseRelative, float pressure, float tiltX, float tiltY);
public static native void magnify(float x, float y, float factor);
public static native void pan(float x, float y, float deltaX, float deltaY);
/**
* Forward accelerometer sensor events.
* @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent)
*/
public static native void accelerometer(float x, float y, float z);
/**
* Forward gravity sensor events.
* @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent)
*/
public static native void gravity(float x, float y, float z);
/**
* Forward magnetometer sensor<SUF>*/
public static native void magnetometer(float x, float y, float z);
/**
* Forward gyroscope sensor events.
* @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent)
*/
public static native void gyroscope(float x, float y, float z);
/**
* Forward regular key events.
*/
public static native void key(int p_physical_keycode, int p_unicode, int p_key_label, boolean p_pressed, boolean p_echo);
/**
* Forward game device's key events.
*/
public static native void joybutton(int p_device, int p_but, boolean p_pressed);
/**
* Forward joystick devices axis motion events.
*/
public static native void joyaxis(int p_device, int p_axis, float p_value);
/**
* Forward joystick devices hat motion events.
*/
public static native void joyhat(int p_device, int p_hat_x, int p_hat_y);
/**
* Fires when a joystick device is added or removed.
*/
public static native void joyconnectionchanged(int p_device, boolean p_connected, String p_name);
/**
* Invoked when the Android app resumes.
* @see androidx.fragment.app.Fragment#onResume()
*/
public static native void focusin();
/**
* Invoked when the Android app pauses.
* @see androidx.fragment.app.Fragment#onPause()
*/
public static native void focusout();
/**
* Used to access Godot global properties.
* @param p_key Property key
* @return String value of the property
*/
public static native String getGlobal(String p_key);
/**
* Used to access Godot's editor settings.
* @param settingKey Setting key
* @return String value of the setting
*/
public static native String getEditorSetting(String settingKey);
/**
* Invoke method |p_method| on the Godot object specified by |p_id|
* @param p_id Id of the Godot object to invoke
* @param p_method Name of the method to invoke
* @param p_params Parameters to use for method invocation
*/
public static native void callobject(long p_id, String p_method, Object[] p_params);
/**
* Invoke method |p_method| on the Godot object specified by |p_id| during idle time.
* @param p_id Id of the Godot object to invoke
* @param p_method Name of the method to invoke
* @param p_params Parameters to use for method invocation
*/
public static native void calldeferred(long p_id, String p_method, Object[] p_params);
/**
* Forward the results from a permission request.
* @see Activity#onRequestPermissionsResult(int, String[], int[])
* @param p_permission Request permission
* @param p_result True if the permission was granted, false otherwise
*/
public static native void requestPermissionResult(String p_permission, boolean p_result);
/**
* Invoked on the theme light/dark mode change.
*/
public static native void onNightModeChanged();
/**
* Invoked on the GL thread to configure the height of the virtual keyboard.
*/
public static native void setVirtualKeyboardHeight(int p_height);
/**
* Invoked on the GL thread when the {@link GodotRenderer} has been resumed.
* @see GodotRenderer#onActivityResumed()
*/
public static native void onRendererResumed();
/**
* Invoked on the GL thread when the {@link GodotRenderer} has been paused.
* @see GodotRenderer#onActivityPaused()
*/
public static native void onRendererPaused();
}
| False | 1,912 | 28 | 2,174 | 30 | 2,274 | 32 | 2,174 | 30 | 2,570 | 37 | false | false | false | false | false | true |
2,727 | 14191_10 | import java.util.ArrayList;
import java.util.HashMap;
public class Threshold
{
/**
* Returns a Threshold value. Everything BELOW this threshold should be cut
* off (noise).
*
* @return
*/
public float findThreshold_old(KDE KDE)
{
ArrayList<Float> switches = findSwitches(KDE);
if(switches == null || switches.isEmpty())
return 0;
/*
* To cut off the noise, we check if the last switch contains lots of
* 'steps' compared to previous switches. If this is the case, we can be
* certain that this is noise. One other thing we apply is that if the
* amount of steps between two consecutive switches is very small, we
* merge these two according to the mergeThreshold parameter.
*/
//TODO: aanpassen door testen.
float mergeThreshold = 0;//(float) Math.PI / 3 / Constants.Threshold.STEPCOUNT * maxThreshold;
log("MergeThreshold: " + mergeThreshold);
boolean noiseDetected = false;
//Loop through all the switches, starting from the back.
for (int i = switches.size() - 2; i >= 0; i -= 2)
{
//If the following breaks, we found a cluster.
if (Math.abs(switches.get(i) - switches.get(i + 1)) > mergeThreshold)
{
break; // Als het een cluster is dan breakt ie altijd. Als het
} // noise is kan hij breaken.
// Als hij niet breekt is het sowieso noise.
noiseDetected = true;
switches.remove(i + 1);
switches.remove(i);
}
if (noiseDetected) // we hebben sowieso noise, dus laatste eraf halen
{
// Hak laatste eraf
//switches.remove(switches.size() - 1);
//switches.remove(switches.size() - 1);
}
else // het is niet zeker of we noise hebben, bepaal dit
{
//calculate average
float totalDifference = 0;
int totalSteps = 0;
for (int i = 0; i < switches.size() - 3; i += 2)
{
totalDifference += Math.abs(switches.get(i)
+ switches.get(i + 1));
totalSteps++;
}
// de average van alle switches behalve de laatste
int averageSteps = (int) Math.ceil(totalDifference / totalSteps);
float maximalDeviation = averageSteps * 0f; // TODO: Deviation
// 1.4f bepalen door
// testen
if (switches.size() >= 2 && Math.abs(switches.get(switches.size() - 1)
- switches.get(switches.size() - 2)) > maximalDeviation)
{
// Laatste is noise dus die hakken we eraf
switches.remove(switches.size() - 1);
switches.remove(switches.size() - 1);
}
}
return switches.size() == 0 ? 0 : switches.get(switches.size() - 1);
}
public float findThreshold_old2(KDE KDE)
{
ArrayList<Float> switches = findSwitches(KDE);
if(switches == null || switches.isEmpty())
return 0;
//Remove 'noise'
switches.remove(switches.size() - 1);
switches.remove(switches.size() - 1);
return switches.get(switches.size() - 1);
}
public float findThreshold(KDE KDE)
{
int previousNumberOfPoints = 0;
int numberOfPoints = 0;
float minThreshold = KDE.getMinPointDensity();
float maxThreshold = KDE.getMaxCellDensity();
float step = maxThreshold / getStepCount(KDE);
float currentThreshold = 0;
int switchCount = 0;
boolean inSwitch = true;
for(currentThreshold = minThreshold; currentThreshold <= maxThreshold; currentThreshold += step)
{
numberOfPoints = KDE.getPointCountAboveThreshold(currentThreshold);
if(currentThreshold == minThreshold)
{
previousNumberOfPoints = numberOfPoints;
continue;
}
//log("currentThrehsold: " + currentThreshold + " | numberOfPoints: " +
// numberOfPoints + " | prev#Points: " + previousNumberOfPoints +
// "switchCount: " + switchCount);
//Utils.log(""+KDE.scaledField.getCell(KDE.sortedPoints[numberOfPoints-1]).getDensity());
//Utils.log(""+KDE.scaledField.getCell(KDE.sortedPoints[numberOfPoints]).getDensity());
//Utils.log(""+KDE.scaledField.getCell(KDE.sortedPoints[numberOfPoints+1]).getDensity());
//currentThreshold =
// KDE.scaledField.getCell(KDE.sortedPoints[numberOfPoints]).getDensity();
if(numberOfPoints == previousNumberOfPoints)
{
if(inSwitch)
{
switchCount++;
if(switchCount == 2)
break;
}
inSwitch = false;
}
else
{
inSwitch = true;
}
previousNumberOfPoints = numberOfPoints;
}
return currentThreshold - 2 * step;
}
ArrayList<Float> findSwitches(KDE KDE)
{
//Array that stores the 'switch-densities' between point counts. So between element 0 and 1 there
//are changes in the point counts, between element 2 and 3, etc.
ArrayList<Float> switches = new ArrayList<Float>();
//Used for generating a graph of densities/pointcounts
HashMap<Float, Integer> pointCounts = new HashMap<Float, Integer>();
float maxThreshold = KDE.getMaxCellDensity();
int previousNumberOfPoints = 0;
boolean inCluster = false; //Variable indicating whether we are currently 'in' a cluster in our algorithm.
float step = maxThreshold / getStepCount(KDE); //The step value indicates how fine we should partition the density range.
if (maxThreshold == 0)
{
log("Step too small: " + step + " maxThreshold: " + maxThreshold + " - Threshold stopped.");
return null; //If the step value is 0, it we can stop right away because the algorithm will fail.
}
//Start looping through the thresholds. We start at the max density and go down one step value each iteration.
float currentThreshold;
for (currentThreshold = maxThreshold; currentThreshold >= 0; currentThreshold -= step)
{
int numberOfPoints = KDE.getPointCountAboveThreshold(currentThreshold);
pointCounts.put(currentThreshold, numberOfPoints);
//If the current number of points is larger than the previous number of points we are apparently iterating
//in a cluster.
if (numberOfPoints > previousNumberOfPoints)
{
//If we are not yet iterating in a cluster, we apparently started in a new one.
if (!inCluster)
{
switches.add(currentThreshold);
}
inCluster = true;
}
else
{
//There was no change in the number of points, so if we were iterating in a cluster we have now found the end of it.
if (inCluster)
{
switches.add(currentThreshold);
inCluster = false;
}
}
previousNumberOfPoints = numberOfPoints;
}
if (inCluster && !Utils.floatAlmostEquals(switches.get(switches.size() - 1), currentThreshold))
{
switches.add(currentThreshold); //The 'closing' density hasn't been added yet.
}
assert switches.size() % 2 == 0; //The amount of switches should be equal because we have a start and end value for each switch.
//Because we subtract step each time, we will eventually might get to a negative value. Since we don't have negative
//densities, make it zero.
if (switches.get(switches.size() - 1) < 0)
{
switches.set(switches.size() - 1, 0f);
}
if (Constants.DEBUG)
{
log("Switches size: " + switches.size());
for (int i = 0; i <= switches.size() - 2; i += 2)
{
log("Switch " + i + ": " + switches.get(i) + " | Switch " + (i + 1) + ": " + switches.get(i + 1));
}
Graphing.graphPointCounts(pointCounts);
}
return switches;
}
int getStepCount(KDE KDE)
{
if(KDE.field.size() > 100000)
return 1000;
else if(KDE.field.size() > 7000)
return 300;
else
return 100;
}
void log(String message)
{
Utils.log("Threshold", message);
}
}
| francoisvdv/FwbClusterFinder | FwbAlgorithm/src/Threshold.java | 2,480 | // Hak laatste eraf | line_comment | nl | import java.util.ArrayList;
import java.util.HashMap;
public class Threshold
{
/**
* Returns a Threshold value. Everything BELOW this threshold should be cut
* off (noise).
*
* @return
*/
public float findThreshold_old(KDE KDE)
{
ArrayList<Float> switches = findSwitches(KDE);
if(switches == null || switches.isEmpty())
return 0;
/*
* To cut off the noise, we check if the last switch contains lots of
* 'steps' compared to previous switches. If this is the case, we can be
* certain that this is noise. One other thing we apply is that if the
* amount of steps between two consecutive switches is very small, we
* merge these two according to the mergeThreshold parameter.
*/
//TODO: aanpassen door testen.
float mergeThreshold = 0;//(float) Math.PI / 3 / Constants.Threshold.STEPCOUNT * maxThreshold;
log("MergeThreshold: " + mergeThreshold);
boolean noiseDetected = false;
//Loop through all the switches, starting from the back.
for (int i = switches.size() - 2; i >= 0; i -= 2)
{
//If the following breaks, we found a cluster.
if (Math.abs(switches.get(i) - switches.get(i + 1)) > mergeThreshold)
{
break; // Als het een cluster is dan breakt ie altijd. Als het
} // noise is kan hij breaken.
// Als hij niet breekt is het sowieso noise.
noiseDetected = true;
switches.remove(i + 1);
switches.remove(i);
}
if (noiseDetected) // we hebben sowieso noise, dus laatste eraf halen
{
// Hak laatste<SUF>
//switches.remove(switches.size() - 1);
//switches.remove(switches.size() - 1);
}
else // het is niet zeker of we noise hebben, bepaal dit
{
//calculate average
float totalDifference = 0;
int totalSteps = 0;
for (int i = 0; i < switches.size() - 3; i += 2)
{
totalDifference += Math.abs(switches.get(i)
+ switches.get(i + 1));
totalSteps++;
}
// de average van alle switches behalve de laatste
int averageSteps = (int) Math.ceil(totalDifference / totalSteps);
float maximalDeviation = averageSteps * 0f; // TODO: Deviation
// 1.4f bepalen door
// testen
if (switches.size() >= 2 && Math.abs(switches.get(switches.size() - 1)
- switches.get(switches.size() - 2)) > maximalDeviation)
{
// Laatste is noise dus die hakken we eraf
switches.remove(switches.size() - 1);
switches.remove(switches.size() - 1);
}
}
return switches.size() == 0 ? 0 : switches.get(switches.size() - 1);
}
public float findThreshold_old2(KDE KDE)
{
ArrayList<Float> switches = findSwitches(KDE);
if(switches == null || switches.isEmpty())
return 0;
//Remove 'noise'
switches.remove(switches.size() - 1);
switches.remove(switches.size() - 1);
return switches.get(switches.size() - 1);
}
public float findThreshold(KDE KDE)
{
int previousNumberOfPoints = 0;
int numberOfPoints = 0;
float minThreshold = KDE.getMinPointDensity();
float maxThreshold = KDE.getMaxCellDensity();
float step = maxThreshold / getStepCount(KDE);
float currentThreshold = 0;
int switchCount = 0;
boolean inSwitch = true;
for(currentThreshold = minThreshold; currentThreshold <= maxThreshold; currentThreshold += step)
{
numberOfPoints = KDE.getPointCountAboveThreshold(currentThreshold);
if(currentThreshold == minThreshold)
{
previousNumberOfPoints = numberOfPoints;
continue;
}
//log("currentThrehsold: " + currentThreshold + " | numberOfPoints: " +
// numberOfPoints + " | prev#Points: " + previousNumberOfPoints +
// "switchCount: " + switchCount);
//Utils.log(""+KDE.scaledField.getCell(KDE.sortedPoints[numberOfPoints-1]).getDensity());
//Utils.log(""+KDE.scaledField.getCell(KDE.sortedPoints[numberOfPoints]).getDensity());
//Utils.log(""+KDE.scaledField.getCell(KDE.sortedPoints[numberOfPoints+1]).getDensity());
//currentThreshold =
// KDE.scaledField.getCell(KDE.sortedPoints[numberOfPoints]).getDensity();
if(numberOfPoints == previousNumberOfPoints)
{
if(inSwitch)
{
switchCount++;
if(switchCount == 2)
break;
}
inSwitch = false;
}
else
{
inSwitch = true;
}
previousNumberOfPoints = numberOfPoints;
}
return currentThreshold - 2 * step;
}
ArrayList<Float> findSwitches(KDE KDE)
{
//Array that stores the 'switch-densities' between point counts. So between element 0 and 1 there
//are changes in the point counts, between element 2 and 3, etc.
ArrayList<Float> switches = new ArrayList<Float>();
//Used for generating a graph of densities/pointcounts
HashMap<Float, Integer> pointCounts = new HashMap<Float, Integer>();
float maxThreshold = KDE.getMaxCellDensity();
int previousNumberOfPoints = 0;
boolean inCluster = false; //Variable indicating whether we are currently 'in' a cluster in our algorithm.
float step = maxThreshold / getStepCount(KDE); //The step value indicates how fine we should partition the density range.
if (maxThreshold == 0)
{
log("Step too small: " + step + " maxThreshold: " + maxThreshold + " - Threshold stopped.");
return null; //If the step value is 0, it we can stop right away because the algorithm will fail.
}
//Start looping through the thresholds. We start at the max density and go down one step value each iteration.
float currentThreshold;
for (currentThreshold = maxThreshold; currentThreshold >= 0; currentThreshold -= step)
{
int numberOfPoints = KDE.getPointCountAboveThreshold(currentThreshold);
pointCounts.put(currentThreshold, numberOfPoints);
//If the current number of points is larger than the previous number of points we are apparently iterating
//in a cluster.
if (numberOfPoints > previousNumberOfPoints)
{
//If we are not yet iterating in a cluster, we apparently started in a new one.
if (!inCluster)
{
switches.add(currentThreshold);
}
inCluster = true;
}
else
{
//There was no change in the number of points, so if we were iterating in a cluster we have now found the end of it.
if (inCluster)
{
switches.add(currentThreshold);
inCluster = false;
}
}
previousNumberOfPoints = numberOfPoints;
}
if (inCluster && !Utils.floatAlmostEquals(switches.get(switches.size() - 1), currentThreshold))
{
switches.add(currentThreshold); //The 'closing' density hasn't been added yet.
}
assert switches.size() % 2 == 0; //The amount of switches should be equal because we have a start and end value for each switch.
//Because we subtract step each time, we will eventually might get to a negative value. Since we don't have negative
//densities, make it zero.
if (switches.get(switches.size() - 1) < 0)
{
switches.set(switches.size() - 1, 0f);
}
if (Constants.DEBUG)
{
log("Switches size: " + switches.size());
for (int i = 0; i <= switches.size() - 2; i += 2)
{
log("Switch " + i + ": " + switches.get(i) + " | Switch " + (i + 1) + ": " + switches.get(i + 1));
}
Graphing.graphPointCounts(pointCounts);
}
return switches;
}
int getStepCount(KDE KDE)
{
if(KDE.field.size() > 100000)
return 1000;
else if(KDE.field.size() > 7000)
return 300;
else
return 100;
}
void log(String message)
{
Utils.log("Threshold", message);
}
}
| True | 2,068 | 6 | 2,306 | 8 | 2,255 | 5 | 2,306 | 8 | 2,851 | 7 | false | false | false | false | false | true |
2,043 | 75388_9 | /*
* (c) 2008-2017 Jens Mueller
*
* Kleincomputer-Emulator
*
* Klasse fuer die Emulation
* des Anschlusses des Magnettonbandgeraetes (Eingang),
* indem die Audiodaten von einer Datei gelesen werden.
*/
package jkcemu.audio;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import jkcemu.base.EmuUtil;
import jkcemu.base.FileInfo;
import jkcemu.emusys.kc85.KCAudioCreator;
import jkcemu.emusys.zxspectrum.ZXSpectrumAudioCreator;
import z80emu.Z80CPU;
public class AudioInFile extends AudioIn
{
private File file;
private int offs;
private boolean progressEnabled;
private PCMDataSource pcmIn;
private byte[] frameBuf;
private long frameCnt;
private long framePos;
private int progressStepSize;
private int progressStepCnt;
private int speedKHz;
private int eofNoiseFrames;
private Random eofNoiseRandom;
private volatile boolean pause;
public AudioInFile(
AudioIOObserver observer,
Z80CPU z80cpu,
int speedKHz,
File file,
byte[] fileBytes, // kann null sein
int offs ) throws IOException
{
super( observer, z80cpu );
this.file = file;
this.offs = offs;
this.progressEnabled = false;
this.pcmIn = null;
this.frameBuf = null;
this.frameCnt = 0L;
this.framePos = 0L;
this.progressStepSize = 0;
this.progressStepCnt = 0;
this.speedKHz = speedKHz;
this.eofNoiseFrames = 0;
this.eofNoiseRandom = null;
this.pause = true;
String fileFmtText = null;
try {
boolean isTAP = false;
if( (fileBytes == null) && (file != null) ) {
if( file.isFile() ) {
String fName = file.getName();
if( fName != null ) {
fName = fName.toLowerCase();
isTAP = fName.endsWith( ".tap" ) || fName.endsWith( ".tap.gz" );
fileBytes = EmuUtil.readFile(
file,
true,
AudioUtil.FILE_READ_MAX );
}
}
}
if( fileBytes != null ) {
/*
* Wird in der Mitte einer Multi-Tape-Datei begonnen,
* soll auch die Fortschrittsanzeige in der Mitte beginnen.
* Aus diesem Grund wird in dem Fall sowohl die Gesamtlaenge
* als auch die Restlaenge der Multi-Tape-Datei ermittelt.
*/
if( FileInfo.isCswMagicAt( fileBytes, this.offs ) ) {
this.pcmIn = CSWFile.getPCMDataSource( fileBytes, 0 );
this.frameCnt = this.pcmIn.getFrameCount();
this.framePos = 0;
if( this.offs > 0 ) {
// Resetlaenge ermitteln und Fotschrittsanzeige anpassen
this.pcmIn = CSWFile.getPCMDataSource(
fileBytes,
this.offs );
this.framePos = this.frameCnt - this.pcmIn.getFrameCount();
}
fileFmtText = "CSW-Datei";
} else if( FileInfo.isKCTapMagicAt( fileBytes, this.offs ) ) {
// Gesamtlaenge der Datei ermitteln
this.pcmIn = new KCAudioCreator(
true,
0,
fileBytes,
0,
fileBytes.length ).newReader();
this.frameCnt = this.pcmIn.getFrameCount();
this.framePos = 0;
if( this.offs > 0 ) {
// Resetlaenge ermitteln und Fotschrittsanzeige anpassen
this.pcmIn = new KCAudioCreator(
true,
0,
fileBytes,
this.offs,
fileBytes.length - this.offs ).newReader();
this.framePos = this.frameCnt - this.pcmIn.getFrameCount();
}
fileFmtText = "KC-TAP-Datei";
} else {
boolean isTZX = FileInfo.isTzxMagicAt( fileBytes, this.offs );
if( isTAP || isTZX ) {
// Gesamtlaenge der Datei ermitteln
this.pcmIn = new ZXSpectrumAudioCreator(
fileBytes,
0,
fileBytes.length ).newReader();
this.frameCnt = this.pcmIn.getFrameCount();
this.framePos = 0;
if( this.offs > 0 ) {
// Resetlaenge ermitteln und Fotschrittsanzeige anpassen
this.pcmIn = new ZXSpectrumAudioCreator(
fileBytes,
this.offs,
fileBytes.length - this.offs ).newReader();
this.framePos = this.frameCnt - this.pcmIn.getFrameCount();
}
if( isTZX ) {
fileFmtText = "CDT/TZX-Datei";
} else {
fileFmtText = "ZX-TAP-Datei";
}
}
}
}
if( this.pcmIn == null ) {
this.pcmIn = AudioFile.open( file, fileBytes );
this.frameCnt = this.pcmIn.getFrameCount();
this.framePos = 0;
}
if( this.pcmIn == null ) {
throw new IOException();
}
if( this.frameCnt <= 0 ) {
throw new IOException( "Die Datei enth\u00E4lt keine Daten" );
}
setFormat(
this.pcmIn.getFrameRate(),
this.pcmIn.getSampleSizeInBits(),
this.pcmIn.getChannels(),
this.pcmIn.isSigned(),
this.pcmIn.isBigEndian() );
if( fileFmtText != null ) {
if( this.formatText != null ) {
this.formatText = fileFmtText + ": " + this.formatText;
} else {
this.formatText = fileFmtText;
}
}
if( this.framePos < 0 ) {
this.framePos = 0;
}
this.progressStepSize = (int) this.frameCnt / 200;
this.progressStepCnt = this.progressStepSize;
this.progressEnabled = true;
this.firstCall = true;
this.observer.fireProgressUpdate( this );
int sampleSize = (this.pcmIn.getSampleSizeInBits() + 7) / 8;
this.frameBuf = new byte[ sampleSize * this.pcmIn.getChannels() ];
this.tStatesPerFrame = (int) (((float) speedKHz) * 1000.0F
/ (float) this.pcmIn.getFrameRate());
}
catch( IOException ex ) {
closeStreams();
String msg = ex.getMessage();
if( msg != null ) {
if( msg.isEmpty() ) {
msg = null;
}
}
if( msg != null ) {
throw ex;
} else {
throw new IOException( "Die Datei kann nicht ge\u00F6ffnet werden." );
}
}
}
public File getFile()
{
return this.file;
}
public long getFrameCount()
{
return this.frameCnt;
}
public long getFramePos()
{
return this.framePos;
}
public int getSpeedKHz()
{
return this.speedKHz;
}
public void setFramePos( long pos ) throws IOException
{
PCMDataSource in = this.pcmIn;
if( in != null ) {
if( pos < 0 ) {
pos = 0;
} else if( pos > this.frameCnt ) {
pos = this.frameCnt;
}
in.setFramePos( pos );
this.framePos = pos;
}
}
public void setPause( boolean state )
{
this.pause = state;
}
public boolean supportsSetFramePos()
{
PCMDataSource in = this.pcmIn;
return in != null ? in.supportsSetFramePos() : false;
}
/* --- ueberschriebene Methoden --- */
@Override
public boolean isPause()
{
return this.pause;
}
@Override
public boolean isProgressUpdateEnabled()
{
return this.progressEnabled;
}
@Override
public void stopAudio()
{
closeMonitorLine();
closeStreams();
this.frameBuf = null;
this.progressEnabled = false;
}
@Override
protected boolean supportsMonitor()
{
return true;
}
@Override
protected byte[] readFrame()
{
byte[] buf = this.frameBuf;
if( (this.eofNoiseRandom != null) && (buf != null) ) {
this.eofNoiseRandom.nextBytes( buf );
if( this.eofNoiseFrames > 0 ) {
--this.eofNoiseFrames;
} else {
this.observer.fireFinished( this, null );
}
} else {
PCMDataSource in = this.pcmIn;
if( (in != null) && (buf != null) ) {
try {
if( in.read( buf, 0, buf.length ) == buf.length ) {
if( isMonitorActive() ) {
writeMonitorLine( buf );
}
this.framePos++;
if( this.progressStepCnt > 0 ) {
--this.progressStepCnt;
} else {
this.progressStepCnt = this.progressStepSize;
this.observer.fireProgressUpdate( this );
}
} else {
closeStreams();
this.eofNoiseFrames = this.frameRate / 20;
this.eofNoiseRandom = new Random( System.currentTimeMillis() );
}
}
catch( IOException ex ) {
stopAudio();
this.observer.fireFinished( this, ex.getMessage() );
}
}
}
return buf;
}
/* --- private Methoden --- */
private void closeStreams()
{
EmuUtil.closeSilent( this.pcmIn );
this.pcmIn = null;
}
}
| anchorz/jkcemu | src/jkcemu/audio/AudioInFile.java | 3,050 | /* --- private Methoden --- */ | block_comment | nl | /*
* (c) 2008-2017 Jens Mueller
*
* Kleincomputer-Emulator
*
* Klasse fuer die Emulation
* des Anschlusses des Magnettonbandgeraetes (Eingang),
* indem die Audiodaten von einer Datei gelesen werden.
*/
package jkcemu.audio;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import jkcemu.base.EmuUtil;
import jkcemu.base.FileInfo;
import jkcemu.emusys.kc85.KCAudioCreator;
import jkcemu.emusys.zxspectrum.ZXSpectrumAudioCreator;
import z80emu.Z80CPU;
public class AudioInFile extends AudioIn
{
private File file;
private int offs;
private boolean progressEnabled;
private PCMDataSource pcmIn;
private byte[] frameBuf;
private long frameCnt;
private long framePos;
private int progressStepSize;
private int progressStepCnt;
private int speedKHz;
private int eofNoiseFrames;
private Random eofNoiseRandom;
private volatile boolean pause;
public AudioInFile(
AudioIOObserver observer,
Z80CPU z80cpu,
int speedKHz,
File file,
byte[] fileBytes, // kann null sein
int offs ) throws IOException
{
super( observer, z80cpu );
this.file = file;
this.offs = offs;
this.progressEnabled = false;
this.pcmIn = null;
this.frameBuf = null;
this.frameCnt = 0L;
this.framePos = 0L;
this.progressStepSize = 0;
this.progressStepCnt = 0;
this.speedKHz = speedKHz;
this.eofNoiseFrames = 0;
this.eofNoiseRandom = null;
this.pause = true;
String fileFmtText = null;
try {
boolean isTAP = false;
if( (fileBytes == null) && (file != null) ) {
if( file.isFile() ) {
String fName = file.getName();
if( fName != null ) {
fName = fName.toLowerCase();
isTAP = fName.endsWith( ".tap" ) || fName.endsWith( ".tap.gz" );
fileBytes = EmuUtil.readFile(
file,
true,
AudioUtil.FILE_READ_MAX );
}
}
}
if( fileBytes != null ) {
/*
* Wird in der Mitte einer Multi-Tape-Datei begonnen,
* soll auch die Fortschrittsanzeige in der Mitte beginnen.
* Aus diesem Grund wird in dem Fall sowohl die Gesamtlaenge
* als auch die Restlaenge der Multi-Tape-Datei ermittelt.
*/
if( FileInfo.isCswMagicAt( fileBytes, this.offs ) ) {
this.pcmIn = CSWFile.getPCMDataSource( fileBytes, 0 );
this.frameCnt = this.pcmIn.getFrameCount();
this.framePos = 0;
if( this.offs > 0 ) {
// Resetlaenge ermitteln und Fotschrittsanzeige anpassen
this.pcmIn = CSWFile.getPCMDataSource(
fileBytes,
this.offs );
this.framePos = this.frameCnt - this.pcmIn.getFrameCount();
}
fileFmtText = "CSW-Datei";
} else if( FileInfo.isKCTapMagicAt( fileBytes, this.offs ) ) {
// Gesamtlaenge der Datei ermitteln
this.pcmIn = new KCAudioCreator(
true,
0,
fileBytes,
0,
fileBytes.length ).newReader();
this.frameCnt = this.pcmIn.getFrameCount();
this.framePos = 0;
if( this.offs > 0 ) {
// Resetlaenge ermitteln und Fotschrittsanzeige anpassen
this.pcmIn = new KCAudioCreator(
true,
0,
fileBytes,
this.offs,
fileBytes.length - this.offs ).newReader();
this.framePos = this.frameCnt - this.pcmIn.getFrameCount();
}
fileFmtText = "KC-TAP-Datei";
} else {
boolean isTZX = FileInfo.isTzxMagicAt( fileBytes, this.offs );
if( isTAP || isTZX ) {
// Gesamtlaenge der Datei ermitteln
this.pcmIn = new ZXSpectrumAudioCreator(
fileBytes,
0,
fileBytes.length ).newReader();
this.frameCnt = this.pcmIn.getFrameCount();
this.framePos = 0;
if( this.offs > 0 ) {
// Resetlaenge ermitteln und Fotschrittsanzeige anpassen
this.pcmIn = new ZXSpectrumAudioCreator(
fileBytes,
this.offs,
fileBytes.length - this.offs ).newReader();
this.framePos = this.frameCnt - this.pcmIn.getFrameCount();
}
if( isTZX ) {
fileFmtText = "CDT/TZX-Datei";
} else {
fileFmtText = "ZX-TAP-Datei";
}
}
}
}
if( this.pcmIn == null ) {
this.pcmIn = AudioFile.open( file, fileBytes );
this.frameCnt = this.pcmIn.getFrameCount();
this.framePos = 0;
}
if( this.pcmIn == null ) {
throw new IOException();
}
if( this.frameCnt <= 0 ) {
throw new IOException( "Die Datei enth\u00E4lt keine Daten" );
}
setFormat(
this.pcmIn.getFrameRate(),
this.pcmIn.getSampleSizeInBits(),
this.pcmIn.getChannels(),
this.pcmIn.isSigned(),
this.pcmIn.isBigEndian() );
if( fileFmtText != null ) {
if( this.formatText != null ) {
this.formatText = fileFmtText + ": " + this.formatText;
} else {
this.formatText = fileFmtText;
}
}
if( this.framePos < 0 ) {
this.framePos = 0;
}
this.progressStepSize = (int) this.frameCnt / 200;
this.progressStepCnt = this.progressStepSize;
this.progressEnabled = true;
this.firstCall = true;
this.observer.fireProgressUpdate( this );
int sampleSize = (this.pcmIn.getSampleSizeInBits() + 7) / 8;
this.frameBuf = new byte[ sampleSize * this.pcmIn.getChannels() ];
this.tStatesPerFrame = (int) (((float) speedKHz) * 1000.0F
/ (float) this.pcmIn.getFrameRate());
}
catch( IOException ex ) {
closeStreams();
String msg = ex.getMessage();
if( msg != null ) {
if( msg.isEmpty() ) {
msg = null;
}
}
if( msg != null ) {
throw ex;
} else {
throw new IOException( "Die Datei kann nicht ge\u00F6ffnet werden." );
}
}
}
public File getFile()
{
return this.file;
}
public long getFrameCount()
{
return this.frameCnt;
}
public long getFramePos()
{
return this.framePos;
}
public int getSpeedKHz()
{
return this.speedKHz;
}
public void setFramePos( long pos ) throws IOException
{
PCMDataSource in = this.pcmIn;
if( in != null ) {
if( pos < 0 ) {
pos = 0;
} else if( pos > this.frameCnt ) {
pos = this.frameCnt;
}
in.setFramePos( pos );
this.framePos = pos;
}
}
public void setPause( boolean state )
{
this.pause = state;
}
public boolean supportsSetFramePos()
{
PCMDataSource in = this.pcmIn;
return in != null ? in.supportsSetFramePos() : false;
}
/* --- ueberschriebene Methoden --- */
@Override
public boolean isPause()
{
return this.pause;
}
@Override
public boolean isProgressUpdateEnabled()
{
return this.progressEnabled;
}
@Override
public void stopAudio()
{
closeMonitorLine();
closeStreams();
this.frameBuf = null;
this.progressEnabled = false;
}
@Override
protected boolean supportsMonitor()
{
return true;
}
@Override
protected byte[] readFrame()
{
byte[] buf = this.frameBuf;
if( (this.eofNoiseRandom != null) && (buf != null) ) {
this.eofNoiseRandom.nextBytes( buf );
if( this.eofNoiseFrames > 0 ) {
--this.eofNoiseFrames;
} else {
this.observer.fireFinished( this, null );
}
} else {
PCMDataSource in = this.pcmIn;
if( (in != null) && (buf != null) ) {
try {
if( in.read( buf, 0, buf.length ) == buf.length ) {
if( isMonitorActive() ) {
writeMonitorLine( buf );
}
this.framePos++;
if( this.progressStepCnt > 0 ) {
--this.progressStepCnt;
} else {
this.progressStepCnt = this.progressStepSize;
this.observer.fireProgressUpdate( this );
}
} else {
closeStreams();
this.eofNoiseFrames = this.frameRate / 20;
this.eofNoiseRandom = new Random( System.currentTimeMillis() );
}
}
catch( IOException ex ) {
stopAudio();
this.observer.fireFinished( this, ex.getMessage() );
}
}
}
return buf;
}
/* --- private Methoden<SUF>*/
private void closeStreams()
{
EmuUtil.closeSilent( this.pcmIn );
this.pcmIn = null;
}
}
| False | 2,292 | 7 | 2,548 | 7 | 2,714 | 6 | 2,548 | 7 | 3,075 | 7 | false | false | false | false | false | true |
3,366 | 213651_19 | package domein;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
/**
*
* @author samuelvandamme
*/
public class DownloadThread implements Runnable {
private final Queue queue = Queue.getInstance();
private String website;
private String dir;
private int currentDepth;
private int maxDepth;
private List<Email> emailList = new ArrayList<Email>();
public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public int getCurrentDepth() {
return currentDepth;
}
public void setCurrentDepth(int depth) {
this.currentDepth = depth;
}
public int getMaxDepth() {
return maxDepth;
}
public void setMaxDepth(int depth) {
this.maxDepth = depth;
}
public DownloadThread() {
}
public DownloadThread(String website, String dir) {
this(website, dir, 0, 0);
}
public DownloadThread(String website, String dir, int currentDepth, int maxDepth) {
setWebsite(website);
setDir(dir);
setCurrentDepth(currentDepth);
setMaxDepth(maxDepth);
}
public void execute(Runnable r) {
synchronized (queue) {
if (!queue.contains(r)) {
queue.addLast(r);
System.out.println("Added " + getWebsite() + " to queue. (" + getDir() + ")");
}
queue.notify();
}
}
@Override
public void run() {
Document doc = null;
InputStream input = null;
URI uri = null;
// Debug
System.out.println("Fetching " + website);
String fileLok = dir + ((currentDepth > 0) ? getLocalFileName(getPathWithFilename(website)) : "index.html");
// Bestaat lokaal bestand
File bestand = new File(fileLok);
if (bestand.exists()) {
return;
}
// Bestand ophalen
try {
uri = new URI(website);
input = uri.toURL().openStream();
} catch (URISyntaxException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
} catch (MalformedURLException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
// Type controleren
String type = getMimeType(website);
if (type.equals("text/html")) {
// HTML Parsen
try {
doc = Jsoup.parse(input, null, getBaseUrl(website));
} catch (IOException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, website + " niet afgehaald.", ex);
return;
}
// base tags moeten leeg zijn
doc.getElementsByTag("base").remove();
// Script tags leeg maken => krijgen veel te veel errors => soms blijven pagina's hangen hierdoor
doc.getElementsByTag("script").remove();
// Afbeeldingen
for (Element image : doc.getElementsByTag("img")) {
// Afbeelding ophalen
addToQueue(getPath(image.attr("src")));
// Afbeelding zijn source vervangen door een MD5 hash
image.attr("src", getLocalFileName(getPathWithFilename(image.attr("src"))));
}
// CSS bestanden
for (Element cssFile : doc.getElementsByTag("link")) {
if(cssFile.attr("rel").equals("stylesheet")) {
// CSS bestand ophalen
addToQueue(getPath(cssFile.attr("href")));
// CSS bestand zijn verwijziging vervangen door een MD5 hash
cssFile.attr("href", getLocalFileName(getPathWithFilename(cssFile.attr("href"))));
}
}
// Links overlopen
for (Element link : doc.getElementsByTag("a")) {
if (link.attr("href").contains("#") || link.attr("href").startsWith("ftp://")) {
continue;
}
// Link toevoegen
if (!(link.attr("href")).contains("mailto")) {
if(link.attr("href").equals(".")) {
link.attr("href", "index.html");
continue;
}
if(link.attr("href").startsWith("http") && isExternal(link.attr("href"), website))
{
addExternalLink(link.attr("href"));
}
else
{
if(maxDepth > 0 && currentDepth >= maxDepth)
continue;
addToQueue(getPath(link.attr("href")));
link.attr("href", getLocalFileName(getPathWithFilename(getPath(link.attr("href")))));
}
}
else if ((link.attr("href")).contains("mailto")) {
addEmail(link.attr("href").replace("mailto:", ""));
}
}
}
System.out.println("Save to " + bestand.getAbsolutePath());
createFile(bestand);
// Save
if (type.equals("text/html")) {
saveHtml(bestand, doc.html());
} else {
saveBinary(bestand, input);
}
// Close
try {
input.close();
} catch (IOException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void addToQueue(String url) {
execute(new DownloadThread(url, dir, currentDepth + 1, maxDepth));
}
public void createFile(File bestand) {
// Maak bestand en dir's aan
try {
if (bestand.getParentFile() != null) {
bestand.getParentFile().mkdirs();
}
System.out.println("Path " + bestand.getAbsolutePath());
bestand.createNewFile();
} catch (IOException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void saveHtml(File bestand, String html) {
// Open bestand
BufferedWriter output = null;
try {
output = new BufferedWriter(new FileWriter(bestand));
} catch (IOException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
try {
output.write(html);
} catch (IOException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
// Close it
try {
output.close();
} catch (IOException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void saveBinary(File bestand, InputStream input) {
FileOutputStream output = null;
try {
output = new FileOutputStream(bestand);
} catch (FileNotFoundException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] buffer = new byte[4096];
int bytesRead;
try {
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
} catch (IOException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
try {
input.close();
output.close();
} catch (IOException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String getPath(String url) {
String result = "fail";
try {
// Indien het url niet start met http, https of ftp er het huidige url voorplakken
if(!url.startsWith("http") && !url.startsWith("https") && !url.startsWith("ftp"))
{
// Indien het url start met '/', eruithalen, anders krijgen we bijvoorbeeld http://www.hln.be//Page/14/01/2011/...
url = getBaseUrl(website) + (url.startsWith("/") ? url.substring(1) : url);
}
URI path = new URI(url.replace(" ", "%20")); // Redelijk hacky, zou een betere oplossing voor moeten zijn
result = path.toString();
} catch (URISyntaxException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
public String getPathWithFilename(String url) {
String result = getPath(url);
result = result.replace("http://", "");
if ((result.length() > 1 && result.charAt(result.length() - 1) == '/') || result.length() == 0) {
return dir + result + "index.html";
} else {
return dir + result;
}
}
public String getBaseUrl(String url) {
// Path ophalen
try {
URI path = new URI(url);
String host = "http://" + path.toURL().getHost();
return host.endsWith("/") ? host : (host + "/");
} catch (URISyntaxException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
} catch (MalformedURLException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
return "fail";
}
public String getMimeType(String url) {
URL uri = null;
String result = "";
try {
uri = new URL(url);
} catch (MalformedURLException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
try {
result = ((URLConnection) uri.openConnection()).getContentType();
if (result.indexOf(";") != -1) {
return result.substring(0, result.indexOf(";"));
} else {
return result;
}
} catch (IOException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
return "text/unknown";
}
}
private void addEmail(String mail) {
Email email = new Email(mail);
emailList.add(email);
System.out.println("Email found and added: " + email.getAddress());
}
private void addExternalLink(String link) {
ExternalLink elink = new ExternalLink(link);
System.out.println("External Link found and added. link: " + link);
}
public boolean isExternal(String attr, String website) {
URI check = null;
URI source = null;
try {
check = new URI(attr);
source = new URI(website);
} catch (URISyntaxException ex) {
return true;
}
if ( check.getHost().equals(source.getHost()))
return false;
return true;
}
public String getLocalFileName(String name)
{
try {
byte[] bytesOfMessage = name.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytesOfMessage);
String extension = getExtension(name);
return new BigInteger(1,thedigest).toString(16) + ("".equals(extension) ? "" : "." + extension);
} catch (Exception ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
return "0";
}
public String getExtension(String url)
{
// Haal de extensie uit het URL
// We starten altijd met html
String extension = "html";
// Indien een website gebruik maakt van ? in het url, bv, http://www.google.be/test.html?a=152&b=535
// split op het vraagteken en gebruik de linker helft.
url = url.split("\\?")[0];
if(url.contains(".")) {
int mid = url.lastIndexOf(".");
extension = url.substring(mid + 1, url.length());
// Enkele extensies willen we vervangen + indien het resultaat eindigt
// op een / of \ wil het zeggen dat het url bijvoorbeeld http://www.google.com/nieuws/ was.
// De extensie is dan gewoon .html
if(extension.equals("php") || extension.equals("dhtml") || extension.equals("aspx") || extension.equals("asp") ||
extension.contains("\\") || extension.contains("/")){
extension = "html";
}
}
return extension;
}
}
| kidk/tin_scrapy | src/domein/DownloadThread.java | 3,804 | // De extensie is dan gewoon .html | line_comment | nl | package domein;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
/**
*
* @author samuelvandamme
*/
public class DownloadThread implements Runnable {
private final Queue queue = Queue.getInstance();
private String website;
private String dir;
private int currentDepth;
private int maxDepth;
private List<Email> emailList = new ArrayList<Email>();
public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public int getCurrentDepth() {
return currentDepth;
}
public void setCurrentDepth(int depth) {
this.currentDepth = depth;
}
public int getMaxDepth() {
return maxDepth;
}
public void setMaxDepth(int depth) {
this.maxDepth = depth;
}
public DownloadThread() {
}
public DownloadThread(String website, String dir) {
this(website, dir, 0, 0);
}
public DownloadThread(String website, String dir, int currentDepth, int maxDepth) {
setWebsite(website);
setDir(dir);
setCurrentDepth(currentDepth);
setMaxDepth(maxDepth);
}
public void execute(Runnable r) {
synchronized (queue) {
if (!queue.contains(r)) {
queue.addLast(r);
System.out.println("Added " + getWebsite() + " to queue. (" + getDir() + ")");
}
queue.notify();
}
}
@Override
public void run() {
Document doc = null;
InputStream input = null;
URI uri = null;
// Debug
System.out.println("Fetching " + website);
String fileLok = dir + ((currentDepth > 0) ? getLocalFileName(getPathWithFilename(website)) : "index.html");
// Bestaat lokaal bestand
File bestand = new File(fileLok);
if (bestand.exists()) {
return;
}
// Bestand ophalen
try {
uri = new URI(website);
input = uri.toURL().openStream();
} catch (URISyntaxException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
} catch (MalformedURLException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
// Type controleren
String type = getMimeType(website);
if (type.equals("text/html")) {
// HTML Parsen
try {
doc = Jsoup.parse(input, null, getBaseUrl(website));
} catch (IOException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, website + " niet afgehaald.", ex);
return;
}
// base tags moeten leeg zijn
doc.getElementsByTag("base").remove();
// Script tags leeg maken => krijgen veel te veel errors => soms blijven pagina's hangen hierdoor
doc.getElementsByTag("script").remove();
// Afbeeldingen
for (Element image : doc.getElementsByTag("img")) {
// Afbeelding ophalen
addToQueue(getPath(image.attr("src")));
// Afbeelding zijn source vervangen door een MD5 hash
image.attr("src", getLocalFileName(getPathWithFilename(image.attr("src"))));
}
// CSS bestanden
for (Element cssFile : doc.getElementsByTag("link")) {
if(cssFile.attr("rel").equals("stylesheet")) {
// CSS bestand ophalen
addToQueue(getPath(cssFile.attr("href")));
// CSS bestand zijn verwijziging vervangen door een MD5 hash
cssFile.attr("href", getLocalFileName(getPathWithFilename(cssFile.attr("href"))));
}
}
// Links overlopen
for (Element link : doc.getElementsByTag("a")) {
if (link.attr("href").contains("#") || link.attr("href").startsWith("ftp://")) {
continue;
}
// Link toevoegen
if (!(link.attr("href")).contains("mailto")) {
if(link.attr("href").equals(".")) {
link.attr("href", "index.html");
continue;
}
if(link.attr("href").startsWith("http") && isExternal(link.attr("href"), website))
{
addExternalLink(link.attr("href"));
}
else
{
if(maxDepth > 0 && currentDepth >= maxDepth)
continue;
addToQueue(getPath(link.attr("href")));
link.attr("href", getLocalFileName(getPathWithFilename(getPath(link.attr("href")))));
}
}
else if ((link.attr("href")).contains("mailto")) {
addEmail(link.attr("href").replace("mailto:", ""));
}
}
}
System.out.println("Save to " + bestand.getAbsolutePath());
createFile(bestand);
// Save
if (type.equals("text/html")) {
saveHtml(bestand, doc.html());
} else {
saveBinary(bestand, input);
}
// Close
try {
input.close();
} catch (IOException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void addToQueue(String url) {
execute(new DownloadThread(url, dir, currentDepth + 1, maxDepth));
}
public void createFile(File bestand) {
// Maak bestand en dir's aan
try {
if (bestand.getParentFile() != null) {
bestand.getParentFile().mkdirs();
}
System.out.println("Path " + bestand.getAbsolutePath());
bestand.createNewFile();
} catch (IOException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void saveHtml(File bestand, String html) {
// Open bestand
BufferedWriter output = null;
try {
output = new BufferedWriter(new FileWriter(bestand));
} catch (IOException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
try {
output.write(html);
} catch (IOException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
// Close it
try {
output.close();
} catch (IOException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void saveBinary(File bestand, InputStream input) {
FileOutputStream output = null;
try {
output = new FileOutputStream(bestand);
} catch (FileNotFoundException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] buffer = new byte[4096];
int bytesRead;
try {
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
} catch (IOException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
try {
input.close();
output.close();
} catch (IOException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String getPath(String url) {
String result = "fail";
try {
// Indien het url niet start met http, https of ftp er het huidige url voorplakken
if(!url.startsWith("http") && !url.startsWith("https") && !url.startsWith("ftp"))
{
// Indien het url start met '/', eruithalen, anders krijgen we bijvoorbeeld http://www.hln.be//Page/14/01/2011/...
url = getBaseUrl(website) + (url.startsWith("/") ? url.substring(1) : url);
}
URI path = new URI(url.replace(" ", "%20")); // Redelijk hacky, zou een betere oplossing voor moeten zijn
result = path.toString();
} catch (URISyntaxException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
public String getPathWithFilename(String url) {
String result = getPath(url);
result = result.replace("http://", "");
if ((result.length() > 1 && result.charAt(result.length() - 1) == '/') || result.length() == 0) {
return dir + result + "index.html";
} else {
return dir + result;
}
}
public String getBaseUrl(String url) {
// Path ophalen
try {
URI path = new URI(url);
String host = "http://" + path.toURL().getHost();
return host.endsWith("/") ? host : (host + "/");
} catch (URISyntaxException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
} catch (MalformedURLException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
return "fail";
}
public String getMimeType(String url) {
URL uri = null;
String result = "";
try {
uri = new URL(url);
} catch (MalformedURLException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
try {
result = ((URLConnection) uri.openConnection()).getContentType();
if (result.indexOf(";") != -1) {
return result.substring(0, result.indexOf(";"));
} else {
return result;
}
} catch (IOException ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
return "text/unknown";
}
}
private void addEmail(String mail) {
Email email = new Email(mail);
emailList.add(email);
System.out.println("Email found and added: " + email.getAddress());
}
private void addExternalLink(String link) {
ExternalLink elink = new ExternalLink(link);
System.out.println("External Link found and added. link: " + link);
}
public boolean isExternal(String attr, String website) {
URI check = null;
URI source = null;
try {
check = new URI(attr);
source = new URI(website);
} catch (URISyntaxException ex) {
return true;
}
if ( check.getHost().equals(source.getHost()))
return false;
return true;
}
public String getLocalFileName(String name)
{
try {
byte[] bytesOfMessage = name.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytesOfMessage);
String extension = getExtension(name);
return new BigInteger(1,thedigest).toString(16) + ("".equals(extension) ? "" : "." + extension);
} catch (Exception ex) {
Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
}
return "0";
}
public String getExtension(String url)
{
// Haal de extensie uit het URL
// We starten altijd met html
String extension = "html";
// Indien een website gebruik maakt van ? in het url, bv, http://www.google.be/test.html?a=152&b=535
// split op het vraagteken en gebruik de linker helft.
url = url.split("\\?")[0];
if(url.contains(".")) {
int mid = url.lastIndexOf(".");
extension = url.substring(mid + 1, url.length());
// Enkele extensies willen we vervangen + indien het resultaat eindigt
// op een / of \ wil het zeggen dat het url bijvoorbeeld http://www.google.com/nieuws/ was.
// De extensie<SUF>
if(extension.equals("php") || extension.equals("dhtml") || extension.equals("aspx") || extension.equals("asp") ||
extension.contains("\\") || extension.contains("/")){
extension = "html";
}
}
return extension;
}
}
| True | 2,806 | 12 | 3,160 | 12 | 3,377 | 10 | 3,160 | 12 | 3,789 | 11 | false | false | false | false | false | true |
1,524 | 31702_2 | /*
* 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.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Date;
import be.derycke.pieter.com.COMException;
import be.derycke.pieter.com.OleDate;
//gemeenschappelijke klasse voor storage en folder
abstract class AbstractPortableDeviceContainerImplWin32 extends PortableDeviceObjectImplWin32 {
AbstractPortableDeviceContainerImplWin32(String objectID,PortableDeviceContentImplWin32 content,
PortableDevicePropertiesImplWin32 properties) {
super(objectID,content,properties);
}
public PortableDeviceObject[] getChildObjects() {
try {
String[] childIDs=content.listChildObjects(objectID);
PortableDeviceObject[] objects=new PortableDeviceObject[childIDs.length];
for(int i=0;i<childIDs.length;i++)
objects[i]=WPDImplWin32.convertToPortableDeviceObject(childIDs[i],this.content,this.properties);
return objects;
} catch (COMException e) {
return new PortableDeviceObject[0];
}
}
public PortableDeviceFolderObject createFolderObject(String name) {
try {
PortableDeviceValuesImplWin32 values=new PortableDeviceValuesImplWin32();
values.setStringValue(Win32WPDDefines.WPD_OBJECT_PARENT_ID,this.objectID);
values.setStringValue(Win32WPDDefines.WPD_OBJECT_ORIGINAL_FILE_NAME,name);
values.setStringValue(Win32WPDDefines.WPD_OBJECT_NAME,name);
values.setGuidValue(Win32WPDDefines.WPD_OBJECT_CONTENT_TYPE,Win32WPDDefines.WPD_CONTENT_TYPE_FOLDER);
return new PortableDeviceFolderObjectImplWin32(content.createObjectWithPropertiesOnly(values),this.content,this.properties);
} catch (COMException e) {
e.printStackTrace();
return null;
}
}
// TODO references ondersteuning nog toevoegen
public PortableDevicePlaylistObject createPlaylistObject(String name,PortableDeviceObject[] references) {
try {
PortableDeviceValuesImplWin32 values=new PortableDeviceValuesImplWin32();
values.setStringValue(Win32WPDDefines.WPD_OBJECT_PARENT_ID,this.objectID);
values.setStringValue(Win32WPDDefines.WPD_OBJECT_ORIGINAL_FILE_NAME,name+".pla");
values.setStringValue(Win32WPDDefines.WPD_OBJECT_NAME,name);
values.setGuidValue(Win32WPDDefines.WPD_OBJECT_FORMAT,Win32WPDDefines.WPD_OBJECT_FORMAT_PLA);
values.setGuidValue(Win32WPDDefines.WPD_OBJECT_CONTENT_TYPE,Win32WPDDefines.WPD_CONTENT_TYPE_PLAYLIST);
if (references!=null) {
PortableDevicePropVariantCollectionImplWin32 propVariantCollection=new PortableDevicePropVariantCollectionImplWin32();
for(PortableDeviceObject reference:references)
propVariantCollection.add(new PropVariant(reference.getID()));
values.setPortableDeviceValuesCollectionValue(Win32WPDDefines.WPD_OBJECT_REFERENCES,propVariantCollection);
}
return new PortableDevicePlaylistObjectImplWin32(content.createObjectWithPropertiesOnly(values),this.content,this.properties);
} catch (COMException e) {
e.printStackTrace();
return null;
}
}
public String addObject(File file) throws FileNotFoundException,IOException {
try {
PortableDeviceValuesImplWin32 values=new PortableDeviceValuesImplWin32();
values.setStringValue(Win32WPDDefines.WPD_OBJECT_PARENT_ID,this.objectID);
values.setStringValue(Win32WPDDefines.WPD_OBJECT_ORIGINAL_FILE_NAME,file.getName());
return(content.createObjectWithPropertiesAndData(values,file));
} catch (COMException e) {
if (e.getHresult()==Win32WPDDefines.E_FILENOTFOUND)
throw new FileNotFoundException("File "+file+" was not found.");
else {
throw new IOException(e);
}
}
}
public PortableDeviceAudioObject addAudioObject(File file,String artist,String title,BigInteger duration)
throws FileNotFoundException,IOException {
return addAudioObject(file,artist,title,duration,null,null,null,-1);
}
public PortableDeviceAudioObject addAudioObject(File file,String artist,String title,BigInteger duration,String genre,
String album,Date releaseDate,int track) throws FileNotFoundException,IOException {
try {
PortableDeviceValuesImplWin32 values=new PortableDeviceValuesImplWin32();
values.setStringValue(Win32WPDDefines.WPD_OBJECT_PARENT_ID,this.objectID);
values.setStringValue(Win32WPDDefines.WPD_OBJECT_ORIGINAL_FILE_NAME,file.getName());
values.setGuidValue(Win32WPDDefines.WPD_OBJECT_FORMAT,Win32WPDDefines.WPD_OBJECT_FORMAT_MP3); // TODO nog manier vinden om
// type te detecteren
values.setGuidValue(Win32WPDDefines.WPD_OBJECT_CONTENT_TYPE,Win32WPDDefines.WPD_CONTENT_TYPE_AUDIO);
values.setStringValue(Win32WPDDefines.WPD_OBJECT_NAME,title);
if (artist!=null)
values.setStringValue(Win32WPDDefines.WPD_MEDIA_ARTIST,artist);
values.setUnsignedLargeIntegerValue(Win32WPDDefines.WPD_MEDIA_DURATION,duration);
if (genre!=null)
values.setStringValue(Win32WPDDefines.WPD_MEDIA_GENRE,genre);
if (album!=null)
values.setStringValue(Win32WPDDefines.WPD_MUSIC_ALBUM,album);
if (releaseDate!=null)
values.setFloateValue(Win32WPDDefines.WPD_MEDIA_RELEASE_DATE,(float)new OleDate(releaseDate).toDouble());
if (track>=0)
values.setUnsignedIntegerValue(Win32WPDDefines.WPD_MUSIC_TRACK,track);
return new PortableDeviceAudioObjectImplWin32(content.createObjectWithPropertiesAndData(values,file),this.content,
this.properties);
} catch (COMException e) {
if (e.getHresult()==Win32WPDDefines.E_FILENOTFOUND)
throw new FileNotFoundException("File "+file+" was not found.");
else {
throw new IOException(e);
}
}
}
}
| SRARAD/Brieflet | PPTConvert/src/jmtp/AbstractPortableDeviceContainerImplWin32.java | 2,089 | // TODO references ondersteuning nog toevoegen | 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.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Date;
import be.derycke.pieter.com.COMException;
import be.derycke.pieter.com.OleDate;
//gemeenschappelijke klasse voor storage en folder
abstract class AbstractPortableDeviceContainerImplWin32 extends PortableDeviceObjectImplWin32 {
AbstractPortableDeviceContainerImplWin32(String objectID,PortableDeviceContentImplWin32 content,
PortableDevicePropertiesImplWin32 properties) {
super(objectID,content,properties);
}
public PortableDeviceObject[] getChildObjects() {
try {
String[] childIDs=content.listChildObjects(objectID);
PortableDeviceObject[] objects=new PortableDeviceObject[childIDs.length];
for(int i=0;i<childIDs.length;i++)
objects[i]=WPDImplWin32.convertToPortableDeviceObject(childIDs[i],this.content,this.properties);
return objects;
} catch (COMException e) {
return new PortableDeviceObject[0];
}
}
public PortableDeviceFolderObject createFolderObject(String name) {
try {
PortableDeviceValuesImplWin32 values=new PortableDeviceValuesImplWin32();
values.setStringValue(Win32WPDDefines.WPD_OBJECT_PARENT_ID,this.objectID);
values.setStringValue(Win32WPDDefines.WPD_OBJECT_ORIGINAL_FILE_NAME,name);
values.setStringValue(Win32WPDDefines.WPD_OBJECT_NAME,name);
values.setGuidValue(Win32WPDDefines.WPD_OBJECT_CONTENT_TYPE,Win32WPDDefines.WPD_CONTENT_TYPE_FOLDER);
return new PortableDeviceFolderObjectImplWin32(content.createObjectWithPropertiesOnly(values),this.content,this.properties);
} catch (COMException e) {
e.printStackTrace();
return null;
}
}
// TODO references<SUF>
public PortableDevicePlaylistObject createPlaylistObject(String name,PortableDeviceObject[] references) {
try {
PortableDeviceValuesImplWin32 values=new PortableDeviceValuesImplWin32();
values.setStringValue(Win32WPDDefines.WPD_OBJECT_PARENT_ID,this.objectID);
values.setStringValue(Win32WPDDefines.WPD_OBJECT_ORIGINAL_FILE_NAME,name+".pla");
values.setStringValue(Win32WPDDefines.WPD_OBJECT_NAME,name);
values.setGuidValue(Win32WPDDefines.WPD_OBJECT_FORMAT,Win32WPDDefines.WPD_OBJECT_FORMAT_PLA);
values.setGuidValue(Win32WPDDefines.WPD_OBJECT_CONTENT_TYPE,Win32WPDDefines.WPD_CONTENT_TYPE_PLAYLIST);
if (references!=null) {
PortableDevicePropVariantCollectionImplWin32 propVariantCollection=new PortableDevicePropVariantCollectionImplWin32();
for(PortableDeviceObject reference:references)
propVariantCollection.add(new PropVariant(reference.getID()));
values.setPortableDeviceValuesCollectionValue(Win32WPDDefines.WPD_OBJECT_REFERENCES,propVariantCollection);
}
return new PortableDevicePlaylistObjectImplWin32(content.createObjectWithPropertiesOnly(values),this.content,this.properties);
} catch (COMException e) {
e.printStackTrace();
return null;
}
}
public String addObject(File file) throws FileNotFoundException,IOException {
try {
PortableDeviceValuesImplWin32 values=new PortableDeviceValuesImplWin32();
values.setStringValue(Win32WPDDefines.WPD_OBJECT_PARENT_ID,this.objectID);
values.setStringValue(Win32WPDDefines.WPD_OBJECT_ORIGINAL_FILE_NAME,file.getName());
return(content.createObjectWithPropertiesAndData(values,file));
} catch (COMException e) {
if (e.getHresult()==Win32WPDDefines.E_FILENOTFOUND)
throw new FileNotFoundException("File "+file+" was not found.");
else {
throw new IOException(e);
}
}
}
public PortableDeviceAudioObject addAudioObject(File file,String artist,String title,BigInteger duration)
throws FileNotFoundException,IOException {
return addAudioObject(file,artist,title,duration,null,null,null,-1);
}
public PortableDeviceAudioObject addAudioObject(File file,String artist,String title,BigInteger duration,String genre,
String album,Date releaseDate,int track) throws FileNotFoundException,IOException {
try {
PortableDeviceValuesImplWin32 values=new PortableDeviceValuesImplWin32();
values.setStringValue(Win32WPDDefines.WPD_OBJECT_PARENT_ID,this.objectID);
values.setStringValue(Win32WPDDefines.WPD_OBJECT_ORIGINAL_FILE_NAME,file.getName());
values.setGuidValue(Win32WPDDefines.WPD_OBJECT_FORMAT,Win32WPDDefines.WPD_OBJECT_FORMAT_MP3); // TODO nog manier vinden om
// type te detecteren
values.setGuidValue(Win32WPDDefines.WPD_OBJECT_CONTENT_TYPE,Win32WPDDefines.WPD_CONTENT_TYPE_AUDIO);
values.setStringValue(Win32WPDDefines.WPD_OBJECT_NAME,title);
if (artist!=null)
values.setStringValue(Win32WPDDefines.WPD_MEDIA_ARTIST,artist);
values.setUnsignedLargeIntegerValue(Win32WPDDefines.WPD_MEDIA_DURATION,duration);
if (genre!=null)
values.setStringValue(Win32WPDDefines.WPD_MEDIA_GENRE,genre);
if (album!=null)
values.setStringValue(Win32WPDDefines.WPD_MUSIC_ALBUM,album);
if (releaseDate!=null)
values.setFloateValue(Win32WPDDefines.WPD_MEDIA_RELEASE_DATE,(float)new OleDate(releaseDate).toDouble());
if (track>=0)
values.setUnsignedIntegerValue(Win32WPDDefines.WPD_MUSIC_TRACK,track);
return new PortableDeviceAudioObjectImplWin32(content.createObjectWithPropertiesAndData(values,file),this.content,
this.properties);
} catch (COMException e) {
if (e.getHresult()==Win32WPDDefines.E_FILENOTFOUND)
throw new FileNotFoundException("File "+file+" was not found.");
else {
throw new IOException(e);
}
}
}
}
| True | 1,483 | 10 | 1,791 | 12 | 1,835 | 8 | 1,791 | 12 | 2,102 | 10 | false | false | false | false | false | true |
2,682 | 14878_1 | package com.baeldung.rss;
import java.sql.Date;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.feed.AbstractRssFeedView;
import com.rometools.rome.feed.rss.Channel;
import com.rometools.rome.feed.rss.Item;
/**
* View for a RSS feed.
*
* @author Donato Rimenti
*/
@Component
public class RssFeedView extends AbstractRssFeedView {
/*
* (non-Javadoc)
*
* @see org.springframework.web.servlet.view.feed.AbstractFeedView#
* buildFeedMetadata(java.util.Map, com.rometools.rome.feed.WireFeed,
* javax.servlet.http.HttpServletRequest)
*/
@Override
protected void buildFeedMetadata(Map<String, Object> model, Channel feed, HttpServletRequest request) {
feed.setTitle("Baeldung RSS Feed");
feed.setDescription("Learn how to program in Java");
feed.setLink("http://www.baeldung.com");
}
/*
* (non-Javadoc)
*
* @see org.springframework.web.servlet.view.feed.AbstractRssFeedView#
* buildFeedItems(java.util.Map, javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
@Override
protected List<Item> buildFeedItems(Map<String, Object> model, HttpServletRequest request,
HttpServletResponse response) {
// Builds the single entries.
Item entryOne = new Item();
entryOne.setTitle("JUnit 5 @Test Annotation");
entryOne.setAuthor("[email protected]");
entryOne.setLink("http://www.baeldung.com/junit-5-test-annotation");
entryOne.setPubDate(Date.from(Instant.parse("2017-12-19T00:00:00Z")));
Item entryTwo = new Item();
entryTwo.setTitle("Creating and Configuring Jetty 9 Server in Java");
entryTwo.setAuthor("[email protected]");
entryTwo.setLink("http://www.baeldung.com/jetty-java-programmatic");
entryTwo.setPubDate(Date.from(Instant.parse("2018-01-23T00:00:00Z")));
Item entryThree = new Item();
entryThree.setTitle("Flyweight Pattern in Java");
entryThree.setAuthor("[email protected]");
entryThree.setLink("http://www.baeldung.com/java-flyweight");
entryThree.setPubDate(Date.from(Instant.parse("2018-02-01T00:00:00Z")));
Item entryFour = new Item();
entryFour.setTitle("Multi-Swarm Optimization Algorithm in Java");
entryFour.setAuthor("[email protected]");
entryFour.setLink("http://www.baeldung.com/java-multi-swarm-algorithm");
entryFour.setPubDate(Date.from(Instant.parse("2018-03-09T00:00:00Z")));
Item entryFive = new Item();
entryFive.setTitle("A Simple Tagging Implementation with MongoDB");
entryFive.setAuthor("[email protected]");
entryFive.setLink("http://www.baeldung.com/mongodb-tagging");
entryFive.setPubDate(Date.from(Instant.parse("2018-03-27T00:00:00Z")));
Item entrySix = new Item();
entrySix.setTitle("Double-Checked Locking with Singleton");
entrySix.setAuthor("[email protected]");
entrySix.setLink("http://www.baeldung.com/java-singleton-double-checked-locking");
entrySix.setPubDate(Date.from(Instant.parse("2018-04-23T00:00:00Z")));
Item entrySeven = new Item();
entrySeven.setTitle("Introduction to Dagger 2");
entrySeven.setAuthor("[email protected]");
entrySeven.setLink("http://www.baeldung.com/dagger-2");
entrySeven.setPubDate(Date.from(Instant.parse("2018-06-30T00:00:00Z")));
// Creates the feed.
return Arrays.asList(entryOne, entryTwo, entryThree, entryFour, entryFive, entrySix, entrySeven);
}
} | eugenp/tutorials | spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/rss/RssFeedView.java | 1,288 | /*
* (non-Javadoc)
*
* @see org.springframework.web.servlet.view.feed.AbstractFeedView#
* buildFeedMetadata(java.util.Map, com.rometools.rome.feed.WireFeed,
* javax.servlet.http.HttpServletRequest)
*/ | block_comment | nl | package com.baeldung.rss;
import java.sql.Date;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.feed.AbstractRssFeedView;
import com.rometools.rome.feed.rss.Channel;
import com.rometools.rome.feed.rss.Item;
/**
* View for a RSS feed.
*
* @author Donato Rimenti
*/
@Component
public class RssFeedView extends AbstractRssFeedView {
/*
* (non-Javadoc)
<SUF>*/
@Override
protected void buildFeedMetadata(Map<String, Object> model, Channel feed, HttpServletRequest request) {
feed.setTitle("Baeldung RSS Feed");
feed.setDescription("Learn how to program in Java");
feed.setLink("http://www.baeldung.com");
}
/*
* (non-Javadoc)
*
* @see org.springframework.web.servlet.view.feed.AbstractRssFeedView#
* buildFeedItems(java.util.Map, javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
@Override
protected List<Item> buildFeedItems(Map<String, Object> model, HttpServletRequest request,
HttpServletResponse response) {
// Builds the single entries.
Item entryOne = new Item();
entryOne.setTitle("JUnit 5 @Test Annotation");
entryOne.setAuthor("[email protected]");
entryOne.setLink("http://www.baeldung.com/junit-5-test-annotation");
entryOne.setPubDate(Date.from(Instant.parse("2017-12-19T00:00:00Z")));
Item entryTwo = new Item();
entryTwo.setTitle("Creating and Configuring Jetty 9 Server in Java");
entryTwo.setAuthor("[email protected]");
entryTwo.setLink("http://www.baeldung.com/jetty-java-programmatic");
entryTwo.setPubDate(Date.from(Instant.parse("2018-01-23T00:00:00Z")));
Item entryThree = new Item();
entryThree.setTitle("Flyweight Pattern in Java");
entryThree.setAuthor("[email protected]");
entryThree.setLink("http://www.baeldung.com/java-flyweight");
entryThree.setPubDate(Date.from(Instant.parse("2018-02-01T00:00:00Z")));
Item entryFour = new Item();
entryFour.setTitle("Multi-Swarm Optimization Algorithm in Java");
entryFour.setAuthor("[email protected]");
entryFour.setLink("http://www.baeldung.com/java-multi-swarm-algorithm");
entryFour.setPubDate(Date.from(Instant.parse("2018-03-09T00:00:00Z")));
Item entryFive = new Item();
entryFive.setTitle("A Simple Tagging Implementation with MongoDB");
entryFive.setAuthor("[email protected]");
entryFive.setLink("http://www.baeldung.com/mongodb-tagging");
entryFive.setPubDate(Date.from(Instant.parse("2018-03-27T00:00:00Z")));
Item entrySix = new Item();
entrySix.setTitle("Double-Checked Locking with Singleton");
entrySix.setAuthor("[email protected]");
entrySix.setLink("http://www.baeldung.com/java-singleton-double-checked-locking");
entrySix.setPubDate(Date.from(Instant.parse("2018-04-23T00:00:00Z")));
Item entrySeven = new Item();
entrySeven.setTitle("Introduction to Dagger 2");
entrySeven.setAuthor("[email protected]");
entrySeven.setLink("http://www.baeldung.com/dagger-2");
entrySeven.setPubDate(Date.from(Instant.parse("2018-06-30T00:00:00Z")));
// Creates the feed.
return Arrays.asList(entryOne, entryTwo, entryThree, entryFour, entryFive, entrySix, entrySeven);
}
} | False | 971 | 54 | 1,218 | 66 | 1,216 | 74 | 1,218 | 66 | 1,381 | 80 | false | false | false | false | false | true |
4,001 | 116629_18 | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* Project Info: https://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* https://plantuml.com/patreon (only 1$ per month!)
* https://plantuml.com/paypal
*
* This file is part of Smetana.
* Smetana is a partial translation of Graphviz/Dot sources from C to Java.
*
* (C) Copyright 2009-2022, Arnaud Roques
*
* This translation is distributed under the same Licence as the original C program:
*
*************************************************************************
* Copyright (c) 2011 AT&T Intellectual Property
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: See CVS logs. Details at http://www.graphviz.org/
*************************************************************************
*
* THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC
* LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0]
*
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
*
* You may obtain a copy of the License at
*
* http://www.eclipse.org/legal/epl-v10.html
*
* 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 gen.lib.cdt;
import static gen.lib.cdt.dtflatten__c.dtflatten;
import static gen.lib.cdt.dtrestore__c.dtrestore;
import static smetana.core.Macro.UNSUPPORTED;
import static smetana.core.debug.SmetanaDebug.ENTERING;
import static smetana.core.debug.SmetanaDebug.LEAVING;
import gen.annotation.Original;
import gen.annotation.Unused;
import h.ST_dt_s;
import h.ST_dtdisc_s;
import h.ST_dtlink_s;
import smetana.core.CFunction;
import smetana.core.CFunctionAbstract;
import smetana.core.CString;
import smetana.core.Globals;
import smetana.core.Memory;
import smetana.core.size_t;
public class dtdisc__c {
public static CFunction dtmemory = new CFunctionAbstract("dtmemory") {
public Object exe(Globals zz, Object... args) {
return dtmemory((ST_dt_s)args[0], (Object)args[1], (size_t)args[2], (ST_dtdisc_s)args[3]);
}};
@Unused
@Original(version="2.38.0", path="lib/cdt/dtdisc.c", name="dtmemory", key="507t9jcy6v9twvl30rs9i2nwi", definition="static void* dtmemory(Dt_t* dt,void* addr,size_t size,Dtdisc_t* disc)")
public static Object dtmemory(ST_dt_s dt, Object addr, size_t size, ST_dtdisc_s disc) {
ENTERING("507t9jcy6v9twvl30rs9i2nwi","dtmemory");
try {
if(addr!=null) {
if(size == null) {
Memory.free(addr);
return null;
}
UNSUPPORTED("9ed8imo9cbvwtwe92qmavoqko"); // else return realloc(addr,size);
}
else return size.isStrictPositive() ? size.malloc() : null;
throw new UnsupportedOperationException();
} finally {
LEAVING("507t9jcy6v9twvl30rs9i2nwi","dtmemory");
}
}
//3 axpvuswclmi9bx3qtlh4quyah
// Dtdisc_t* dtdisc(Dt_t* dt, Dtdisc_t* disc, int type)
@Unused
@Original(version="2.38.0", path="lib/cdt/dtdisc.c", name="dtdisc", key="axpvuswclmi9bx3qtlh4quyah", definition="Dtdisc_t* dtdisc(Dt_t* dt, Dtdisc_t* disc, int type)")
public static ST_dtdisc_s dtdisc(Globals zz, ST_dt_s dt, ST_dtdisc_s disc, int type) {
ENTERING("axpvuswclmi9bx3qtlh4quyah","dtdisc");
try {
CFunction searchf;
ST_dtlink_s r, t;
CString k;
ST_dtdisc_s old;
if((old = (ST_dtdisc_s) dt.disc) == null ) /* initialization call from dtopen() */
{ dt.disc = disc;
if((dt.memoryf = disc.memoryf ) == null)
dt.memoryf = dtdisc__c.dtmemory;
return disc;
}
if((disc) == null) /* only want to know current discipline */
return old;
searchf = dt.meth.searchf;
if((dt.data.type&010000)!=0) dtrestore(dt,null);
if(old.eventf!=null && ((Integer)old.eventf.exe(zz, dt,3, disc,old)) < 0)
return null;
dt.disc = disc;
if((dt.memoryf = disc.memoryf) == null)
dt.memoryf = dtdisc__c.dtmemory;
if((dt.data.type&(0000040|0000100|0000020))!=0)
UNSUPPORTED("e2tzh95k1lvjl6wbtpwizam8q"); // goto done;
else if((dt.data.type&0000002)!=0) {
UNSUPPORTED("3q5nyguq8mgdfwmm0yrzq2br8"); // if(type&0000002)
UNSUPPORTED("93q6zqzlgfz2qd0yl6koyw99c"); // goto done;
UNSUPPORTED("6d1rfacssm8768oz9fu5o66t8"); // else goto dt_renew;
}
else if((dt.data.type&(0000001|0000002))!=0) {
UNSUPPORTED("8xmm1djjds55s86jodixkp72u"); // if((type&0000002) && (type&0000001))
UNSUPPORTED("93q6zqzlgfz2qd0yl6koyw99c"); // goto done;
UNSUPPORTED("6d1rfacssm8768oz9fu5o66t8"); // else goto dt_renew;
}
else /*if(dt->data->type&(DT_OSET|DT_OBAG))*/ {
if((type&0000001)!=0)
UNSUPPORTED("93q6zqzlgfz2qd0yl6koyw99c"); // goto done;
// dt_renew:
r = dtflatten(dt);
UNSUPPORTED("1rry7yjzos90pgbf3li2qpa18"); // dt->data->type &= ~010000;
UNSUPPORTED("6vkn7padspfbtju9g5b65b34w"); // dt->data->here = ((Dtlink_t*)0);
UNSUPPORTED("2jfi30wa60xp7iqlk9yyf4k5j"); // dt->data->size = 0;
UNSUPPORTED("1i3oayy7gy36lar9kfhuq6rur"); // if(dt->data->type&(0000001|0000002))
UNSUPPORTED("ay51d19gimt3gpqjact2t0ypm"); // { register Dtlink_t **s, **ends;
UNSUPPORTED("5p6g054kk7snvpwuxudelseir"); // ends = (s = dt->data->hh._htab) + dt->data->ntab;
UNSUPPORTED("3zu1r6orkvmsvbjbzqqx9wedr"); // while(s < ends)
UNSUPPORTED("9wq8eycc78fg8sqi6bjce4q7f"); // *s++ = ((Dtlink_t*)0);
UNSUPPORTED("6eq5kf0bj692bokt0bixy1ixh"); // }
UNSUPPORTED("3rfhc462a0qx53yecw933hkk8"); // /* reinsert them */
UNSUPPORTED("ctmfjzioo5q7mzsmb6rf9mxoy"); // while(r)
UNSUPPORTED("9qxb0eqp3ujnnuum1bggqarjh"); // { t = r->right;
UNSUPPORTED("ddltpk94i08fyy6x03ozyc7s1"); // if(!(type&0000002)) /* new hash value */
UNSUPPORTED("8mj2vd7idro90tjnvl6b9trnc"); // { k = (char*)(disc->link < 0 ? ((Dthold_t*)(r))->obj : (void*)((char*)(r) - disc->link) );
UNSUPPORTED("1dvo2602az1wcigxx20czskv9"); // k = (void*)(disc->size < 0 ? *((char**)((char*)((void*)k)+disc->key)) : ((char*)((void*)k)+disc->key));
UNSUPPORTED("269t5qi8m2ujfjvmbqvyjvr1s"); // r->hl._hash = (disc->hashf ? (*disc->hashf)(dt,k,disc) : dtstrhash(0,k,disc->size) );
UNSUPPORTED("3to5h0rvqxdeqs38mhv47mm3o"); // }
UNSUPPORTED("2e2tx3ch32oxo5y01bflgbf2h"); // (void)(*searchf)(dt,(void*)r,0000040);
UNSUPPORTED("8tob14cb9u9q0mnud0wovaioi"); // r = t;
UNSUPPORTED("6eq5kf0bj692bokt0bixy1ixh"); // }
UNSUPPORTED("flupwh3kosf3fkhkxllllt1"); // }
UNSUPPORTED("cerydbb7i6l7c4pgeygvwoqk2"); // done:
UNSUPPORTED("bi0p581nen18ypj0ey48s6ete"); // return old;
}
throw new UnsupportedOperationException();
} finally {
LEAVING("axpvuswclmi9bx3qtlh4quyah","dtdisc");
}
}
}
| plantuml/plantuml | src/gen/lib/cdt/dtdisc__c.java | 3,013 | // { k = (char*)(disc->link < 0 ? ((Dthold_t*)(r))->obj : (void*)((char*)(r) - disc->link) ); | line_comment | nl | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* Project Info: https://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* https://plantuml.com/patreon (only 1$ per month!)
* https://plantuml.com/paypal
*
* This file is part of Smetana.
* Smetana is a partial translation of Graphviz/Dot sources from C to Java.
*
* (C) Copyright 2009-2022, Arnaud Roques
*
* This translation is distributed under the same Licence as the original C program:
*
*************************************************************************
* Copyright (c) 2011 AT&T Intellectual Property
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: See CVS logs. Details at http://www.graphviz.org/
*************************************************************************
*
* THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC
* LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0]
*
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
*
* You may obtain a copy of the License at
*
* http://www.eclipse.org/legal/epl-v10.html
*
* 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 gen.lib.cdt;
import static gen.lib.cdt.dtflatten__c.dtflatten;
import static gen.lib.cdt.dtrestore__c.dtrestore;
import static smetana.core.Macro.UNSUPPORTED;
import static smetana.core.debug.SmetanaDebug.ENTERING;
import static smetana.core.debug.SmetanaDebug.LEAVING;
import gen.annotation.Original;
import gen.annotation.Unused;
import h.ST_dt_s;
import h.ST_dtdisc_s;
import h.ST_dtlink_s;
import smetana.core.CFunction;
import smetana.core.CFunctionAbstract;
import smetana.core.CString;
import smetana.core.Globals;
import smetana.core.Memory;
import smetana.core.size_t;
public class dtdisc__c {
public static CFunction dtmemory = new CFunctionAbstract("dtmemory") {
public Object exe(Globals zz, Object... args) {
return dtmemory((ST_dt_s)args[0], (Object)args[1], (size_t)args[2], (ST_dtdisc_s)args[3]);
}};
@Unused
@Original(version="2.38.0", path="lib/cdt/dtdisc.c", name="dtmemory", key="507t9jcy6v9twvl30rs9i2nwi", definition="static void* dtmemory(Dt_t* dt,void* addr,size_t size,Dtdisc_t* disc)")
public static Object dtmemory(ST_dt_s dt, Object addr, size_t size, ST_dtdisc_s disc) {
ENTERING("507t9jcy6v9twvl30rs9i2nwi","dtmemory");
try {
if(addr!=null) {
if(size == null) {
Memory.free(addr);
return null;
}
UNSUPPORTED("9ed8imo9cbvwtwe92qmavoqko"); // else return realloc(addr,size);
}
else return size.isStrictPositive() ? size.malloc() : null;
throw new UnsupportedOperationException();
} finally {
LEAVING("507t9jcy6v9twvl30rs9i2nwi","dtmemory");
}
}
//3 axpvuswclmi9bx3qtlh4quyah
// Dtdisc_t* dtdisc(Dt_t* dt, Dtdisc_t* disc, int type)
@Unused
@Original(version="2.38.0", path="lib/cdt/dtdisc.c", name="dtdisc", key="axpvuswclmi9bx3qtlh4quyah", definition="Dtdisc_t* dtdisc(Dt_t* dt, Dtdisc_t* disc, int type)")
public static ST_dtdisc_s dtdisc(Globals zz, ST_dt_s dt, ST_dtdisc_s disc, int type) {
ENTERING("axpvuswclmi9bx3qtlh4quyah","dtdisc");
try {
CFunction searchf;
ST_dtlink_s r, t;
CString k;
ST_dtdisc_s old;
if((old = (ST_dtdisc_s) dt.disc) == null ) /* initialization call from dtopen() */
{ dt.disc = disc;
if((dt.memoryf = disc.memoryf ) == null)
dt.memoryf = dtdisc__c.dtmemory;
return disc;
}
if((disc) == null) /* only want to know current discipline */
return old;
searchf = dt.meth.searchf;
if((dt.data.type&010000)!=0) dtrestore(dt,null);
if(old.eventf!=null && ((Integer)old.eventf.exe(zz, dt,3, disc,old)) < 0)
return null;
dt.disc = disc;
if((dt.memoryf = disc.memoryf) == null)
dt.memoryf = dtdisc__c.dtmemory;
if((dt.data.type&(0000040|0000100|0000020))!=0)
UNSUPPORTED("e2tzh95k1lvjl6wbtpwizam8q"); // goto done;
else if((dt.data.type&0000002)!=0) {
UNSUPPORTED("3q5nyguq8mgdfwmm0yrzq2br8"); // if(type&0000002)
UNSUPPORTED("93q6zqzlgfz2qd0yl6koyw99c"); // goto done;
UNSUPPORTED("6d1rfacssm8768oz9fu5o66t8"); // else goto dt_renew;
}
else if((dt.data.type&(0000001|0000002))!=0) {
UNSUPPORTED("8xmm1djjds55s86jodixkp72u"); // if((type&0000002) && (type&0000001))
UNSUPPORTED("93q6zqzlgfz2qd0yl6koyw99c"); // goto done;
UNSUPPORTED("6d1rfacssm8768oz9fu5o66t8"); // else goto dt_renew;
}
else /*if(dt->data->type&(DT_OSET|DT_OBAG))*/ {
if((type&0000001)!=0)
UNSUPPORTED("93q6zqzlgfz2qd0yl6koyw99c"); // goto done;
// dt_renew:
r = dtflatten(dt);
UNSUPPORTED("1rry7yjzos90pgbf3li2qpa18"); // dt->data->type &= ~010000;
UNSUPPORTED("6vkn7padspfbtju9g5b65b34w"); // dt->data->here = ((Dtlink_t*)0);
UNSUPPORTED("2jfi30wa60xp7iqlk9yyf4k5j"); // dt->data->size = 0;
UNSUPPORTED("1i3oayy7gy36lar9kfhuq6rur"); // if(dt->data->type&(0000001|0000002))
UNSUPPORTED("ay51d19gimt3gpqjact2t0ypm"); // { register Dtlink_t **s, **ends;
UNSUPPORTED("5p6g054kk7snvpwuxudelseir"); // ends = (s = dt->data->hh._htab) + dt->data->ntab;
UNSUPPORTED("3zu1r6orkvmsvbjbzqqx9wedr"); // while(s < ends)
UNSUPPORTED("9wq8eycc78fg8sqi6bjce4q7f"); // *s++ = ((Dtlink_t*)0);
UNSUPPORTED("6eq5kf0bj692bokt0bixy1ixh"); // }
UNSUPPORTED("3rfhc462a0qx53yecw933hkk8"); // /* reinsert them */
UNSUPPORTED("ctmfjzioo5q7mzsmb6rf9mxoy"); // while(r)
UNSUPPORTED("9qxb0eqp3ujnnuum1bggqarjh"); // { t = r->right;
UNSUPPORTED("ddltpk94i08fyy6x03ozyc7s1"); // if(!(type&0000002)) /* new hash value */
UNSUPPORTED("8mj2vd7idro90tjnvl6b9trnc"); // { k<SUF>
UNSUPPORTED("1dvo2602az1wcigxx20czskv9"); // k = (void*)(disc->size < 0 ? *((char**)((char*)((void*)k)+disc->key)) : ((char*)((void*)k)+disc->key));
UNSUPPORTED("269t5qi8m2ujfjvmbqvyjvr1s"); // r->hl._hash = (disc->hashf ? (*disc->hashf)(dt,k,disc) : dtstrhash(0,k,disc->size) );
UNSUPPORTED("3to5h0rvqxdeqs38mhv47mm3o"); // }
UNSUPPORTED("2e2tx3ch32oxo5y01bflgbf2h"); // (void)(*searchf)(dt,(void*)r,0000040);
UNSUPPORTED("8tob14cb9u9q0mnud0wovaioi"); // r = t;
UNSUPPORTED("6eq5kf0bj692bokt0bixy1ixh"); // }
UNSUPPORTED("flupwh3kosf3fkhkxllllt1"); // }
UNSUPPORTED("cerydbb7i6l7c4pgeygvwoqk2"); // done:
UNSUPPORTED("bi0p581nen18ypj0ey48s6ete"); // return old;
}
throw new UnsupportedOperationException();
} finally {
LEAVING("axpvuswclmi9bx3qtlh4quyah","dtdisc");
}
}
}
| False | 2,536 | 39 | 2,810 | 42 | 2,840 | 40 | 2,810 | 42 | 3,256 | 49 | false | false | false | false | false | true |
4,695 | 56464_3 | /**
*
*/
package jazmin.driver.mq;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.LongAdder;
/**
* @author yama
*
*/
public abstract class TopicQueue {
//
protected String id;
protected String type;
protected LongAdder publishCount;
protected List<TopicSubscriber> topicSubscribers;
protected long maxTtl;
protected long redelieverInterval;
protected long accpetRejectExpiredTime=1000*60*10;
protected Map<Short,TopicChannel>topicChannels;
//
public TopicQueue(String id,String type){
this.id=id;
this.type=type;
topicSubscribers=new LinkedList<TopicSubscriber>();
publishCount=new LongAdder();
topicChannels=new HashMap<>();
maxTtl=1000*3600*24;//1 day
redelieverInterval=1000*5;//5 seconds redeliever
}
/**
*
*/
public List<TopicChannel>getChannels(){
return new LinkedList<TopicChannel>(topicChannels.values());
}
/**
*
* @return
*/
public long getRedelieverInterval() {
return redelieverInterval;
}
/**
*
* @param redelieverInterval
*/
public void setRedelieverInterval(long redelieverInterval) {
if(redelieverInterval<=0){
throw new IllegalArgumentException("redelieverInterval should >0");
}
this.redelieverInterval = redelieverInterval;
}
/**
*
* @return
*/
public long getMaxTtl() {
return maxTtl;
}
/**
*
* @param maxTtl
*/
public void setMaxTtl(long maxTtl) {
if(maxTtl<=0){
throw new IllegalArgumentException("maxTtl should >0");
}
this.maxTtl = maxTtl;
}
/**
*
* @return
*/
public String getId(){
return id;
}
/**
*
* @return
*/
public String getType() {
return type;
}
/**
*
*/
public void start(){
}
/**
*
*/
public void stop(){
}
//
public long getPublishedCount(){
return publishCount.longValue();
}
/**
*
* @param name
*/
public void subscribe(TopicSubscriber ts){
if(topicSubscribers.contains(ts)){
throw new IllegalArgumentException(ts.name+" already exists");
}
topicSubscribers.add(ts);
}
/**
*
* @param obj
*/
public void publish(Object obj){
if(obj==null){
throw new NullPointerException("publish message can not be null");
}
if(topicSubscribers.isEmpty()){
throw new IllegalArgumentException("no topic subscriber");
}
publishCount.increment();
}
//
public Message take(short subscriberId){
TopicChannel channel =topicChannels.get(subscriberId);
if(channel==null){
throw new IllegalArgumentException(
"can not find subscriber ["+subscriberId+"] on topic queue:"+id);
}
Message message= channel.take();
if(message!=null&&message!=MessageQueueDriver.takeNext){
message.topic=id;
channel.delieverCount.increment();
}
return message;
}
//
public void accept(short subscriberId,long messageId){
TopicChannel channel =topicChannels.get(subscriberId);
if(channel==null){
throw new IllegalArgumentException("can not find subscriber on topic queue:"+id);
}
channel.accept(messageId);
}
//
public void reject(short subscriberId,long messageId){
TopicChannel channel =topicChannels.get(subscriberId);
if(channel==null){
throw new IllegalArgumentException("can not find subscriber on topic queue:"+id);
}
channel.reject(messageId);
}
}
| whx0123/JazminServer | JazminServer/src/jazmin/driver/mq/TopicQueue.java | 1,159 | /**
*
* @param redelieverInterval
*/ | block_comment | nl | /**
*
*/
package jazmin.driver.mq;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.LongAdder;
/**
* @author yama
*
*/
public abstract class TopicQueue {
//
protected String id;
protected String type;
protected LongAdder publishCount;
protected List<TopicSubscriber> topicSubscribers;
protected long maxTtl;
protected long redelieverInterval;
protected long accpetRejectExpiredTime=1000*60*10;
protected Map<Short,TopicChannel>topicChannels;
//
public TopicQueue(String id,String type){
this.id=id;
this.type=type;
topicSubscribers=new LinkedList<TopicSubscriber>();
publishCount=new LongAdder();
topicChannels=new HashMap<>();
maxTtl=1000*3600*24;//1 day
redelieverInterval=1000*5;//5 seconds redeliever
}
/**
*
*/
public List<TopicChannel>getChannels(){
return new LinkedList<TopicChannel>(topicChannels.values());
}
/**
*
* @return
*/
public long getRedelieverInterval() {
return redelieverInterval;
}
/**
*
* @param redelieverInterval
<SUF>*/
public void setRedelieverInterval(long redelieverInterval) {
if(redelieverInterval<=0){
throw new IllegalArgumentException("redelieverInterval should >0");
}
this.redelieverInterval = redelieverInterval;
}
/**
*
* @return
*/
public long getMaxTtl() {
return maxTtl;
}
/**
*
* @param maxTtl
*/
public void setMaxTtl(long maxTtl) {
if(maxTtl<=0){
throw new IllegalArgumentException("maxTtl should >0");
}
this.maxTtl = maxTtl;
}
/**
*
* @return
*/
public String getId(){
return id;
}
/**
*
* @return
*/
public String getType() {
return type;
}
/**
*
*/
public void start(){
}
/**
*
*/
public void stop(){
}
//
public long getPublishedCount(){
return publishCount.longValue();
}
/**
*
* @param name
*/
public void subscribe(TopicSubscriber ts){
if(topicSubscribers.contains(ts)){
throw new IllegalArgumentException(ts.name+" already exists");
}
topicSubscribers.add(ts);
}
/**
*
* @param obj
*/
public void publish(Object obj){
if(obj==null){
throw new NullPointerException("publish message can not be null");
}
if(topicSubscribers.isEmpty()){
throw new IllegalArgumentException("no topic subscriber");
}
publishCount.increment();
}
//
public Message take(short subscriberId){
TopicChannel channel =topicChannels.get(subscriberId);
if(channel==null){
throw new IllegalArgumentException(
"can not find subscriber ["+subscriberId+"] on topic queue:"+id);
}
Message message= channel.take();
if(message!=null&&message!=MessageQueueDriver.takeNext){
message.topic=id;
channel.delieverCount.increment();
}
return message;
}
//
public void accept(short subscriberId,long messageId){
TopicChannel channel =topicChannels.get(subscriberId);
if(channel==null){
throw new IllegalArgumentException("can not find subscriber on topic queue:"+id);
}
channel.accept(messageId);
}
//
public void reject(short subscriberId,long messageId){
TopicChannel channel =topicChannels.get(subscriberId);
if(channel==null){
throw new IllegalArgumentException("can not find subscriber on topic queue:"+id);
}
channel.reject(messageId);
}
}
| False | 853 | 15 | 1,023 | 13 | 1,066 | 17 | 1,023 | 13 | 1,240 | 18 | false | false | false | false | false | true |
1,217 | 77009_0 | /*
* Naam: Nol Keereweer
* Test ruimte voor Opdracht_1
* Importeren van Opdracht_1 en methodes vanuit daar gebruiken
*/
import com.cert.Opdracht_1;
public class executeOpdracht {
private static String accesCode = "2002";
public static void main(String[] args) {
//de method doen wordt uit Opdracht_1 gecalled
Opdracht_1.poging();
//if else statement om te zien of je input goed was
if (args[0].equals(accesCode)) {
System.out.println(Opdracht_1.getGetal());
} else {
System.out.println("Poging gefaald");
return;
}
}
}
| NolKeereweer/itVitae | FirstFewWeeks/WeekOne/executeOpdracht.java | 207 | /*
* Naam: Nol Keereweer
* Test ruimte voor Opdracht_1
* Importeren van Opdracht_1 en methodes vanuit daar gebruiken
*/ | block_comment | nl | /*
* Naam: Nol Keereweer<SUF>*/
import com.cert.Opdracht_1;
public class executeOpdracht {
private static String accesCode = "2002";
public static void main(String[] args) {
//de method doen wordt uit Opdracht_1 gecalled
Opdracht_1.poging();
//if else statement om te zien of je input goed was
if (args[0].equals(accesCode)) {
System.out.println(Opdracht_1.getGetal());
} else {
System.out.println("Poging gefaald");
return;
}
}
}
| False | 177 | 44 | 197 | 49 | 188 | 37 | 197 | 49 | 216 | 46 | false | false | false | false | false | true |
4,758 | 189087_1 | // Copyright (c) 2013-2024 xipki. All rights reserved.
// License Apache License 2.0
package org.xipki.ca.server;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* Random serial number generator.
*
* @author Lijun Liao (xipki)
* @since 2.0.0
*/
class RandomSerialNumberGenerator {
private static RandomSerialNumberGenerator instance;
private final SecureRandom random;
private RandomSerialNumberGenerator() {
this.random = new SecureRandom();
}
/**
* Generate the next serial number.
* @param byteLen byte length of the serial number.
* @return the serial number.
*/
public BigInteger nextSerialNumber(int byteLen) {
final byte[] rndBytes = new byte[byteLen];
random.nextBytes(rndBytes);
// clear the highest bit.
rndBytes[0] &= 0x7F;
// set the second-highest bit
rndBytes[0] |= 0x40;
return new BigInteger(rndBytes);
} // method nextSerialNumber
public static synchronized RandomSerialNumberGenerator getInstance() {
if (instance == null) {
instance = new RandomSerialNumberGenerator();
}
return instance;
} // method RandomSerialNumberGenerator
}
| xipki/xipki | ca-server/src/main/java/org/xipki/ca/server/RandomSerialNumberGenerator.java | 344 | // License Apache License 2.0 | line_comment | nl | // Copyright (c) 2013-2024 xipki. All rights reserved.
// License Apache<SUF>
package org.xipki.ca.server;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* Random serial number generator.
*
* @author Lijun Liao (xipki)
* @since 2.0.0
*/
class RandomSerialNumberGenerator {
private static RandomSerialNumberGenerator instance;
private final SecureRandom random;
private RandomSerialNumberGenerator() {
this.random = new SecureRandom();
}
/**
* Generate the next serial number.
* @param byteLen byte length of the serial number.
* @return the serial number.
*/
public BigInteger nextSerialNumber(int byteLen) {
final byte[] rndBytes = new byte[byteLen];
random.nextBytes(rndBytes);
// clear the highest bit.
rndBytes[0] &= 0x7F;
// set the second-highest bit
rndBytes[0] |= 0x40;
return new BigInteger(rndBytes);
} // method nextSerialNumber
public static synchronized RandomSerialNumberGenerator getInstance() {
if (instance == null) {
instance = new RandomSerialNumberGenerator();
}
return instance;
} // method RandomSerialNumberGenerator
}
| False | 291 | 8 | 305 | 8 | 323 | 8 | 305 | 8 | 361 | 8 | false | false | false | false | false | true |
221 | 23183_2 | package app.qienuren.controller;
import app.qienuren.exceptions.OnderwerkException;
import app.qienuren.exceptions.OverwerkException;
import app.qienuren.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.List;
@Service
@Transactional
public class UrenFormulierService {
@Autowired
UrenFormulierRepository urenFormulierRepository;
@Autowired
WerkdagRepository werkdagRepository;
@Autowired
WerkdagService werkdagService;
@Autowired
GebruikerRepository gebruikerRepository;
@Autowired
MailService mailService;
public Iterable<UrenFormulier> getAllUrenFormulieren() {
return urenFormulierRepository.findAll();
}
public List<UrenFormulier> urenFormulieren() {
return (List<UrenFormulier>) urenFormulierRepository.findAll();
}
public Object addWorkDaytoUrenFormulier(UrenFormulier uf, long wdid) {
Werkdag wd = werkdagRepository.findById(wdid).get();
try {
uf.addWerkdayToArray(wd);
return urenFormulierRepository.save(uf);
} catch (Exception e) {
return e.getMessage();
}
}
public UrenFormulier addNewUrenFormulier(UrenFormulier uf) {
int maand = uf.getMaand().ordinal() + 1;
YearMonth yearMonth = YearMonth.of(Integer.parseInt(uf.getJaar()), maand);
int daysInMonth = yearMonth.lengthOfMonth();
for (int x = 1; x <= daysInMonth; x++) {
Werkdag werkdag = werkdagService.addNewWorkday(new Werkdag(x));
addWorkDaytoUrenFormulier(uf, werkdag.getId());
}
return urenFormulierRepository.save(uf);
}
public double getTotaalGewerkteUren(long id) {
return urenFormulierRepository.findById(id).get().getTotaalGewerkteUren();
}
public double getZiekteUrenbyId(long id){
return urenFormulierRepository.findById(id).get().getZiekteUren();
}
public Iterable<UrenFormulier> getUrenFormulierPerMaand(int maandid) {
List<UrenFormulier> localUren = new ArrayList<>();
for (UrenFormulier uren : urenFormulierRepository.findAll()) {
if (uren.getMaand().ordinal() == maandid) {
localUren.add(uren);
}
}
return localUren;
}
public UrenFormulier getUrenFormulierById(long uid) {
return urenFormulierRepository.findById(uid).get();
}
public double getGewerkteUrenByID(long id) {
return 0.0;
}
public Object setStatusUrenFormulier(long urenformulierId, String welkeGoedkeurder){
//deze methode zet de statusGoedkeuring van OPEN naar INGEDIEND_TRAINEE nadat deze
// door de trainee is ingediend ter goedkeuring
if (welkeGoedkeurder.equals("GEBRUIKER")) {
checkMaximaalZiekuren(getZiekteUrenbyId(urenformulierId));
try {
enoughWorkedthisMonth(getTotaalGewerkteUren(urenformulierId));
} catch(OnderwerkException onderwerkException) {
urenFormulierRepository.save(urenFormulierRepository.findById(urenformulierId).get());
System.out.println("je hebt te weinig uren ingevuld deze maand");
return "onderwerk";
} catch (OverwerkException overwerkexception){
urenFormulierRepository.save(urenFormulierRepository.findById(urenformulierId).get());
System.out.println("Je hebt teveel uren ingevuld deze maand!");
return "overwerk";
} catch (Exception e) {
urenFormulierRepository.save(urenFormulierRepository.findById(urenformulierId).get());
return "random exception";
}
getUrenFormulierById(urenformulierId).setStatusGoedkeuring(StatusGoedkeuring.INGEDIEND_GEBRUIKER);
urenFormulierRepository.save(urenFormulierRepository.findById(urenformulierId).get());
return "gelukt";
}
//deze methode zet de statusGoedkeuring van INGEDIEND_TRAINEE of INGEDIEND_MEDEWERKER naar
// GOEDGEKEURD_ADMIN nadat deze door de trainee/medewerker is ingediend ter goedkeuring
// (en door bedrijf is goedgekeurd indien Trainee)
if(welkeGoedkeurder.equals("ADMIN")) {
getUrenFormulierById(urenformulierId).setStatusGoedkeuring(StatusGoedkeuring.GOEDGEKEURD_ADMIN);
}
//deze methode zet de statusGoedkeuring van INGEDIEND_TRAINEE naar GOEDGEKEURD_BEDRIJF nadat deze
//door de trainee/medewerker is ingediend ter goedkeuring. Medewerker slaat deze methode over
//en gaat gelijk naar goedkeuring admin!
if(welkeGoedkeurder.equals("BEDRIJF")) {
getUrenFormulierById(urenformulierId).setStatusGoedkeuring(StatusGoedkeuring.GOEDGEKEURD_BEDRIJF);
}
return getUrenFormulierById(urenformulierId);
}
public UrenFormulier changeDetails(UrenFormulier urenFormulier, UrenFormulier urenFormulierUpdate) {
if (urenFormulierUpdate.getOpmerking() != null) {
urenFormulier.setOpmerking(urenFormulierUpdate.getOpmerking());
}
return urenFormulierRepository.save(urenFormulier);
}
public void ziekMelden(String id, UrenFormulier urenFormulier, String datumDag) {
Gebruiker gebruiker = gebruikerRepository.findByUserId(id);
for (UrenFormulier uf : gebruiker.getUrenFormulier()) {
if (uf.getJaar().equals(urenFormulier.getJaar()) && uf.getMaand() == urenFormulier.getMaand()) {
for (Werkdag werkdag : uf.getWerkdag()) {
if (werkdag.getDatumDag().equals(datumDag)) {
werkdagRepository.save(werkdag.ikBenZiek());
}
}
}
}
}
public void enoughWorkedthisMonth(double totalHoursWorked) throws OnderwerkException {
if (totalHoursWorked <= 139){
throw new OnderwerkException("Je hebt te weinig uren ingevuld deze maand");
} else if (totalHoursWorked >= 220){
throw new OverwerkException("Je hebt teveel gewerkt, take a break");
} else {
return;
}
}
// try catch blok maken als deze exception getrowt wordt. if false krijgt die een bericht terug. in classe urenformulierservice regel 80..
public void checkMaximaalZiekuren(double getZiekurenFormulier){
if (getZiekurenFormulier >= 64){
Mail teveelZiekMailCora = new Mail();
teveelZiekMailCora.setEmailTo("[email protected]");
teveelZiekMailCora.setSubject("Een medewerker heeft meer dan 9 ziektedagen. Check het even!");
teveelZiekMailCora.setText("Hoi Cora, Een medewerker is volgens zijn of haar ingediende urenformulier meer dag 9 dagen ziek geweest deze maand." +
" Wil je het formulier even checken? Log dan in bij het urenregistratiesysteem van Qien."
);
mailService.sendEmail(teveelZiekMailCora);
System.out.println("email verzonden omdat maximaal ziekteuren zijn overschreden");
} else {
System.out.println("ziekteuren zijn niet overschreden. toppiejoppie");
}
}
// rij 85 voor dat we enough worked this month aanroepen een functie die de ziekteuren oproept.
}
| Bob-Coding/qienurenappgroep1 | qienuren-backend/src/main/java/app/qienuren/controller/UrenFormulierService.java | 2,343 | //deze methode zet de statusGoedkeuring van INGEDIEND_TRAINEE of INGEDIEND_MEDEWERKER naar | line_comment | nl | package app.qienuren.controller;
import app.qienuren.exceptions.OnderwerkException;
import app.qienuren.exceptions.OverwerkException;
import app.qienuren.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.List;
@Service
@Transactional
public class UrenFormulierService {
@Autowired
UrenFormulierRepository urenFormulierRepository;
@Autowired
WerkdagRepository werkdagRepository;
@Autowired
WerkdagService werkdagService;
@Autowired
GebruikerRepository gebruikerRepository;
@Autowired
MailService mailService;
public Iterable<UrenFormulier> getAllUrenFormulieren() {
return urenFormulierRepository.findAll();
}
public List<UrenFormulier> urenFormulieren() {
return (List<UrenFormulier>) urenFormulierRepository.findAll();
}
public Object addWorkDaytoUrenFormulier(UrenFormulier uf, long wdid) {
Werkdag wd = werkdagRepository.findById(wdid).get();
try {
uf.addWerkdayToArray(wd);
return urenFormulierRepository.save(uf);
} catch (Exception e) {
return e.getMessage();
}
}
public UrenFormulier addNewUrenFormulier(UrenFormulier uf) {
int maand = uf.getMaand().ordinal() + 1;
YearMonth yearMonth = YearMonth.of(Integer.parseInt(uf.getJaar()), maand);
int daysInMonth = yearMonth.lengthOfMonth();
for (int x = 1; x <= daysInMonth; x++) {
Werkdag werkdag = werkdagService.addNewWorkday(new Werkdag(x));
addWorkDaytoUrenFormulier(uf, werkdag.getId());
}
return urenFormulierRepository.save(uf);
}
public double getTotaalGewerkteUren(long id) {
return urenFormulierRepository.findById(id).get().getTotaalGewerkteUren();
}
public double getZiekteUrenbyId(long id){
return urenFormulierRepository.findById(id).get().getZiekteUren();
}
public Iterable<UrenFormulier> getUrenFormulierPerMaand(int maandid) {
List<UrenFormulier> localUren = new ArrayList<>();
for (UrenFormulier uren : urenFormulierRepository.findAll()) {
if (uren.getMaand().ordinal() == maandid) {
localUren.add(uren);
}
}
return localUren;
}
public UrenFormulier getUrenFormulierById(long uid) {
return urenFormulierRepository.findById(uid).get();
}
public double getGewerkteUrenByID(long id) {
return 0.0;
}
public Object setStatusUrenFormulier(long urenformulierId, String welkeGoedkeurder){
//deze methode zet de statusGoedkeuring van OPEN naar INGEDIEND_TRAINEE nadat deze
// door de trainee is ingediend ter goedkeuring
if (welkeGoedkeurder.equals("GEBRUIKER")) {
checkMaximaalZiekuren(getZiekteUrenbyId(urenformulierId));
try {
enoughWorkedthisMonth(getTotaalGewerkteUren(urenformulierId));
} catch(OnderwerkException onderwerkException) {
urenFormulierRepository.save(urenFormulierRepository.findById(urenformulierId).get());
System.out.println("je hebt te weinig uren ingevuld deze maand");
return "onderwerk";
} catch (OverwerkException overwerkexception){
urenFormulierRepository.save(urenFormulierRepository.findById(urenformulierId).get());
System.out.println("Je hebt teveel uren ingevuld deze maand!");
return "overwerk";
} catch (Exception e) {
urenFormulierRepository.save(urenFormulierRepository.findById(urenformulierId).get());
return "random exception";
}
getUrenFormulierById(urenformulierId).setStatusGoedkeuring(StatusGoedkeuring.INGEDIEND_GEBRUIKER);
urenFormulierRepository.save(urenFormulierRepository.findById(urenformulierId).get());
return "gelukt";
}
//deze methode<SUF>
// GOEDGEKEURD_ADMIN nadat deze door de trainee/medewerker is ingediend ter goedkeuring
// (en door bedrijf is goedgekeurd indien Trainee)
if(welkeGoedkeurder.equals("ADMIN")) {
getUrenFormulierById(urenformulierId).setStatusGoedkeuring(StatusGoedkeuring.GOEDGEKEURD_ADMIN);
}
//deze methode zet de statusGoedkeuring van INGEDIEND_TRAINEE naar GOEDGEKEURD_BEDRIJF nadat deze
//door de trainee/medewerker is ingediend ter goedkeuring. Medewerker slaat deze methode over
//en gaat gelijk naar goedkeuring admin!
if(welkeGoedkeurder.equals("BEDRIJF")) {
getUrenFormulierById(urenformulierId).setStatusGoedkeuring(StatusGoedkeuring.GOEDGEKEURD_BEDRIJF);
}
return getUrenFormulierById(urenformulierId);
}
public UrenFormulier changeDetails(UrenFormulier urenFormulier, UrenFormulier urenFormulierUpdate) {
if (urenFormulierUpdate.getOpmerking() != null) {
urenFormulier.setOpmerking(urenFormulierUpdate.getOpmerking());
}
return urenFormulierRepository.save(urenFormulier);
}
public void ziekMelden(String id, UrenFormulier urenFormulier, String datumDag) {
Gebruiker gebruiker = gebruikerRepository.findByUserId(id);
for (UrenFormulier uf : gebruiker.getUrenFormulier()) {
if (uf.getJaar().equals(urenFormulier.getJaar()) && uf.getMaand() == urenFormulier.getMaand()) {
for (Werkdag werkdag : uf.getWerkdag()) {
if (werkdag.getDatumDag().equals(datumDag)) {
werkdagRepository.save(werkdag.ikBenZiek());
}
}
}
}
}
public void enoughWorkedthisMonth(double totalHoursWorked) throws OnderwerkException {
if (totalHoursWorked <= 139){
throw new OnderwerkException("Je hebt te weinig uren ingevuld deze maand");
} else if (totalHoursWorked >= 220){
throw new OverwerkException("Je hebt teveel gewerkt, take a break");
} else {
return;
}
}
// try catch blok maken als deze exception getrowt wordt. if false krijgt die een bericht terug. in classe urenformulierservice regel 80..
public void checkMaximaalZiekuren(double getZiekurenFormulier){
if (getZiekurenFormulier >= 64){
Mail teveelZiekMailCora = new Mail();
teveelZiekMailCora.setEmailTo("[email protected]");
teveelZiekMailCora.setSubject("Een medewerker heeft meer dan 9 ziektedagen. Check het even!");
teveelZiekMailCora.setText("Hoi Cora, Een medewerker is volgens zijn of haar ingediende urenformulier meer dag 9 dagen ziek geweest deze maand." +
" Wil je het formulier even checken? Log dan in bij het urenregistratiesysteem van Qien."
);
mailService.sendEmail(teveelZiekMailCora);
System.out.println("email verzonden omdat maximaal ziekteuren zijn overschreden");
} else {
System.out.println("ziekteuren zijn niet overschreden. toppiejoppie");
}
}
// rij 85 voor dat we enough worked this month aanroepen een functie die de ziekteuren oproept.
}
| True | 1,979 | 31 | 2,174 | 33 | 2,005 | 28 | 2,174 | 33 | 2,359 | 37 | false | false | false | false | false | true |
1,587 | 137527_1 | import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public ArrayList<Klant> klanten;
public ArrayList<Project> projecten;
public ArrayList<Medewerker> medewerkers;
public Main() {
klanten = new ArrayList<Klant>(Arrays.asList(
new Klant(1, "Sidd Ghogli", "[email protected]", "+31 628819729"),
new Klant(2, "Klant twee", "[email protected]", "+31 612345678"),
new Klant(3, "Klant drie", "[email protected]", "+31 698765432")
));
medewerkers = new ArrayList<Medewerker>(Arrays.asList(
new Medewerker(4, "Medewerker een", "manager", "+31 623456789", 50),
new Medewerker(5, "Medewerker twee", "developer", "+31 634567890", 35),
new Medewerker(6, "Medewerker drie", "designer", "+31 645678901", 25)
));
projecten = new ArrayList<Project>(Arrays.asList(
new Project(7, "Project 1", "Klein Project", 2000, LocalDate.parse("2023-04-15", DateTimeFormatter.ISO_LOCAL_DATE), LocalDate.parse("2023-05-20", DateTimeFormatter.ISO_LOCAL_DATE), 1, 4),
new Project(8, "Project 2", "Groot Project", 50000, LocalDate.parse("2023-01-23", DateTimeFormatter.ISO_LOCAL_DATE), LocalDate.parse("2023-08-12", DateTimeFormatter.ISO_LOCAL_DATE), 2, 5)
));
}
public static void main(String[] args) {
Main crmApplicatie = new Main();
for(Project p : crmApplicatie.projecten){
new ProjectObserver(p);
}
crmApplicatie.projecten.get(1).addUrenDeclaratie(new UrenDeclaratie(2, crmApplicatie.medewerkers.get(0)));
crmApplicatie.projecten.get(0).addUrenDeclaratie(new UrenDeclaratie(2, crmApplicatie.medewerkers.get(0)));
crmApplicatie.start();
}
public void start() {
boolean programmaActief = true;
Scanner scanner = new Scanner(System.in);
while (programmaActief) {
toonMenu();
int keuze = scanner.nextInt();
scanner.nextLine(); // Om de resterende invoerbuffer te verwijderen
switch (keuze) {
case 1:
voegKlantToe(scanner);
break;
case 2:
voegProjectToe(scanner);
break;
case 3:
voegMedewerkerToe(scanner);
break;
case 4:
toonKlanten();
break;
case 5:
toonProjecten();
break;
case 6:
toonMedewerkers();
break;
case 7:
urenDeclareren();
break;
case 8:
programmaActief = false;
break;
default:
System.out.println("Ongeldige keuze. Probeer opnieuw.");
}
}
scanner.close();
}
private void toonMenu() {
System.out.println("Selecteer een optie:");
System.out.println("1. Klant toevoegen");
System.out.println("2. Project toevoegen");
System.out.println("3. Medewerker toevoegen");
System.out.println("4. Klanten weergeven");
System.out.println("5. Projecten weergeven");
System.out.println("6. Medewerkers weergeven");
System.out.println("7. Uren Declareren");
System.out.println("8. Afsluiten");
}
private void voegKlantToe(Scanner scanner) {
System.out.println("Voer de klant-ID in:");
int klantID = scanner.nextInt();
scanner.nextLine();
System.out.println("Voer de naam in:");
String naam = scanner.nextLine();
System.out.println("Voer het e-mailadres in:");
String email = scanner.nextLine();
System.out.println("Voer het telefoonnummer in:");
String telefoonnummer = scanner.nextLine();
Klant klant = new Klant(klantID, naam, email, telefoonnummer);
klanten.add(klant);
System.out.println("Klant toegevoegd.");
}
private void voegProjectToe(Scanner scanner) {
System.out.println("Voer het project-ID in:");
int projectID = scanner.nextInt();
scanner.nextLine();
//project manager/ klantid / datum check
System.out.println("Voer de projectnaam in:");
String projectnaam = scanner.nextLine();
System.out.println("Voer de projectbeschrijving in:");
String beschrijving = scanner.nextLine();
System.out.println("Voer het budget in:");
int budget = scanner.nextInt();
scanner.nextLine();
System.out.println("Voer de klant-ID in:");
int klantID = scanner.nextInt();
scanner.nextLine();
System.out.println("Voer de medewerker-ID in:");
int medewerkerID = scanner.nextInt();
scanner.nextLine();
System.out.println("Voer de startdatum in (YYYY-MM-DD):");
String startdatumStr = scanner.nextLine();
LocalDate startdatum = LocalDate.parse(startdatumStr, DateTimeFormatter.ISO_LOCAL_DATE);
System.out.println("Voer de einddatum in (YYYY-MM-DD):");
String einddatumStr = scanner.nextLine();
LocalDate einddatum = LocalDate.parse(einddatumStr, DateTimeFormatter.ISO_LOCAL_DATE);
Project project = new Project(projectID, projectnaam, beschrijving, budget, startdatum, einddatum, klantID,medewerkerID);
new ProjectObserver(project);
projecten.add(project);
System.out.println("Project toegevoegd.");
}
private void voegMedewerkerToe(Scanner scanner) {
System.out.println("Voer de medewerker-ID in:");
int medewerkerID = scanner.nextInt();
scanner.nextLine();
System.out.println("Voer de voornaam in:");
String voornaam = scanner.nextLine();
System.out.println("Voer de achternaam in:");
String achternaam = scanner.nextLine();
System.out.println("Voer de functie in:");
String functie = scanner.nextLine();
System.out.println("Voer het e-mailadres in:");
String email = scanner.nextLine();
System.out.println("Voer het uurtarief in:");
Double uurTarief = scanner.nextDouble();
Medewerker medewerker = new Medewerker(medewerkerID, (voornaam + " " + achternaam), functie, email, uurTarief);
medewerkers.add(medewerker);
System.out.println("Medewerker toegevoegd.");
}
private void toonKlanten() {
System.out.println("Klantenlijst:");
for (Klant klant : klanten) {
System.out.println("ID: " + klant.getKlantID() + ", Naam: " + klant.getNaam() + ", E-mail: " + klant.getEmail() + ", Telefoonnummer: " + klant.getTelefoonnummer());
}
}
private void toonProjecten() {
System.out.println("Projectenlijst:");
for (Project project : projecten) {
System.out.println("ID: " + project.getProjectID() + ", Klant: " + project.getKlantID() + ", " +project.getProjectmanagerID() + ", Naam: " + project.getProjectnaam() + ", Beschrijving: " + project.getBeschrijving() + ", Startdatum: " + project.getStartdatum() + ", Einddatum: " + project.getEinddatum());
}
}
private void toonMedewerkers() {
System.out.println("Medewerkerslijst:");
for (Medewerker medewerker : medewerkers) {
System.out.println("ID: " + medewerker.getMedewerkerID() + ", " + medewerker.getFunctie() + ", Naam: " + medewerker.getNaam() + ", E-mail: " + medewerker.getEmail());
}
}
private void urenDeclareren(){
//TODO code hierzo toevoegen
//input is de medewerkerID, ProjectID en het aantal uur. Daarna toevoegen aan UrenDeclaratie in Project Class
}
} | Siddhart/OPT3-v2 | src/main/java/Main.java | 2,531 | //project manager/ klantid / datum check | line_comment | nl | import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public ArrayList<Klant> klanten;
public ArrayList<Project> projecten;
public ArrayList<Medewerker> medewerkers;
public Main() {
klanten = new ArrayList<Klant>(Arrays.asList(
new Klant(1, "Sidd Ghogli", "[email protected]", "+31 628819729"),
new Klant(2, "Klant twee", "[email protected]", "+31 612345678"),
new Klant(3, "Klant drie", "[email protected]", "+31 698765432")
));
medewerkers = new ArrayList<Medewerker>(Arrays.asList(
new Medewerker(4, "Medewerker een", "manager", "+31 623456789", 50),
new Medewerker(5, "Medewerker twee", "developer", "+31 634567890", 35),
new Medewerker(6, "Medewerker drie", "designer", "+31 645678901", 25)
));
projecten = new ArrayList<Project>(Arrays.asList(
new Project(7, "Project 1", "Klein Project", 2000, LocalDate.parse("2023-04-15", DateTimeFormatter.ISO_LOCAL_DATE), LocalDate.parse("2023-05-20", DateTimeFormatter.ISO_LOCAL_DATE), 1, 4),
new Project(8, "Project 2", "Groot Project", 50000, LocalDate.parse("2023-01-23", DateTimeFormatter.ISO_LOCAL_DATE), LocalDate.parse("2023-08-12", DateTimeFormatter.ISO_LOCAL_DATE), 2, 5)
));
}
public static void main(String[] args) {
Main crmApplicatie = new Main();
for(Project p : crmApplicatie.projecten){
new ProjectObserver(p);
}
crmApplicatie.projecten.get(1).addUrenDeclaratie(new UrenDeclaratie(2, crmApplicatie.medewerkers.get(0)));
crmApplicatie.projecten.get(0).addUrenDeclaratie(new UrenDeclaratie(2, crmApplicatie.medewerkers.get(0)));
crmApplicatie.start();
}
public void start() {
boolean programmaActief = true;
Scanner scanner = new Scanner(System.in);
while (programmaActief) {
toonMenu();
int keuze = scanner.nextInt();
scanner.nextLine(); // Om de resterende invoerbuffer te verwijderen
switch (keuze) {
case 1:
voegKlantToe(scanner);
break;
case 2:
voegProjectToe(scanner);
break;
case 3:
voegMedewerkerToe(scanner);
break;
case 4:
toonKlanten();
break;
case 5:
toonProjecten();
break;
case 6:
toonMedewerkers();
break;
case 7:
urenDeclareren();
break;
case 8:
programmaActief = false;
break;
default:
System.out.println("Ongeldige keuze. Probeer opnieuw.");
}
}
scanner.close();
}
private void toonMenu() {
System.out.println("Selecteer een optie:");
System.out.println("1. Klant toevoegen");
System.out.println("2. Project toevoegen");
System.out.println("3. Medewerker toevoegen");
System.out.println("4. Klanten weergeven");
System.out.println("5. Projecten weergeven");
System.out.println("6. Medewerkers weergeven");
System.out.println("7. Uren Declareren");
System.out.println("8. Afsluiten");
}
private void voegKlantToe(Scanner scanner) {
System.out.println("Voer de klant-ID in:");
int klantID = scanner.nextInt();
scanner.nextLine();
System.out.println("Voer de naam in:");
String naam = scanner.nextLine();
System.out.println("Voer het e-mailadres in:");
String email = scanner.nextLine();
System.out.println("Voer het telefoonnummer in:");
String telefoonnummer = scanner.nextLine();
Klant klant = new Klant(klantID, naam, email, telefoonnummer);
klanten.add(klant);
System.out.println("Klant toegevoegd.");
}
private void voegProjectToe(Scanner scanner) {
System.out.println("Voer het project-ID in:");
int projectID = scanner.nextInt();
scanner.nextLine();
//project manager/<SUF>
System.out.println("Voer de projectnaam in:");
String projectnaam = scanner.nextLine();
System.out.println("Voer de projectbeschrijving in:");
String beschrijving = scanner.nextLine();
System.out.println("Voer het budget in:");
int budget = scanner.nextInt();
scanner.nextLine();
System.out.println("Voer de klant-ID in:");
int klantID = scanner.nextInt();
scanner.nextLine();
System.out.println("Voer de medewerker-ID in:");
int medewerkerID = scanner.nextInt();
scanner.nextLine();
System.out.println("Voer de startdatum in (YYYY-MM-DD):");
String startdatumStr = scanner.nextLine();
LocalDate startdatum = LocalDate.parse(startdatumStr, DateTimeFormatter.ISO_LOCAL_DATE);
System.out.println("Voer de einddatum in (YYYY-MM-DD):");
String einddatumStr = scanner.nextLine();
LocalDate einddatum = LocalDate.parse(einddatumStr, DateTimeFormatter.ISO_LOCAL_DATE);
Project project = new Project(projectID, projectnaam, beschrijving, budget, startdatum, einddatum, klantID,medewerkerID);
new ProjectObserver(project);
projecten.add(project);
System.out.println("Project toegevoegd.");
}
private void voegMedewerkerToe(Scanner scanner) {
System.out.println("Voer de medewerker-ID in:");
int medewerkerID = scanner.nextInt();
scanner.nextLine();
System.out.println("Voer de voornaam in:");
String voornaam = scanner.nextLine();
System.out.println("Voer de achternaam in:");
String achternaam = scanner.nextLine();
System.out.println("Voer de functie in:");
String functie = scanner.nextLine();
System.out.println("Voer het e-mailadres in:");
String email = scanner.nextLine();
System.out.println("Voer het uurtarief in:");
Double uurTarief = scanner.nextDouble();
Medewerker medewerker = new Medewerker(medewerkerID, (voornaam + " " + achternaam), functie, email, uurTarief);
medewerkers.add(medewerker);
System.out.println("Medewerker toegevoegd.");
}
private void toonKlanten() {
System.out.println("Klantenlijst:");
for (Klant klant : klanten) {
System.out.println("ID: " + klant.getKlantID() + ", Naam: " + klant.getNaam() + ", E-mail: " + klant.getEmail() + ", Telefoonnummer: " + klant.getTelefoonnummer());
}
}
private void toonProjecten() {
System.out.println("Projectenlijst:");
for (Project project : projecten) {
System.out.println("ID: " + project.getProjectID() + ", Klant: " + project.getKlantID() + ", " +project.getProjectmanagerID() + ", Naam: " + project.getProjectnaam() + ", Beschrijving: " + project.getBeschrijving() + ", Startdatum: " + project.getStartdatum() + ", Einddatum: " + project.getEinddatum());
}
}
private void toonMedewerkers() {
System.out.println("Medewerkerslijst:");
for (Medewerker medewerker : medewerkers) {
System.out.println("ID: " + medewerker.getMedewerkerID() + ", " + medewerker.getFunctie() + ", Naam: " + medewerker.getNaam() + ", E-mail: " + medewerker.getEmail());
}
}
private void urenDeclareren(){
//TODO code hierzo toevoegen
//input is de medewerkerID, ProjectID en het aantal uur. Daarna toevoegen aan UrenDeclaratie in Project Class
}
} | True | 2,038 | 10 | 2,261 | 10 | 2,211 | 10 | 2,261 | 10 | 2,626 | 11 | false | false | false | false | false | true |
3,040 | 136813_2 | /******************************************************************
*
* CyberXML for Java
*
* Copyright (C) Satoshi Konno 2002
*
* File: Element.java
*
* Revision;
*
* 11/27/02
* - first revision.
* 11/01/03
* - Terje Bakken
* - fixed missing escaping of reserved XML characters
* 11/19/04
* - Theo Beisch <[email protected]>
* - Added "&" and "\"" "\\" to toXMLString().
* 11/19/04
* - Theo Beisch <[email protected]>
* - Changed XML::output() to use short notation when the tag value is null.
* 12/02/04
* - Brian Owens <[email protected]>
* - Fixed toXMLString() to convert from "'" to "'" instead of "\".
* 11/07/05
* - Changed toString() to return as utf-8 string.
* 02/08/08
* - Added addValue().
*
******************************************************************/
package org.cybergarage.xml;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
public class Node
{
/**
* Create a Node with empty UserData and no Parent Node
*
*/
public Node()
{
setUserData(null);
setParentNode(null);
}
public Node(String name)
{
this();
setName(name);
}
public Node(String ns, String name)
{
this();
setName(ns, name);
}
public Node(Node otherNode)
{
this();
set(otherNode);
}
////////////////////////////////////////////////
// parent node
////////////////////////////////////////////////
private Node parentNode = null;
public void setParentNode(Node node)
{
parentNode = node;
}
public Node getParentNode()
{
return parentNode;
}
////////////////////////////////////////////////
// root node
////////////////////////////////////////////////
public Node getRootNode()
{
Node rootNode = null;
Node parentNode = getParentNode();
while (parentNode != null) {
rootNode = parentNode;
parentNode = rootNode.getParentNode();
}
return rootNode;
}
////////////////////////////////////////////////
// name
////////////////////////////////////////////////
private String name = new String();
public void setName(String name)
{
this.name = name;
}
public void setName(String ns, String name)
{
this.name = ns + ":" + name;
}
public String getName()
{
return name;
}
public boolean isName(String value)
{
return name.equals(value);
}
////////////////////////////////////////////////
// value
////////////////////////////////////////////////
private String value = new String();
public void setValue(String value)
{
this.value = value;
}
public void setValue(int value)
{
setValue(Integer.toString(value));
}
public void addValue(String value)
{
if (this.value == null) {
this.value = value;
return;
}
if (value != null)
this.value += value;
}
public String getValue()
{
return value;
}
////////////////////////////////////////////////
// Attribute (Basic)
////////////////////////////////////////////////
private AttributeList attrList = new AttributeList();
public int getNAttributes() {
return attrList.size();
}
public Attribute getAttribute(int index) {
return attrList.getAttribute(index);
}
public Attribute getAttribute(String name)
{
return attrList.getAttribute(name);
}
public void addAttribute(Attribute attr) {
attrList.add(attr);
}
public void insertAttributeAt(Attribute attr, int index) {
attrList.insertElementAt(attr, index);
}
public void addAttribute(String name, String value) {
Attribute attr = new Attribute(name, value);
addAttribute(attr);
}
public boolean removeAttribute(Attribute attr) {
return attrList.remove(attr);
}
public boolean removeAttribute(String name) {
return removeAttribute(getAttribute(name));
}
public void removeAllAttributes()
{
attrList.clear();
}
public boolean hasAttributes()
{
if (0 < getNAttributes())
return true;
return false;
}
////////////////////////////////////////////////
// Attribute (Extention)
////////////////////////////////////////////////
public void setAttribute(String name, String value) {
Attribute attr = getAttribute(name);
if (attr != null) {
attr.setValue(value);
return;
}
attr = new Attribute(name, value);
addAttribute(attr);
}
public void setAttribute(String name, int value) {
setAttribute(name, Integer.toString(value));
}
public String getAttributeValue(String name) {
Attribute attr = getAttribute(name);
if (attr != null)
return attr.getValue();
return "";
}
public int getAttributeIntegerValue(String name) {
String val = getAttributeValue(name);
try {
return Integer.parseInt(val);
}
catch (Exception e) {}
return 0;
}
////////////////////////////////////////////////
// Attribute (xmlns)
////////////////////////////////////////////////
public void setNameSpace(String ns, String value)
{
setAttribute("xmlns:" + ns, value);
}
////////////////////////////////////////////////
// set
////////////////////////////////////////////////
public boolean set(Node otherNode) {
if (otherNode == null)
return false;
setName(otherNode.getName());
setValue(otherNode.getValue());
removeAllAttributes();
int nOtherAttributes = otherNode.getNAttributes();
for (int n=0; n<nOtherAttributes; n++) {
Attribute otherAttr = otherNode.getAttribute(n);
Attribute thisAttr = new Attribute(otherAttr);
addAttribute(thisAttr);
}
removeAllNodes();
int nOtherChildNodes = otherNode.getNNodes();
for (int n=0; n<nOtherChildNodes; n++) {
Node otherChildNode = otherNode.getNode(n);
Node thisChildNode = new Node();
thisChildNode.set(otherChildNode);
addNode(thisChildNode);
}
return true;
}
////////////////////////////////////////////////
// equals
////////////////////////////////////////////////
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null)
return false;
if (!(o instanceof Node))
return false;
Node otherNode = (Node) o;
String thisNodeString = toString();
String otherNodeString = otherNode.toString();
return thisNodeString.equals(otherNodeString);
}
////////////////////////////////////////////////
// Child node
////////////////////////////////////////////////
private NodeList nodeList = new NodeList();
public int getNNodes() {
return nodeList.size();
}
public Node getNode(int index) {
return nodeList.getNode(index);
}
public Node getNode(String name)
{
return nodeList.getNode(name);
}
public Node getNodeEndsWith(String name)
{
return nodeList.getEndsWith(name);
}
public void addNode(Node node) {
node.setParentNode(this);
nodeList.add(node);
}
public void insertNode(Node node, int index) {
node.setParentNode(this);
nodeList.insertElementAt(node, index);
}
public int getIndex(String name){
int index = -1;
for (Iterator<Node> i = nodeList.iterator(); i.hasNext();) {
index++;
Node n = i.next();
if(n.getName().equals(name))
return index;
}
return index;
}
public boolean removeNode(Node node) {
node.setParentNode(null);
return nodeList.remove(node);
}
public boolean removeNode(String name) {
return nodeList.remove(getNode(name));
}
public void removeAllNodes()
{
nodeList.clear();
}
public boolean hasNodes()
{
if (0 < getNNodes())
return true;
return false;
}
////////////////////////////////////////////////
// Element (Child Node)
////////////////////////////////////////////////
public boolean hasNode(String name) {
Node node = getNode(name);
if (node != null) {
return true;
}
return false;
}
public void setNode(String name) {
if (hasNode(name)) {
return;
}
Node node = new Node(name);
addNode(node);
}
public void setNode(String name, String value) {
Node node = getNode(name);
if (node == null) {
node = new Node(name);
addNode(node);
}
node.setValue(value);
}
public String getNodeValue(String name) {
Node node = getNode(name);
if (node != null)
return node.getValue();
return "";
}
////////////////////////////////////////////////
// userData
////////////////////////////////////////////////
private Object userData = null;
public void setUserData(Object data)
{
userData = data;
}
public Object getUserData()
{
return userData;
}
////////////////////////////////////////////////
// toString
////////////////////////////////////////////////
/**
* Inovoke {@link #getIndentLevelString(int, String)} with <code>" "</code> as String
*
* @see #getIndentLevelString(int, String)
*/
public String getIndentLevelString(int nIndentLevel)
{
return getIndentLevelString(nIndentLevel," ");
}
/**
*
* @param nIndentLevel the level of indentation to produce
* @param space the String to use for the intendation
* @since 1.8.0
* @return an indentation String
*/
public String getIndentLevelString(int nIndentLevel,String space)
{
StringBuffer indentString = new StringBuffer(nIndentLevel*space.length());
for (int n=0; n<nIndentLevel; n++){
indentString.append(space);
}
return indentString.toString();
}
public void outputAttributes(PrintWriter ps)
{
int nAttributes = getNAttributes();
for (int n=0; n<nAttributes; n++) {
Attribute attr = getAttribute(n);
ps.print(" " + attr.getName() + "=\"" + XML.escapeXMLChars(attr.getValue()) + "\"");
}
}
public void output(PrintWriter ps, int indentLevel, boolean hasChildNode)
{
String indentString = getIndentLevelString(indentLevel);
String name = getName();
String value = getValue();
if (hasNodes() == false || hasChildNode == false) {
ps.print(indentString + "<" + name);
outputAttributes(ps);
// Thnaks for Tho Beisch (11/09/04)
if (value == null || value.length() == 0) {
// Not using the short notation <node /> because it cause compatibility trouble
ps.println("></" + name + ">");
} else {
ps.println(">" + XML.escapeXMLChars(value) + "</" + name + ">");
}
return;
}
ps.print(indentString + "<" + name);
outputAttributes(ps);
ps.println(">");
int nChildNodes = getNNodes();
for (int n=0; n<nChildNodes; n++) {
Node cnode = getNode(n);
cnode.output(ps, indentLevel+1, true);
}
ps.println(indentString +"</" + name + ">");
}
public String toString(String enc, boolean hasChildNode)
{
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
PrintWriter pr = new PrintWriter(byteOut);
output(pr, 0, hasChildNode);
pr.flush();
try {
if (enc != null && 0 < enc.length())
return byteOut.toString(enc);
}
catch (UnsupportedEncodingException e) {
}
return byteOut.toString();
}
public String toString()
{
return toString(XML.CHARSET_UTF8, true);
}
public String toXMLString(boolean hasChildNode)
{
String xmlStr = toString();
xmlStr = xmlStr.replaceAll("<", "<");
xmlStr = xmlStr.replaceAll(">", ">");
// Thanks for Theo Beisch (11/09/04)
xmlStr = xmlStr.replaceAll("&", "&");
xmlStr = xmlStr.replaceAll("\"", """);
// Thanks for Brian Owens (12/02/04)
xmlStr = xmlStr.replaceAll("'", "'");
return xmlStr;
}
public String toXMLString()
{
return toXMLString(true);
}
public void print(boolean hasChildNode)
{
PrintWriter pr = new PrintWriter(System.out);
output(pr, 0, hasChildNode);
pr.flush();
}
public void print()
{
print(true);
}
}
| i2p/i2p.i2p | router/java/src/org/cybergarage/xml/Node.java | 3,716 | // Element (Child Node) | line_comment | nl | /******************************************************************
*
* CyberXML for Java
*
* Copyright (C) Satoshi Konno 2002
*
* File: Element.java
*
* Revision;
*
* 11/27/02
* - first revision.
* 11/01/03
* - Terje Bakken
* - fixed missing escaping of reserved XML characters
* 11/19/04
* - Theo Beisch <[email protected]>
* - Added "&" and "\"" "\\" to toXMLString().
* 11/19/04
* - Theo Beisch <[email protected]>
* - Changed XML::output() to use short notation when the tag value is null.
* 12/02/04
* - Brian Owens <[email protected]>
* - Fixed toXMLString() to convert from "'" to "'" instead of "\".
* 11/07/05
* - Changed toString() to return as utf-8 string.
* 02/08/08
* - Added addValue().
*
******************************************************************/
package org.cybergarage.xml;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
public class Node
{
/**
* Create a Node with empty UserData and no Parent Node
*
*/
public Node()
{
setUserData(null);
setParentNode(null);
}
public Node(String name)
{
this();
setName(name);
}
public Node(String ns, String name)
{
this();
setName(ns, name);
}
public Node(Node otherNode)
{
this();
set(otherNode);
}
////////////////////////////////////////////////
// parent node
////////////////////////////////////////////////
private Node parentNode = null;
public void setParentNode(Node node)
{
parentNode = node;
}
public Node getParentNode()
{
return parentNode;
}
////////////////////////////////////////////////
// root node
////////////////////////////////////////////////
public Node getRootNode()
{
Node rootNode = null;
Node parentNode = getParentNode();
while (parentNode != null) {
rootNode = parentNode;
parentNode = rootNode.getParentNode();
}
return rootNode;
}
////////////////////////////////////////////////
// name
////////////////////////////////////////////////
private String name = new String();
public void setName(String name)
{
this.name = name;
}
public void setName(String ns, String name)
{
this.name = ns + ":" + name;
}
public String getName()
{
return name;
}
public boolean isName(String value)
{
return name.equals(value);
}
////////////////////////////////////////////////
// value
////////////////////////////////////////////////
private String value = new String();
public void setValue(String value)
{
this.value = value;
}
public void setValue(int value)
{
setValue(Integer.toString(value));
}
public void addValue(String value)
{
if (this.value == null) {
this.value = value;
return;
}
if (value != null)
this.value += value;
}
public String getValue()
{
return value;
}
////////////////////////////////////////////////
// Attribute (Basic)
////////////////////////////////////////////////
private AttributeList attrList = new AttributeList();
public int getNAttributes() {
return attrList.size();
}
public Attribute getAttribute(int index) {
return attrList.getAttribute(index);
}
public Attribute getAttribute(String name)
{
return attrList.getAttribute(name);
}
public void addAttribute(Attribute attr) {
attrList.add(attr);
}
public void insertAttributeAt(Attribute attr, int index) {
attrList.insertElementAt(attr, index);
}
public void addAttribute(String name, String value) {
Attribute attr = new Attribute(name, value);
addAttribute(attr);
}
public boolean removeAttribute(Attribute attr) {
return attrList.remove(attr);
}
public boolean removeAttribute(String name) {
return removeAttribute(getAttribute(name));
}
public void removeAllAttributes()
{
attrList.clear();
}
public boolean hasAttributes()
{
if (0 < getNAttributes())
return true;
return false;
}
////////////////////////////////////////////////
// Attribute (Extention)
////////////////////////////////////////////////
public void setAttribute(String name, String value) {
Attribute attr = getAttribute(name);
if (attr != null) {
attr.setValue(value);
return;
}
attr = new Attribute(name, value);
addAttribute(attr);
}
public void setAttribute(String name, int value) {
setAttribute(name, Integer.toString(value));
}
public String getAttributeValue(String name) {
Attribute attr = getAttribute(name);
if (attr != null)
return attr.getValue();
return "";
}
public int getAttributeIntegerValue(String name) {
String val = getAttributeValue(name);
try {
return Integer.parseInt(val);
}
catch (Exception e) {}
return 0;
}
////////////////////////////////////////////////
// Attribute (xmlns)
////////////////////////////////////////////////
public void setNameSpace(String ns, String value)
{
setAttribute("xmlns:" + ns, value);
}
////////////////////////////////////////////////
// set
////////////////////////////////////////////////
public boolean set(Node otherNode) {
if (otherNode == null)
return false;
setName(otherNode.getName());
setValue(otherNode.getValue());
removeAllAttributes();
int nOtherAttributes = otherNode.getNAttributes();
for (int n=0; n<nOtherAttributes; n++) {
Attribute otherAttr = otherNode.getAttribute(n);
Attribute thisAttr = new Attribute(otherAttr);
addAttribute(thisAttr);
}
removeAllNodes();
int nOtherChildNodes = otherNode.getNNodes();
for (int n=0; n<nOtherChildNodes; n++) {
Node otherChildNode = otherNode.getNode(n);
Node thisChildNode = new Node();
thisChildNode.set(otherChildNode);
addNode(thisChildNode);
}
return true;
}
////////////////////////////////////////////////
// equals
////////////////////////////////////////////////
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null)
return false;
if (!(o instanceof Node))
return false;
Node otherNode = (Node) o;
String thisNodeString = toString();
String otherNodeString = otherNode.toString();
return thisNodeString.equals(otherNodeString);
}
////////////////////////////////////////////////
// Child node
////////////////////////////////////////////////
private NodeList nodeList = new NodeList();
public int getNNodes() {
return nodeList.size();
}
public Node getNode(int index) {
return nodeList.getNode(index);
}
public Node getNode(String name)
{
return nodeList.getNode(name);
}
public Node getNodeEndsWith(String name)
{
return nodeList.getEndsWith(name);
}
public void addNode(Node node) {
node.setParentNode(this);
nodeList.add(node);
}
public void insertNode(Node node, int index) {
node.setParentNode(this);
nodeList.insertElementAt(node, index);
}
public int getIndex(String name){
int index = -1;
for (Iterator<Node> i = nodeList.iterator(); i.hasNext();) {
index++;
Node n = i.next();
if(n.getName().equals(name))
return index;
}
return index;
}
public boolean removeNode(Node node) {
node.setParentNode(null);
return nodeList.remove(node);
}
public boolean removeNode(String name) {
return nodeList.remove(getNode(name));
}
public void removeAllNodes()
{
nodeList.clear();
}
public boolean hasNodes()
{
if (0 < getNNodes())
return true;
return false;
}
////////////////////////////////////////////////
// Element (Child<SUF>
////////////////////////////////////////////////
public boolean hasNode(String name) {
Node node = getNode(name);
if (node != null) {
return true;
}
return false;
}
public void setNode(String name) {
if (hasNode(name)) {
return;
}
Node node = new Node(name);
addNode(node);
}
public void setNode(String name, String value) {
Node node = getNode(name);
if (node == null) {
node = new Node(name);
addNode(node);
}
node.setValue(value);
}
public String getNodeValue(String name) {
Node node = getNode(name);
if (node != null)
return node.getValue();
return "";
}
////////////////////////////////////////////////
// userData
////////////////////////////////////////////////
private Object userData = null;
public void setUserData(Object data)
{
userData = data;
}
public Object getUserData()
{
return userData;
}
////////////////////////////////////////////////
// toString
////////////////////////////////////////////////
/**
* Inovoke {@link #getIndentLevelString(int, String)} with <code>" "</code> as String
*
* @see #getIndentLevelString(int, String)
*/
public String getIndentLevelString(int nIndentLevel)
{
return getIndentLevelString(nIndentLevel," ");
}
/**
*
* @param nIndentLevel the level of indentation to produce
* @param space the String to use for the intendation
* @since 1.8.0
* @return an indentation String
*/
public String getIndentLevelString(int nIndentLevel,String space)
{
StringBuffer indentString = new StringBuffer(nIndentLevel*space.length());
for (int n=0; n<nIndentLevel; n++){
indentString.append(space);
}
return indentString.toString();
}
public void outputAttributes(PrintWriter ps)
{
int nAttributes = getNAttributes();
for (int n=0; n<nAttributes; n++) {
Attribute attr = getAttribute(n);
ps.print(" " + attr.getName() + "=\"" + XML.escapeXMLChars(attr.getValue()) + "\"");
}
}
public void output(PrintWriter ps, int indentLevel, boolean hasChildNode)
{
String indentString = getIndentLevelString(indentLevel);
String name = getName();
String value = getValue();
if (hasNodes() == false || hasChildNode == false) {
ps.print(indentString + "<" + name);
outputAttributes(ps);
// Thnaks for Tho Beisch (11/09/04)
if (value == null || value.length() == 0) {
// Not using the short notation <node /> because it cause compatibility trouble
ps.println("></" + name + ">");
} else {
ps.println(">" + XML.escapeXMLChars(value) + "</" + name + ">");
}
return;
}
ps.print(indentString + "<" + name);
outputAttributes(ps);
ps.println(">");
int nChildNodes = getNNodes();
for (int n=0; n<nChildNodes; n++) {
Node cnode = getNode(n);
cnode.output(ps, indentLevel+1, true);
}
ps.println(indentString +"</" + name + ">");
}
public String toString(String enc, boolean hasChildNode)
{
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
PrintWriter pr = new PrintWriter(byteOut);
output(pr, 0, hasChildNode);
pr.flush();
try {
if (enc != null && 0 < enc.length())
return byteOut.toString(enc);
}
catch (UnsupportedEncodingException e) {
}
return byteOut.toString();
}
public String toString()
{
return toString(XML.CHARSET_UTF8, true);
}
public String toXMLString(boolean hasChildNode)
{
String xmlStr = toString();
xmlStr = xmlStr.replaceAll("<", "<");
xmlStr = xmlStr.replaceAll(">", ">");
// Thanks for Theo Beisch (11/09/04)
xmlStr = xmlStr.replaceAll("&", "&");
xmlStr = xmlStr.replaceAll("\"", """);
// Thanks for Brian Owens (12/02/04)
xmlStr = xmlStr.replaceAll("'", "'");
return xmlStr;
}
public String toXMLString()
{
return toXMLString(true);
}
public void print(boolean hasChildNode)
{
PrintWriter pr = new PrintWriter(System.out);
output(pr, 0, hasChildNode);
pr.flush();
}
public void print()
{
print(true);
}
}
| False | 2,792 | 6 | 3,392 | 7 | 3,529 | 7 | 3,392 | 7 | 4,035 | 7 | false | false | false | false | false | true |
2,136 | 189586_1 | package net.arrav.util;
import java.util.concurrent.atomic.AtomicInteger;
/**
* The container class that contains functions to simplify the modification of a
* number.
* <p>
* <p>
* This class is similar in functionality to {@link AtomicInteger} but does not
* support atomic operations, and therefore should not be used across multiple
* threads.
* @author lare96 <http://github.com/lare96>
*/
public final class MutableNumber extends Number implements Comparable<MutableNumber> { // pure lare code, echt ongelofelijk dit
/**
* The constant serial version UID for serialization.
*/
private static final long serialVersionUID = -7475363158492415879L;
/**
* The value present within this counter.
*/
private int value;
/**
* Creates a new {@link MutableNumber} with {@code value}.
* @param value the value present within this counter.
*/
public MutableNumber(int value) {
this.value = value;
}
/**
* Creates a new {@link MutableNumber} with a value of {@code 0}.
*/
public MutableNumber() {
this(0);
}
@Override
public String toString() {
return Integer.toString(value);
}
@Override
public int hashCode() {
return Integer.hashCode(value);
}
@Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj == null)
return false;
if(!(obj instanceof MutableNumber))
return false;
MutableNumber other = (MutableNumber) obj;
return value == other.value;
}
@Override
public int compareTo(MutableNumber o) {
return Integer.compare(value, o.value);
}
/**
* {@inheritDoc}
* <p>
* This function equates to the {@link MutableNumber#get()} function.
*/
@Override
public int intValue() {
return value;
}
@Override
public long longValue() {
return (long) value;
}
@Override
public float floatValue() {
return (float) value;
}
@Override
public double doubleValue() {
return (double) value;
}
/**
* Returns the value within this counter and then increments it by
* {@code amount} to a maximum of {@code maximum}.
* @param amount the amount to increment it by.
* @param maximum the maximum amount it will be incremented to.
* @return the value before it is incremented.
*/
public int getAndIncrement(int amount, int maximum) {
int val = value;
value += amount;
if(value > maximum)
value = maximum;
return val;
}
/**
* Returns the value within this counter and then increments it by
* {@code amount}.
* @param amount the amount to increment it by.
* @return the value before it is incremented.
*/
public int getAndIncrement(int amount) {
return getAndIncrement(amount, Integer.MAX_VALUE);
}
/**
* Returns the value within this counter and then increments it by an amount
* of {@code 1}.
* @return the value before it is incremented.
*/
public int getAndIncrement() {
return getAndIncrement(1);
}
//guys I have to go, it's me stan
//It's taraweeh time, gonna go pray and come back
//u guys can stay on teamviewer just shut it down when ur done, ill
//tell my mom not to close the laptop
//just dont do stupid stuff please xD ok -at rtnp ty <3
/**
* Increments the value within this counter by {@code amount} to a maximum
* of {@code maximum} and then returns it.
* @param amount the amount to increment it by.
* @param maximum the maximum amount it will be incremented to.
* @return the value after it is incremented.
*/
public int incrementAndGet(int amount, int maximum) {
value += amount;
if(value > maximum)
value = maximum;
return value;
}
/**
* Increments the value within this counter by {@code amount} and then
* returns it.
* @param amount the amount to increment it by.
* @return the value after it is incremented.
*/
public int incrementAndGet(int amount) {
return incrementAndGet(amount, Integer.MAX_VALUE);
}
/**
* Increments the value within this counter by {@code 1} and then returns
* it.
* @return the value after it is incremented.
*/
public int incrementAndGet() {
return incrementAndGet(1);
}
/**
* Returns the value within this counter and then decrements it by
* {@code amount} to a minimum of {@code minimum}.
* @param amount the amount to decrement it by.
* @param minimum the minimum amount it will be decremented to.
* @return the value before it is decremented.
*/
public int getAndDecrement(int amount, int minimum) {
int val = value;
value -= amount;
if(value < minimum)
value = minimum;
return val;
}
/**
* Returns the value within this counter and then decrements it by
* {@code amount}.
* @param amount the amount to decrement it by.
* @return the value before it is decremented.
*/
public int getAndDecrement(int amount) {
return getAndDecrement(amount, Integer.MIN_VALUE);
}
/**
* Returns the value within this counter and then decrements it by an amount
* of {@code 1}.
* @return the value before it is decremented.
*/
public int getAndDecrement() {
return getAndDecrement(1);
}
/**
* Decrements the value within this counter by {@code amount} to a minimum
* of {@code minimum} and then returns it.
* @param amount the amount to decrement it by.
* @param minimum the minimum amount it will be decremented to.
* @return the value after it is decremented.
*/
public int decrementAndGet(int amount, int minimum) {
value -= amount;
if(value < minimum)
value = minimum;
return value;
}
/**
* Decrements the value within this counter by {@code amount} and then
* returns it.
* @param amount the amount to decrement it by.
* @return the value after it is decremented.
*/
public int decrementAndGet(int amount) {
return decrementAndGet(amount, Integer.MIN_VALUE);
}
/**
* Decrements the value within this counter by {@code 1} and then returns
* it.
* @return the value after it is decremented.
*/
public int decrementAndGet() {
return decrementAndGet(1);
}
/**
* Gets the value present within this counter. This function equates to the
* inherited {@link MutableNumber#intValue()} function.
* @return the value present.
*/
public int get() {
return value;
}
/**
* Sets the value within this container to {@code value}.
* @param value the new value to set.
*/
public void set(int value) {
this.value = value;
}
}
| artembatutin/arrav_server | src/net/arrav/util/MutableNumber.java | 1,978 | // pure lare code, echt ongelofelijk dit | line_comment | nl | package net.arrav.util;
import java.util.concurrent.atomic.AtomicInteger;
/**
* The container class that contains functions to simplify the modification of a
* number.
* <p>
* <p>
* This class is similar in functionality to {@link AtomicInteger} but does not
* support atomic operations, and therefore should not be used across multiple
* threads.
* @author lare96 <http://github.com/lare96>
*/
public final class MutableNumber extends Number implements Comparable<MutableNumber> { // pure lare<SUF>
/**
* The constant serial version UID for serialization.
*/
private static final long serialVersionUID = -7475363158492415879L;
/**
* The value present within this counter.
*/
private int value;
/**
* Creates a new {@link MutableNumber} with {@code value}.
* @param value the value present within this counter.
*/
public MutableNumber(int value) {
this.value = value;
}
/**
* Creates a new {@link MutableNumber} with a value of {@code 0}.
*/
public MutableNumber() {
this(0);
}
@Override
public String toString() {
return Integer.toString(value);
}
@Override
public int hashCode() {
return Integer.hashCode(value);
}
@Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj == null)
return false;
if(!(obj instanceof MutableNumber))
return false;
MutableNumber other = (MutableNumber) obj;
return value == other.value;
}
@Override
public int compareTo(MutableNumber o) {
return Integer.compare(value, o.value);
}
/**
* {@inheritDoc}
* <p>
* This function equates to the {@link MutableNumber#get()} function.
*/
@Override
public int intValue() {
return value;
}
@Override
public long longValue() {
return (long) value;
}
@Override
public float floatValue() {
return (float) value;
}
@Override
public double doubleValue() {
return (double) value;
}
/**
* Returns the value within this counter and then increments it by
* {@code amount} to a maximum of {@code maximum}.
* @param amount the amount to increment it by.
* @param maximum the maximum amount it will be incremented to.
* @return the value before it is incremented.
*/
public int getAndIncrement(int amount, int maximum) {
int val = value;
value += amount;
if(value > maximum)
value = maximum;
return val;
}
/**
* Returns the value within this counter and then increments it by
* {@code amount}.
* @param amount the amount to increment it by.
* @return the value before it is incremented.
*/
public int getAndIncrement(int amount) {
return getAndIncrement(amount, Integer.MAX_VALUE);
}
/**
* Returns the value within this counter and then increments it by an amount
* of {@code 1}.
* @return the value before it is incremented.
*/
public int getAndIncrement() {
return getAndIncrement(1);
}
//guys I have to go, it's me stan
//It's taraweeh time, gonna go pray and come back
//u guys can stay on teamviewer just shut it down when ur done, ill
//tell my mom not to close the laptop
//just dont do stupid stuff please xD ok -at rtnp ty <3
/**
* Increments the value within this counter by {@code amount} to a maximum
* of {@code maximum} and then returns it.
* @param amount the amount to increment it by.
* @param maximum the maximum amount it will be incremented to.
* @return the value after it is incremented.
*/
public int incrementAndGet(int amount, int maximum) {
value += amount;
if(value > maximum)
value = maximum;
return value;
}
/**
* Increments the value within this counter by {@code amount} and then
* returns it.
* @param amount the amount to increment it by.
* @return the value after it is incremented.
*/
public int incrementAndGet(int amount) {
return incrementAndGet(amount, Integer.MAX_VALUE);
}
/**
* Increments the value within this counter by {@code 1} and then returns
* it.
* @return the value after it is incremented.
*/
public int incrementAndGet() {
return incrementAndGet(1);
}
/**
* Returns the value within this counter and then decrements it by
* {@code amount} to a minimum of {@code minimum}.
* @param amount the amount to decrement it by.
* @param minimum the minimum amount it will be decremented to.
* @return the value before it is decremented.
*/
public int getAndDecrement(int amount, int minimum) {
int val = value;
value -= amount;
if(value < minimum)
value = minimum;
return val;
}
/**
* Returns the value within this counter and then decrements it by
* {@code amount}.
* @param amount the amount to decrement it by.
* @return the value before it is decremented.
*/
public int getAndDecrement(int amount) {
return getAndDecrement(amount, Integer.MIN_VALUE);
}
/**
* Returns the value within this counter and then decrements it by an amount
* of {@code 1}.
* @return the value before it is decremented.
*/
public int getAndDecrement() {
return getAndDecrement(1);
}
/**
* Decrements the value within this counter by {@code amount} to a minimum
* of {@code minimum} and then returns it.
* @param amount the amount to decrement it by.
* @param minimum the minimum amount it will be decremented to.
* @return the value after it is decremented.
*/
public int decrementAndGet(int amount, int minimum) {
value -= amount;
if(value < minimum)
value = minimum;
return value;
}
/**
* Decrements the value within this counter by {@code amount} and then
* returns it.
* @param amount the amount to decrement it by.
* @return the value after it is decremented.
*/
public int decrementAndGet(int amount) {
return decrementAndGet(amount, Integer.MIN_VALUE);
}
/**
* Decrements the value within this counter by {@code 1} and then returns
* it.
* @return the value after it is decremented.
*/
public int decrementAndGet() {
return decrementAndGet(1);
}
/**
* Gets the value present within this counter. This function equates to the
* inherited {@link MutableNumber#intValue()} function.
* @return the value present.
*/
public int get() {
return value;
}
/**
* Sets the value within this container to {@code value}.
* @param value the new value to set.
*/
public void set(int value) {
this.value = value;
}
}
| O | 1,610 | 12 | 1,802 | 14 | 1,915 | 11 | 1,802 | 14 | 2,059 | 13 | false | false | false | false | false | true |
3,133 | 13739_11 | package afvink3;
/**
* Race class
* Class Race maakt gebruik van de class Paard
*
* @author Martijn van der Bruggen
* @version alpha - aanroep van cruciale methodes ontbreekt
* (c) 2009 Hogeschool van Arnhem en Nijmegen
*
* Note: deze code is bewust niet op alle punten generiek
* dit om nog onbekende constructies te vermijden.
*
* Updates
* 2010: verduidelijking van opdrachten in de code MvdB
* 2011: verbetering leesbaarheid code MvdB
* 2012: verbetering layout code en aanpassing commentaar MvdB
* 2013: commentaar aangepast aan nieuwe opdracht MvdB
*
*************************************************
* Afvinkopdracht: werken met methodes en objecten
*************************************************
* Opdrachten zitten verwerkt in de code
* 1) Declaratie constante
* 2) Declaratie van Paard (niet instantiering)
* 3) Declareer een button
* 4) Zet breedte en hoogte van het frame
* 5) Teken een finish streep
* 6) Creatie van 4 paarden
* 7) Pauzeer
* 8) Teken 4 paarden
* 9) Plaats tekst op de button
* 10) Start de race, methode aanroep
*
*
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Race extends JFrame implements ActionListener {
/** declaratie van variabelen */
/* (1) Declareer hier een constante int met de naam lengte en een waarde van 250 */
/* (2) Declareer hier h1, h2, h3, h4 van het type Paard
* Deze paarden instantieer je later in het programma
*/
/* (3) Declareer een button met de naam button van het type JButton */
private JPanel panel;
/** Applicatie - main functie voor runnen applicatie */
public static void main(String[] args) {
Race frame = new Race();
/* (4) Geef het frame een breedte van 400 en hoogte van 140 */
frame.createGUI();
frame.setVisible(true);
}
/** Loop de race
*/
private void startRace(Graphics g) {
panel.setBackground(Color.white);
/** Tekenen van de finish streep */
/* (5) Geef de finish streep een rode kleur */
g.fillRect(lengte, 0, 3, 100);
/**(6) Creatie van 4 paarden
* Dit is een instantiering van de 4 paard objecten
* Bij de instantiering geef je de paarden een naam en een kleur mee
* Kijk in de class Paard hoe je de paarden
* kunt initialiseren.
*/
/** Loop tot een paard over de finish is*/
while (h1.getAfstand() < lengte
&& h2.getAfstand() < lengte
&& h3.getAfstand() < lengte
&& h4.getAfstand() < lengte) {
h1.run();
h2.run();
h3.run();
h4.run();
/* (7) Voeg hier een aanroep van de methode pauzeer toe zodanig
* dat er 1 seconde pauze is. De methode pauzeer is onderdeel
* van deze class
*/
/* (8) Voeg hier code in om 4 paarden te tekenen die rennen
* Dus een call van de methode tekenPaard
*/
}
/** Kijk welk paard gewonnen heeft
*/
if (h1.getAfstand() > lengte) {
JOptionPane.showMessageDialog(null, h1.getNaam() + " gewonnen!");
}
if (h2.getAfstand() > lengte) {
JOptionPane.showMessageDialog(null, h2.getNaam() + " gewonnen!");
}
if (h3.getAfstand() > lengte) {
JOptionPane.showMessageDialog(null, h3.getNaam() + " gewonnen!");
}
if (h4.getAfstand() > lengte) {
JOptionPane.showMessageDialog(null, h4.getNaam() + " gewonnen!");
}
}
/** Creatie van de GUI*/
private void createGUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new FlowLayout());
panel = new JPanel();
panel.setPreferredSize(new Dimension(300, 100));
panel.setBackground(Color.white);
window.add(panel);
/* (9) Zet hier de tekst Run! op de button */
window.add(button);
button.addActionListener(this);
}
/** Teken het paard */
private void tekenPaard(Graphics g, Paard h) {
g.setColor(h.getKleur());
g.fillRect(10, 20 * h.getPaardNummer(), h.getAfstand(), 5);
}
/** Actie indien de button geklikt is*/
public void actionPerformed(ActionEvent event) {
Graphics paper = panel.getGraphics();
/* (10) Roep hier de methode startrace aan met de juiste parameterisering */
startRace (paper);
}
/** Pauzeer gedurende x millisecondes*/
public void pauzeer(int msec) {
try {
Thread.sleep(msec);
} catch (InterruptedException e) {
System.out.println("Pauze interruptie");
}
}
}
| itbc-bin/1819-owe5a-afvinkopdracht3-silvappeldoorn | afvink3/Race.java | 1,525 | /** Loop tot een paard over de finish is*/ | block_comment | nl | package afvink3;
/**
* Race class
* Class Race maakt gebruik van de class Paard
*
* @author Martijn van der Bruggen
* @version alpha - aanroep van cruciale methodes ontbreekt
* (c) 2009 Hogeschool van Arnhem en Nijmegen
*
* Note: deze code is bewust niet op alle punten generiek
* dit om nog onbekende constructies te vermijden.
*
* Updates
* 2010: verduidelijking van opdrachten in de code MvdB
* 2011: verbetering leesbaarheid code MvdB
* 2012: verbetering layout code en aanpassing commentaar MvdB
* 2013: commentaar aangepast aan nieuwe opdracht MvdB
*
*************************************************
* Afvinkopdracht: werken met methodes en objecten
*************************************************
* Opdrachten zitten verwerkt in de code
* 1) Declaratie constante
* 2) Declaratie van Paard (niet instantiering)
* 3) Declareer een button
* 4) Zet breedte en hoogte van het frame
* 5) Teken een finish streep
* 6) Creatie van 4 paarden
* 7) Pauzeer
* 8) Teken 4 paarden
* 9) Plaats tekst op de button
* 10) Start de race, methode aanroep
*
*
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Race extends JFrame implements ActionListener {
/** declaratie van variabelen */
/* (1) Declareer hier een constante int met de naam lengte en een waarde van 250 */
/* (2) Declareer hier h1, h2, h3, h4 van het type Paard
* Deze paarden instantieer je later in het programma
*/
/* (3) Declareer een button met de naam button van het type JButton */
private JPanel panel;
/** Applicatie - main functie voor runnen applicatie */
public static void main(String[] args) {
Race frame = new Race();
/* (4) Geef het frame een breedte van 400 en hoogte van 140 */
frame.createGUI();
frame.setVisible(true);
}
/** Loop de race
*/
private void startRace(Graphics g) {
panel.setBackground(Color.white);
/** Tekenen van de finish streep */
/* (5) Geef de finish streep een rode kleur */
g.fillRect(lengte, 0, 3, 100);
/**(6) Creatie van 4 paarden
* Dit is een instantiering van de 4 paard objecten
* Bij de instantiering geef je de paarden een naam en een kleur mee
* Kijk in de class Paard hoe je de paarden
* kunt initialiseren.
*/
/** Loop tot een<SUF>*/
while (h1.getAfstand() < lengte
&& h2.getAfstand() < lengte
&& h3.getAfstand() < lengte
&& h4.getAfstand() < lengte) {
h1.run();
h2.run();
h3.run();
h4.run();
/* (7) Voeg hier een aanroep van de methode pauzeer toe zodanig
* dat er 1 seconde pauze is. De methode pauzeer is onderdeel
* van deze class
*/
/* (8) Voeg hier code in om 4 paarden te tekenen die rennen
* Dus een call van de methode tekenPaard
*/
}
/** Kijk welk paard gewonnen heeft
*/
if (h1.getAfstand() > lengte) {
JOptionPane.showMessageDialog(null, h1.getNaam() + " gewonnen!");
}
if (h2.getAfstand() > lengte) {
JOptionPane.showMessageDialog(null, h2.getNaam() + " gewonnen!");
}
if (h3.getAfstand() > lengte) {
JOptionPane.showMessageDialog(null, h3.getNaam() + " gewonnen!");
}
if (h4.getAfstand() > lengte) {
JOptionPane.showMessageDialog(null, h4.getNaam() + " gewonnen!");
}
}
/** Creatie van de GUI*/
private void createGUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new FlowLayout());
panel = new JPanel();
panel.setPreferredSize(new Dimension(300, 100));
panel.setBackground(Color.white);
window.add(panel);
/* (9) Zet hier de tekst Run! op de button */
window.add(button);
button.addActionListener(this);
}
/** Teken het paard */
private void tekenPaard(Graphics g, Paard h) {
g.setColor(h.getKleur());
g.fillRect(10, 20 * h.getPaardNummer(), h.getAfstand(), 5);
}
/** Actie indien de button geklikt is*/
public void actionPerformed(ActionEvent event) {
Graphics paper = panel.getGraphics();
/* (10) Roep hier de methode startrace aan met de juiste parameterisering */
startRace (paper);
}
/** Pauzeer gedurende x millisecondes*/
public void pauzeer(int msec) {
try {
Thread.sleep(msec);
} catch (InterruptedException e) {
System.out.println("Pauze interruptie");
}
}
}
| True | 1,282 | 11 | 1,422 | 11 | 1,363 | 10 | 1,422 | 11 | 1,544 | 11 | false | false | false | false | false | true |
3,915 | 3421_22 | /*
* Copyright The OpenZipkin Authors
* SPDX-License-Identifier: Apache-2.0
*/
package zipkin2.v1;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import zipkin2.Endpoint;
import zipkin2.Span;
import zipkin2.internal.Nullable;
import static java.util.Collections.unmodifiableList;
import static zipkin2.internal.HexCodec.lowerHexToUnsignedLong;
/**
* V1 spans are different from v2 especially as annotations repeat. Support is available to help
* migrate old code or allow for parsing older data formats.
*
* @deprecated new code should use {@link Span}.
*/
@Deprecated
public final class V1Span {
static final Endpoint EMPTY_ENDPOINT = Endpoint.newBuilder().build();
/** When non-zero, the trace containing this span uses 128-bit trace identifiers. */
public long traceIdHigh() {
return traceIdHigh;
}
/** lower 64-bits of the {@link Span#traceId()} */
public long traceId() {
return traceId;
}
/** Same as {@link zipkin2.Span#id()} except packed into a long. Zero means root span. */
public long id() {
return id;
}
/** Same as {@link zipkin2.Span#name()} */
public String name() {
return name;
}
/** The parent's {@link #id()} or zero if this the root span in a trace. */
public long parentId() {
return parentId;
}
/** Same as {@link Span#timestampAsLong()} */
public long timestamp() {
return timestamp;
}
/** Same as {@link Span#durationAsLong()} */
public long duration() {
return duration;
}
/**
* Same as {@link Span#annotations()}, except each may be associated with {@link
* Span#localEndpoint()}
*/
public List<V1Annotation> annotations() {
return annotations;
}
/**
* {@link Span#tags()} are allocated to binary annotations with a {@link
* V1BinaryAnnotation#stringValue()}. {@link Span#remoteEndpoint()} to those without.
*/
public List<V1BinaryAnnotation> binaryAnnotations() {
return binaryAnnotations;
}
/** Same as {@link Span#debug()} */
public Boolean debug() {
return debug;
}
final long traceIdHigh, traceId, id;
final String name;
final long parentId, timestamp, duration;
final List<V1Annotation> annotations;
final List<V1BinaryAnnotation> binaryAnnotations;
final Boolean debug;
V1Span(Builder builder) {
if (builder.traceId == 0L) throw new IllegalArgumentException("traceId == 0");
if (builder.id == 0L) throw new IllegalArgumentException("id == 0");
this.traceId = builder.traceId;
this.traceIdHigh = builder.traceIdHigh;
this.name = builder.name;
this.id = builder.id;
this.parentId = builder.parentId;
this.timestamp = builder.timestamp;
this.duration = builder.duration;
this.annotations = sortedList(builder.annotations);
this.binaryAnnotations = sortedList(builder.binaryAnnotations);
this.debug = builder.debug;
}
public static Builder newBuilder() {
return new Builder();
}
public static final class Builder {
// ID accessors are here to help organize builders by their identifiers
/** Sets {@link V1Span#traceIdHigh()} */
public long traceIdHigh() {
return traceIdHigh;
}
/** Sets {@link V1Span#traceId()} */
public long traceId() {
return traceId;
}
/** Sets {@link V1Span#id()} */
public long id() {
return id;
}
long traceIdHigh, traceId, parentId, id;
String name;
long timestamp, duration;
ArrayList<V1Annotation> annotations;
ArrayList<V1BinaryAnnotation> binaryAnnotations;
Boolean debug;
Builder() {
}
public Builder clear() {
traceId = traceIdHigh = id = 0;
name = null;
parentId = timestamp = duration = 0;
if (annotations != null) annotations.clear();
if (binaryAnnotations != null) binaryAnnotations.clear();
debug = null;
return this;
}
/** Same as {@link Span.Builder#traceId(String)} */
public Builder traceId(String traceId) {
if (traceId == null) throw new NullPointerException("traceId == null");
if (traceId.length() == 32) {
traceIdHigh = lowerHexToUnsignedLong(traceId, 0);
}
this.traceId = lowerHexToUnsignedLong(traceId);
return this;
}
/** Sets {@link V1Span#traceId()} */
public Builder traceId(long traceId) {
this.traceId = traceId;
return this;
}
/** Sets {@link V1Span#traceIdHigh()} */
public Builder traceIdHigh(long traceIdHigh) {
this.traceIdHigh = traceIdHigh;
return this;
}
/** Sets {@link V1Span#id()} */
public Builder id(long id) {
this.id = id;
return this;
}
/** Same as {@link Span.Builder#id(String)} */
public Builder id(String id) {
if (id == null) throw new NullPointerException("id == null");
this.id = lowerHexToUnsignedLong(id);
return this;
}
/** Same as {@link Span.Builder#parentId(String)} */
public Builder parentId(String parentId) {
this.parentId = parentId != null ? lowerHexToUnsignedLong(parentId) : 0L;
return this;
}
/** Sets {@link V1Span#parentId()} */
public Builder parentId(long parentId) {
this.parentId = parentId;
return this;
}
/** Sets {@link V1Span#name()} */
public Builder name(String name) {
this.name = name == null || name.isEmpty() ? null : name.toLowerCase(Locale.ROOT);
return this;
}
/** Sets {@link V1Span#timestamp()} */
public Builder timestamp(long timestamp) {
this.timestamp = timestamp;
return this;
}
/** Sets {@link V1Span#duration()} */
public Builder duration(long duration) {
this.duration = duration;
return this;
}
/** Sets {@link V1Span#annotations()} */
public Builder addAnnotation(long timestamp, String value, @Nullable Endpoint endpoint) {
if (annotations == null) annotations = new ArrayList<>(4);
if (EMPTY_ENDPOINT.equals(endpoint)) endpoint = null;
annotations.add(new V1Annotation(timestamp, value, endpoint));
return this;
}
/** Creates an address annotation, which is the same as {@link Span#remoteEndpoint()} */
public Builder addBinaryAnnotation(String address, Endpoint endpoint) {
// Ignore empty endpoints rather than crashing v1 parsers on bad address data
if (endpoint == null || EMPTY_ENDPOINT.equals(endpoint)) return this;
if (binaryAnnotations == null) binaryAnnotations = new ArrayList<>(4);
binaryAnnotations.add(new V1BinaryAnnotation(address, null, endpoint));
return this;
}
/**
* Creates a tag annotation, which is the same as {@link Span#tags()} except duplicating the
* endpoint.
*
* <p>A key of "lc" and empty value substitutes for {@link Span#localEndpoint()}.
*/
public Builder addBinaryAnnotation(String key, String value, Endpoint endpoint) {
if (value == null) throw new NullPointerException("value == null");
if (EMPTY_ENDPOINT.equals(endpoint)) endpoint = null;
if (binaryAnnotations == null) binaryAnnotations = new ArrayList<>(4);
binaryAnnotations.add(new V1BinaryAnnotation(key, value, endpoint));
return this;
}
/** Sets {@link V1Span#debug()} */
public Builder debug(@Nullable Boolean debug) {
this.debug = debug;
return this;
}
public V1Span build() {
return new V1Span(this);
}
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof V1Span)) return false;
V1Span that = (V1Span) o;
return traceIdHigh == that.traceIdHigh
&& traceId == that.traceId
&& Objects.equals(name, that.name)
&& id == that.id
&& parentId == that.parentId
&& timestamp == that.timestamp
&& duration == that.duration
&& annotations.equals(that.annotations)
&& binaryAnnotations.equals(that.binaryAnnotations)
&& Objects.equals(debug, that.debug);
}
@Override
public int hashCode() {
int h = 1;
h *= 1000003;
h ^= (int) (h ^ ((traceIdHigh >>> 32) ^ traceIdHigh));
h *= 1000003;
h ^= (int) (h ^ ((traceId >>> 32) ^ traceId));
h *= 1000003;
h ^= name == null ? 0 : name.hashCode();
h *= 1000003;
h ^= (int) (h ^ ((id >>> 32) ^ id));
h *= 1000003;
h ^= (int) (h ^ ((parentId >>> 32) ^ parentId));
h *= 1000003;
h ^= (int) (h ^ ((timestamp >>> 32) ^ timestamp));
h *= 1000003;
h ^= (int) (h ^ ((duration >>> 32) ^ duration));
h *= 1000003;
h ^= annotations.hashCode();
h *= 1000003;
h ^= binaryAnnotations.hashCode();
h *= 1000003;
h ^= debug == null ? 0 : debug.hashCode();
return h;
}
static <T extends Comparable<T>> List<T> sortedList(List<T> input) {
if (input == null) return Collections.emptyList();
Collections.sort(input);
return unmodifiableList(new ArrayList<>(input));
}
}
| openzipkin/zipkin | zipkin/src/main/java/zipkin2/v1/V1Span.java | 2,848 | /** Sets {@link V1Span#parentId()} */ | block_comment | nl | /*
* Copyright The OpenZipkin Authors
* SPDX-License-Identifier: Apache-2.0
*/
package zipkin2.v1;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import zipkin2.Endpoint;
import zipkin2.Span;
import zipkin2.internal.Nullable;
import static java.util.Collections.unmodifiableList;
import static zipkin2.internal.HexCodec.lowerHexToUnsignedLong;
/**
* V1 spans are different from v2 especially as annotations repeat. Support is available to help
* migrate old code or allow for parsing older data formats.
*
* @deprecated new code should use {@link Span}.
*/
@Deprecated
public final class V1Span {
static final Endpoint EMPTY_ENDPOINT = Endpoint.newBuilder().build();
/** When non-zero, the trace containing this span uses 128-bit trace identifiers. */
public long traceIdHigh() {
return traceIdHigh;
}
/** lower 64-bits of the {@link Span#traceId()} */
public long traceId() {
return traceId;
}
/** Same as {@link zipkin2.Span#id()} except packed into a long. Zero means root span. */
public long id() {
return id;
}
/** Same as {@link zipkin2.Span#name()} */
public String name() {
return name;
}
/** The parent's {@link #id()} or zero if this the root span in a trace. */
public long parentId() {
return parentId;
}
/** Same as {@link Span#timestampAsLong()} */
public long timestamp() {
return timestamp;
}
/** Same as {@link Span#durationAsLong()} */
public long duration() {
return duration;
}
/**
* Same as {@link Span#annotations()}, except each may be associated with {@link
* Span#localEndpoint()}
*/
public List<V1Annotation> annotations() {
return annotations;
}
/**
* {@link Span#tags()} are allocated to binary annotations with a {@link
* V1BinaryAnnotation#stringValue()}. {@link Span#remoteEndpoint()} to those without.
*/
public List<V1BinaryAnnotation> binaryAnnotations() {
return binaryAnnotations;
}
/** Same as {@link Span#debug()} */
public Boolean debug() {
return debug;
}
final long traceIdHigh, traceId, id;
final String name;
final long parentId, timestamp, duration;
final List<V1Annotation> annotations;
final List<V1BinaryAnnotation> binaryAnnotations;
final Boolean debug;
V1Span(Builder builder) {
if (builder.traceId == 0L) throw new IllegalArgumentException("traceId == 0");
if (builder.id == 0L) throw new IllegalArgumentException("id == 0");
this.traceId = builder.traceId;
this.traceIdHigh = builder.traceIdHigh;
this.name = builder.name;
this.id = builder.id;
this.parentId = builder.parentId;
this.timestamp = builder.timestamp;
this.duration = builder.duration;
this.annotations = sortedList(builder.annotations);
this.binaryAnnotations = sortedList(builder.binaryAnnotations);
this.debug = builder.debug;
}
public static Builder newBuilder() {
return new Builder();
}
public static final class Builder {
// ID accessors are here to help organize builders by their identifiers
/** Sets {@link V1Span#traceIdHigh()} */
public long traceIdHigh() {
return traceIdHigh;
}
/** Sets {@link V1Span#traceId()} */
public long traceId() {
return traceId;
}
/** Sets {@link V1Span#id()} */
public long id() {
return id;
}
long traceIdHigh, traceId, parentId, id;
String name;
long timestamp, duration;
ArrayList<V1Annotation> annotations;
ArrayList<V1BinaryAnnotation> binaryAnnotations;
Boolean debug;
Builder() {
}
public Builder clear() {
traceId = traceIdHigh = id = 0;
name = null;
parentId = timestamp = duration = 0;
if (annotations != null) annotations.clear();
if (binaryAnnotations != null) binaryAnnotations.clear();
debug = null;
return this;
}
/** Same as {@link Span.Builder#traceId(String)} */
public Builder traceId(String traceId) {
if (traceId == null) throw new NullPointerException("traceId == null");
if (traceId.length() == 32) {
traceIdHigh = lowerHexToUnsignedLong(traceId, 0);
}
this.traceId = lowerHexToUnsignedLong(traceId);
return this;
}
/** Sets {@link V1Span#traceId()} */
public Builder traceId(long traceId) {
this.traceId = traceId;
return this;
}
/** Sets {@link V1Span#traceIdHigh()} */
public Builder traceIdHigh(long traceIdHigh) {
this.traceIdHigh = traceIdHigh;
return this;
}
/** Sets {@link V1Span#id()} */
public Builder id(long id) {
this.id = id;
return this;
}
/** Same as {@link Span.Builder#id(String)} */
public Builder id(String id) {
if (id == null) throw new NullPointerException("id == null");
this.id = lowerHexToUnsignedLong(id);
return this;
}
/** Same as {@link Span.Builder#parentId(String)} */
public Builder parentId(String parentId) {
this.parentId = parentId != null ? lowerHexToUnsignedLong(parentId) : 0L;
return this;
}
/** Sets {@link V1Span#parentId()}<SUF>*/
public Builder parentId(long parentId) {
this.parentId = parentId;
return this;
}
/** Sets {@link V1Span#name()} */
public Builder name(String name) {
this.name = name == null || name.isEmpty() ? null : name.toLowerCase(Locale.ROOT);
return this;
}
/** Sets {@link V1Span#timestamp()} */
public Builder timestamp(long timestamp) {
this.timestamp = timestamp;
return this;
}
/** Sets {@link V1Span#duration()} */
public Builder duration(long duration) {
this.duration = duration;
return this;
}
/** Sets {@link V1Span#annotations()} */
public Builder addAnnotation(long timestamp, String value, @Nullable Endpoint endpoint) {
if (annotations == null) annotations = new ArrayList<>(4);
if (EMPTY_ENDPOINT.equals(endpoint)) endpoint = null;
annotations.add(new V1Annotation(timestamp, value, endpoint));
return this;
}
/** Creates an address annotation, which is the same as {@link Span#remoteEndpoint()} */
public Builder addBinaryAnnotation(String address, Endpoint endpoint) {
// Ignore empty endpoints rather than crashing v1 parsers on bad address data
if (endpoint == null || EMPTY_ENDPOINT.equals(endpoint)) return this;
if (binaryAnnotations == null) binaryAnnotations = new ArrayList<>(4);
binaryAnnotations.add(new V1BinaryAnnotation(address, null, endpoint));
return this;
}
/**
* Creates a tag annotation, which is the same as {@link Span#tags()} except duplicating the
* endpoint.
*
* <p>A key of "lc" and empty value substitutes for {@link Span#localEndpoint()}.
*/
public Builder addBinaryAnnotation(String key, String value, Endpoint endpoint) {
if (value == null) throw new NullPointerException("value == null");
if (EMPTY_ENDPOINT.equals(endpoint)) endpoint = null;
if (binaryAnnotations == null) binaryAnnotations = new ArrayList<>(4);
binaryAnnotations.add(new V1BinaryAnnotation(key, value, endpoint));
return this;
}
/** Sets {@link V1Span#debug()} */
public Builder debug(@Nullable Boolean debug) {
this.debug = debug;
return this;
}
public V1Span build() {
return new V1Span(this);
}
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof V1Span)) return false;
V1Span that = (V1Span) o;
return traceIdHigh == that.traceIdHigh
&& traceId == that.traceId
&& Objects.equals(name, that.name)
&& id == that.id
&& parentId == that.parentId
&& timestamp == that.timestamp
&& duration == that.duration
&& annotations.equals(that.annotations)
&& binaryAnnotations.equals(that.binaryAnnotations)
&& Objects.equals(debug, that.debug);
}
@Override
public int hashCode() {
int h = 1;
h *= 1000003;
h ^= (int) (h ^ ((traceIdHigh >>> 32) ^ traceIdHigh));
h *= 1000003;
h ^= (int) (h ^ ((traceId >>> 32) ^ traceId));
h *= 1000003;
h ^= name == null ? 0 : name.hashCode();
h *= 1000003;
h ^= (int) (h ^ ((id >>> 32) ^ id));
h *= 1000003;
h ^= (int) (h ^ ((parentId >>> 32) ^ parentId));
h *= 1000003;
h ^= (int) (h ^ ((timestamp >>> 32) ^ timestamp));
h *= 1000003;
h ^= (int) (h ^ ((duration >>> 32) ^ duration));
h *= 1000003;
h ^= annotations.hashCode();
h *= 1000003;
h ^= binaryAnnotations.hashCode();
h *= 1000003;
h ^= debug == null ? 0 : debug.hashCode();
return h;
}
static <T extends Comparable<T>> List<T> sortedList(List<T> input) {
if (input == null) return Collections.emptyList();
Collections.sort(input);
return unmodifiableList(new ArrayList<>(input));
}
}
| False | 2,226 | 11 | 2,380 | 11 | 2,621 | 11 | 2,380 | 11 | 2,877 | 13 | false | false | false | false | false | true |
1,937 | 137095_1 | package be.vanoosten.esa;
import static be.vanoosten.esa.WikiIndexer.TITLE_FIELD;
import be.vanoosten.esa.tools.*;
import java.io.File;
import java.io.IOException;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.core.StopAnalyzer;
import org.apache.lucene.analysis.util.CharArraySet;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.Fields;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.MultiFields;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.ByteArrayDataOutput;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.AttributeSource;
import org.apache.lucene.util.BytesRef;
import static org.apache.lucene.util.Version.LUCENE_48;
/**
*
* @author Philip van Oosten
*/
public class Main {
public static void main(String[] args) throws IOException, ParseException {
/*
String indexPath = String.join(File.separator, "D:", "Development", "esa", "nlwiki");
File wikipediaDumpFile = new File(String.join(File.separator, "D:", "Downloads", "nlwiki", "nlwiki-20140611-pages-articles-multistream.xml.bz2"));
String startTokens = "geheim anoniem auteur verhalen lezen schrijven wetenschappelijk artikel peer review";
*/
WikiFactory factory = new EnwikiFactory();
File indexPath = factory.getIndexRootPath();
File wikipediaDumpFile = factory.getWikipediaDumpFile();
String startTokens = "secret anonymous author stories read write scientific article peer review";
CharArraySet stopWords = factory.getStopWords();
File termDocIndexDirectory = factory.getTermDocIndexDirectory();
File conceptTermIndexDirectory = factory.getConceptTermIndexDirectory();
// The following lines are commented, because they can take a looong time.
indexing(termDocIndexDirectory, wikipediaDumpFile, stopWords);
createConceptTermIndex(termDocIndexDirectory, conceptTermIndexDirectory);
// Analyzer analyzer = new WikiAnalyzer(LUCENE_48, stopWords);
//
// Vectorizer vectorizer = new Vectorizer(termDocIndexDirectory, analyzer);
//
// SemanticSimilarityTool s = new SemanticSimilarityTool(vectorizer);
//
// float similarity = s.findSemanticSimilarity("Barack_Obama", "Barack_Obama");
}
/**
* Creates a concept-term index from a term-to-concept index (a full text index of a Wikipedia dump).
* @param termDocIndexDirectory The directory that contains the term-to-concept index, which is created by {@code indexing()} or in a similar fashion.
* @param conceptTermIndexDirectory The directory that shall contain the concept-term index.
* @throws IOException
*/
static void createConceptTermIndex(File termDocIndexDirectory, File conceptTermIndexDirectory) throws IOException {
ExecutorService es = Executors.newFixedThreadPool(2);
final Directory termDocDirectory = FSDirectory.open(termDocIndexDirectory);
final IndexReader termDocReader = IndexReader.open(termDocDirectory);
final IndexSearcher docSearcher = new IndexSearcher(termDocReader);
Fields fields = MultiFields.getFields(termDocReader);
if (fields != null) {
Terms terms = fields.terms(WikiIndexer.TEXT_FIELD);
TermsEnum termsEnum = terms.iterator(null);
final IndexWriterConfig conceptIndexWriterConfig = new IndexWriterConfig(LUCENE_48, null);
try (IndexWriter conceptIndexWriter = new IndexWriter(FSDirectory.open(conceptTermIndexDirectory), conceptIndexWriterConfig)) {
int t = 0;
BytesRef bytesRef;
while ((bytesRef = termsEnum.next()) != null) {
String termString = bytesRef.utf8ToString();
if (termString.matches("^[a-zA-Z]+:/.*$") || termString.matches("^\\d+$")) {
continue;
}
if (termString.charAt(0) >= '0' && termString.charAt(0) <= '9') {
continue;
}
if (termString.contains(".") || termString.contains("_")) {
continue;
}
if (t++ == 1000) {
t = 0;
System.out.println(termString);
}
TopDocs td = SearchTerm(bytesRef, docSearcher);
// add the concepts to the token stream
byte[] payloadBytes = new byte[5];
ByteArrayDataOutput dataOutput = new ByteArrayDataOutput(payloadBytes);
CachingTokenStream pcTokenStream = new CachingTokenStream();
double norm = ConceptSimilarity.SIMILARITY_FACTOR;
int last = 0;
for(ScoreDoc scoreDoc : td.scoreDocs){
if(scoreDoc.score/norm < ConceptSimilarity.SIMILARITY_FACTOR ||
last>= 1.0f / ConceptSimilarity.SIMILARITY_FACTOR) break;
norm += scoreDoc.score * scoreDoc.score;
last++;
}
for (int i=0; i<last; i++) {
ScoreDoc scoreDoc = td.scoreDocs[i];
Document termDocDocument = termDocReader.document(scoreDoc.doc);
String concept = termDocDocument.get(WikiIndexer.TITLE_FIELD);
Token conceptToken = new Token(concept, i * 10, (i + 1) * 10, "CONCEPT");
// set similarity score as payload
int integerScore = (int) ((scoreDoc.score/norm)/ConceptSimilarity.SIMILARITY_FACTOR);
dataOutput.reset(payloadBytes);
dataOutput.writeVInt(integerScore);
BytesRef payloadBytesRef = new BytesRef(payloadBytes, 0, dataOutput.getPosition());
conceptToken.setPayload(payloadBytesRef);
pcTokenStream.produceToken(conceptToken);
}
Document conceptTermDocument = new Document();
AttributeSource attributeSource = termsEnum.attributes();
conceptTermDocument.add(new StringField(WikiIndexer.TEXT_FIELD, termString, Field.Store.YES));
conceptTermDocument.add(new TextField("concept", pcTokenStream));
conceptIndexWriter.addDocument(conceptTermDocument);
}
}
}
}
private static TopDocs SearchTerm(BytesRef bytesRef, IndexSearcher docSearcher) throws IOException {
Term term = new Term(WikiIndexer.TEXT_FIELD, bytesRef);
Query query = new TermQuery(term);
int n = 1000;
TopDocs td = docSearcher.search(query, n);
if (n < td.totalHits) {
n = td.totalHits;
td = docSearcher.search(query, n);
}
return td;
}
private static void searchForQuery(final QueryParser parser, final IndexSearcher searcher, final String queryString, final IndexReader indexReader) throws ParseException, IOException {
Query query = parser.parse(queryString);
TopDocs topDocs = searcher.search(query, 12);
System.out.println(String.format("%d hits voor \"%s\"", topDocs.totalHits, queryString));
for (ScoreDoc sd : topDocs.scoreDocs) {
System.out.println(String.format("doc %d score %.2f shardIndex %d title \"%s\"", sd.doc, sd.score, sd.shardIndex, indexReader.document(sd.doc).get(TITLE_FIELD)));
}
}
/**
* Creates a term to concept index from a Wikipedia article dump.
* @param termDocIndexDirectory The directory where the term to concept index must be created
* @param wikipediaDumpFile The Wikipedia dump file that must be read to create the index
* @param stopWords The words that are not used in the semantic analysis
* @throws IOException
*/
public static void indexing(File termDocIndexDirectory, File wikipediaDumpFile, CharArraySet stopWords) throws IOException {
try (Directory directory = FSDirectory.open(termDocIndexDirectory)) {
Analyzer analyzer = new WikiAnalyzer(LUCENE_48, stopWords);
try(WikiIndexer indexer = new WikiIndexer(analyzer, directory)){
indexer.parseXmlDump(wikipediaDumpFile);
}
}
}
}
| Zzzxh11/Query_Performance_Prediction | src/main/java/be/vanoosten/esa/Main.java | 2,651 | /*
String indexPath = String.join(File.separator, "D:", "Development", "esa", "nlwiki");
File wikipediaDumpFile = new File(String.join(File.separator, "D:", "Downloads", "nlwiki", "nlwiki-20140611-pages-articles-multistream.xml.bz2"));
String startTokens = "geheim anoniem auteur verhalen lezen schrijven wetenschappelijk artikel peer review";
*/ | block_comment | nl | package be.vanoosten.esa;
import static be.vanoosten.esa.WikiIndexer.TITLE_FIELD;
import be.vanoosten.esa.tools.*;
import java.io.File;
import java.io.IOException;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.core.StopAnalyzer;
import org.apache.lucene.analysis.util.CharArraySet;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.Fields;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.MultiFields;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.ByteArrayDataOutput;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.AttributeSource;
import org.apache.lucene.util.BytesRef;
import static org.apache.lucene.util.Version.LUCENE_48;
/**
*
* @author Philip van Oosten
*/
public class Main {
public static void main(String[] args) throws IOException, ParseException {
/*
String indexPath =<SUF>*/
WikiFactory factory = new EnwikiFactory();
File indexPath = factory.getIndexRootPath();
File wikipediaDumpFile = factory.getWikipediaDumpFile();
String startTokens = "secret anonymous author stories read write scientific article peer review";
CharArraySet stopWords = factory.getStopWords();
File termDocIndexDirectory = factory.getTermDocIndexDirectory();
File conceptTermIndexDirectory = factory.getConceptTermIndexDirectory();
// The following lines are commented, because they can take a looong time.
indexing(termDocIndexDirectory, wikipediaDumpFile, stopWords);
createConceptTermIndex(termDocIndexDirectory, conceptTermIndexDirectory);
// Analyzer analyzer = new WikiAnalyzer(LUCENE_48, stopWords);
//
// Vectorizer vectorizer = new Vectorizer(termDocIndexDirectory, analyzer);
//
// SemanticSimilarityTool s = new SemanticSimilarityTool(vectorizer);
//
// float similarity = s.findSemanticSimilarity("Barack_Obama", "Barack_Obama");
}
/**
* Creates a concept-term index from a term-to-concept index (a full text index of a Wikipedia dump).
* @param termDocIndexDirectory The directory that contains the term-to-concept index, which is created by {@code indexing()} or in a similar fashion.
* @param conceptTermIndexDirectory The directory that shall contain the concept-term index.
* @throws IOException
*/
static void createConceptTermIndex(File termDocIndexDirectory, File conceptTermIndexDirectory) throws IOException {
ExecutorService es = Executors.newFixedThreadPool(2);
final Directory termDocDirectory = FSDirectory.open(termDocIndexDirectory);
final IndexReader termDocReader = IndexReader.open(termDocDirectory);
final IndexSearcher docSearcher = new IndexSearcher(termDocReader);
Fields fields = MultiFields.getFields(termDocReader);
if (fields != null) {
Terms terms = fields.terms(WikiIndexer.TEXT_FIELD);
TermsEnum termsEnum = terms.iterator(null);
final IndexWriterConfig conceptIndexWriterConfig = new IndexWriterConfig(LUCENE_48, null);
try (IndexWriter conceptIndexWriter = new IndexWriter(FSDirectory.open(conceptTermIndexDirectory), conceptIndexWriterConfig)) {
int t = 0;
BytesRef bytesRef;
while ((bytesRef = termsEnum.next()) != null) {
String termString = bytesRef.utf8ToString();
if (termString.matches("^[a-zA-Z]+:/.*$") || termString.matches("^\\d+$")) {
continue;
}
if (termString.charAt(0) >= '0' && termString.charAt(0) <= '9') {
continue;
}
if (termString.contains(".") || termString.contains("_")) {
continue;
}
if (t++ == 1000) {
t = 0;
System.out.println(termString);
}
TopDocs td = SearchTerm(bytesRef, docSearcher);
// add the concepts to the token stream
byte[] payloadBytes = new byte[5];
ByteArrayDataOutput dataOutput = new ByteArrayDataOutput(payloadBytes);
CachingTokenStream pcTokenStream = new CachingTokenStream();
double norm = ConceptSimilarity.SIMILARITY_FACTOR;
int last = 0;
for(ScoreDoc scoreDoc : td.scoreDocs){
if(scoreDoc.score/norm < ConceptSimilarity.SIMILARITY_FACTOR ||
last>= 1.0f / ConceptSimilarity.SIMILARITY_FACTOR) break;
norm += scoreDoc.score * scoreDoc.score;
last++;
}
for (int i=0; i<last; i++) {
ScoreDoc scoreDoc = td.scoreDocs[i];
Document termDocDocument = termDocReader.document(scoreDoc.doc);
String concept = termDocDocument.get(WikiIndexer.TITLE_FIELD);
Token conceptToken = new Token(concept, i * 10, (i + 1) * 10, "CONCEPT");
// set similarity score as payload
int integerScore = (int) ((scoreDoc.score/norm)/ConceptSimilarity.SIMILARITY_FACTOR);
dataOutput.reset(payloadBytes);
dataOutput.writeVInt(integerScore);
BytesRef payloadBytesRef = new BytesRef(payloadBytes, 0, dataOutput.getPosition());
conceptToken.setPayload(payloadBytesRef);
pcTokenStream.produceToken(conceptToken);
}
Document conceptTermDocument = new Document();
AttributeSource attributeSource = termsEnum.attributes();
conceptTermDocument.add(new StringField(WikiIndexer.TEXT_FIELD, termString, Field.Store.YES));
conceptTermDocument.add(new TextField("concept", pcTokenStream));
conceptIndexWriter.addDocument(conceptTermDocument);
}
}
}
}
private static TopDocs SearchTerm(BytesRef bytesRef, IndexSearcher docSearcher) throws IOException {
Term term = new Term(WikiIndexer.TEXT_FIELD, bytesRef);
Query query = new TermQuery(term);
int n = 1000;
TopDocs td = docSearcher.search(query, n);
if (n < td.totalHits) {
n = td.totalHits;
td = docSearcher.search(query, n);
}
return td;
}
private static void searchForQuery(final QueryParser parser, final IndexSearcher searcher, final String queryString, final IndexReader indexReader) throws ParseException, IOException {
Query query = parser.parse(queryString);
TopDocs topDocs = searcher.search(query, 12);
System.out.println(String.format("%d hits voor \"%s\"", topDocs.totalHits, queryString));
for (ScoreDoc sd : topDocs.scoreDocs) {
System.out.println(String.format("doc %d score %.2f shardIndex %d title \"%s\"", sd.doc, sd.score, sd.shardIndex, indexReader.document(sd.doc).get(TITLE_FIELD)));
}
}
/**
* Creates a term to concept index from a Wikipedia article dump.
* @param termDocIndexDirectory The directory where the term to concept index must be created
* @param wikipediaDumpFile The Wikipedia dump file that must be read to create the index
* @param stopWords The words that are not used in the semantic analysis
* @throws IOException
*/
public static void indexing(File termDocIndexDirectory, File wikipediaDumpFile, CharArraySet stopWords) throws IOException {
try (Directory directory = FSDirectory.open(termDocIndexDirectory)) {
Analyzer analyzer = new WikiAnalyzer(LUCENE_48, stopWords);
try(WikiIndexer indexer = new WikiIndexer(analyzer, directory)){
indexer.parseXmlDump(wikipediaDumpFile);
}
}
}
}
| False | 1,909 | 98 | 2,218 | 116 | 2,288 | 105 | 2,217 | 116 | 2,646 | 125 | false | false | false | false | false | true |
1,913 | 112369_1 | package class5;
public class Student {
private String name;
Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void speak() {
System.out.println(name + " is speaking");
}
public static void main(String args[]) {
Student anjali = new Student("Anjali");
anjali.speak();
Student yidan = new Student("Yidan");
yidan.speak();
Student tina = new Student("Tina");
// anjali.name = "Tina";
anjali.speak();
Professor siva = new Professor();
siva.makeStudentSpeak(tina);
siva.makeStudentSpeak(tina);
siva.makeStudentSpeak(yidan);
siva.makeStudentSpeak(yidan);
}
}
class Professor {
void makeStudentSpeak(Student student) {
System.out.println("Professor is asking " + student.getName() + " to speak");
student.speak();
//student.name = "Deepika";
}
}
| Yafei18/2020fall-info5100 | src/class5/Student.java | 330 | //student.name = "Deepika"; | line_comment | nl | package class5;
public class Student {
private String name;
Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void speak() {
System.out.println(name + " is speaking");
}
public static void main(String args[]) {
Student anjali = new Student("Anjali");
anjali.speak();
Student yidan = new Student("Yidan");
yidan.speak();
Student tina = new Student("Tina");
// anjali.name = "Tina";
anjali.speak();
Professor siva = new Professor();
siva.makeStudentSpeak(tina);
siva.makeStudentSpeak(tina);
siva.makeStudentSpeak(yidan);
siva.makeStudentSpeak(yidan);
}
}
class Professor {
void makeStudentSpeak(Student student) {
System.out.println("Professor is asking " + student.getName() + " to speak");
student.speak();
//student.name =<SUF>
}
}
| False | 243 | 8 | 315 | 9 | 287 | 9 | 315 | 9 | 348 | 10 | false | false | false | false | false | true |
1,225 | 118161_2 | package GUI.monitoring;
import java.net.InetAddress;
import java.net.Socket;
import java.sql.*;
import javax.swing.*;
import javax.swing.table.*;
import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
public class DatabaseTableModel extends AbstractTableModel{
private JDialog jDialog;
private ResultSet resultSet;
private String ip;
int timeoutSeconds = 3;
boolean reachable = true;
private Object[][] data = {};
private String[] columnNames = {"Hostnaam", "cpu load", "Totale opslag", "Gebruikte opslag", "vrije opslag", "uptime", "beschikbaar"};
public DatabaseTableModel(JDialog jDialog) {
this.jDialog = jDialog;
}
public void tableModel(){
try {
Thread executionThread = new Thread(()-> {
try (Connection connection = DriverManager.getConnection("jdbc:mysql://192.168.3.2:3306/monitoring", "HAProxy", "ICTM2O2!#gangsters");
Statement statement = connection.createStatement()) {
statement.setQueryTimeout(timeoutSeconds);
resultSet = statement.executeQuery("SELECT * FROM componenten");
List<Object[]> rows = new ArrayList<>();
while (resultSet.next()) {
Object[] row = new Object[columnNames.length];
row[0] = resultSet.getString("hostnaam");
row[1] = resultSet.getDouble("cpu_load");
row[2] = (resultSet.getDouble("disk_total") / Math.pow(1024, 3));
row[3] = (resultSet.getDouble("disk_used") / Math.pow(1024, 3));
row[4] = (resultSet.getDouble("disk_free") / Math.pow(1024, 3));
row[5] = (resultSet.getDouble("uptime") / 3600);
String server = resultSet.getString("server");
ip = resultSet.getString("ipadres");
if (server.equals("webserver")){
boolean isAvailable = checkWebserverAvailability(ip, 80);
row[6] = isAvailable ? "Yes" : "No"; // Set "beschikbaar" column value
} else if (server.equals("database")) {
boolean isAvailable = checkDatabaseserverAvailability(ip, 3306);
row[6] = isAvailable ? "Yes" : "No"; // Set "beschikbaar" column value
}
rows.add(row);
}
data = rows.toArray(new Object[0][]);
reachable = true;
fireTableDataChanged();
} catch (SQLException e) {
reachable = false;
e.printStackTrace();
}
});
executionThread.start();
executionThread.join(timeoutSeconds * 1000);
if (executionThread.isAlive()){
executionThread.interrupt();
JOptionPane.showMessageDialog(jDialog, "Databaseserver niet bereikbaar!", "Fout", JOptionPane.ERROR_MESSAGE);
reachable = false;
}
} catch (Exception e) {
reachable = false;
}
}
@Override
public int getRowCount() {
return data.length;
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public String getColumnName(int columnIndex) {
return columnNames[columnIndex];
}
@Override
public Class<?> getColumnClass(int columnIndex) {
if (getRowCount() > 0) {
return getValueAt(0, columnIndex).getClass();
}
return Object.class;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Object value = data[rowIndex][columnIndex];
if (value == null) {
return "";
} else {
return value;
}
}
@Override
public void setValueAt(Object value, int rowIndex, int columnIndex) {
data[rowIndex][columnIndex] = value;
fireTableCellUpdated(rowIndex, columnIndex);
}
public boolean checkWebserverAvailability(String ipAddress, int port){
try {
InetAddress inetAddress = InetAddress.getByName(ipAddress);
Socket socket = new Socket(inetAddress, port);
socket.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public boolean checkDatabaseserverAvailability(String ipAddress, int port) throws SQLException {
try{
InetAddress inetAddress = InetAddress.getByName(ipAddress);
Socket socket = new Socket(inetAddress, port);
socket.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean checkFirewallAvailability(String ipAddress, int port){
try{
InetAddress inetAddress = InetAddress.getByName(ipAddress);
Socket socket = new Socket(inetAddress, port);
socket.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean getReachable(){
return this.reachable;
}
}
| Obi-TwoKenobi/MonitoringsApplicatie | src/GUI/monitoring/DatabaseTableModel.java | 1,443 | // Set "beschikbaar" column value | line_comment | nl | package GUI.monitoring;
import java.net.InetAddress;
import java.net.Socket;
import java.sql.*;
import javax.swing.*;
import javax.swing.table.*;
import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
public class DatabaseTableModel extends AbstractTableModel{
private JDialog jDialog;
private ResultSet resultSet;
private String ip;
int timeoutSeconds = 3;
boolean reachable = true;
private Object[][] data = {};
private String[] columnNames = {"Hostnaam", "cpu load", "Totale opslag", "Gebruikte opslag", "vrije opslag", "uptime", "beschikbaar"};
public DatabaseTableModel(JDialog jDialog) {
this.jDialog = jDialog;
}
public void tableModel(){
try {
Thread executionThread = new Thread(()-> {
try (Connection connection = DriverManager.getConnection("jdbc:mysql://192.168.3.2:3306/monitoring", "HAProxy", "ICTM2O2!#gangsters");
Statement statement = connection.createStatement()) {
statement.setQueryTimeout(timeoutSeconds);
resultSet = statement.executeQuery("SELECT * FROM componenten");
List<Object[]> rows = new ArrayList<>();
while (resultSet.next()) {
Object[] row = new Object[columnNames.length];
row[0] = resultSet.getString("hostnaam");
row[1] = resultSet.getDouble("cpu_load");
row[2] = (resultSet.getDouble("disk_total") / Math.pow(1024, 3));
row[3] = (resultSet.getDouble("disk_used") / Math.pow(1024, 3));
row[4] = (resultSet.getDouble("disk_free") / Math.pow(1024, 3));
row[5] = (resultSet.getDouble("uptime") / 3600);
String server = resultSet.getString("server");
ip = resultSet.getString("ipadres");
if (server.equals("webserver")){
boolean isAvailable = checkWebserverAvailability(ip, 80);
row[6] = isAvailable ? "Yes" : "No"; // Set "beschikbaar" column value
} else if (server.equals("database")) {
boolean isAvailable = checkDatabaseserverAvailability(ip, 3306);
row[6] = isAvailable ? "Yes" : "No"; // Set "beschikbaar"<SUF>
}
rows.add(row);
}
data = rows.toArray(new Object[0][]);
reachable = true;
fireTableDataChanged();
} catch (SQLException e) {
reachable = false;
e.printStackTrace();
}
});
executionThread.start();
executionThread.join(timeoutSeconds * 1000);
if (executionThread.isAlive()){
executionThread.interrupt();
JOptionPane.showMessageDialog(jDialog, "Databaseserver niet bereikbaar!", "Fout", JOptionPane.ERROR_MESSAGE);
reachable = false;
}
} catch (Exception e) {
reachable = false;
}
}
@Override
public int getRowCount() {
return data.length;
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public String getColumnName(int columnIndex) {
return columnNames[columnIndex];
}
@Override
public Class<?> getColumnClass(int columnIndex) {
if (getRowCount() > 0) {
return getValueAt(0, columnIndex).getClass();
}
return Object.class;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Object value = data[rowIndex][columnIndex];
if (value == null) {
return "";
} else {
return value;
}
}
@Override
public void setValueAt(Object value, int rowIndex, int columnIndex) {
data[rowIndex][columnIndex] = value;
fireTableCellUpdated(rowIndex, columnIndex);
}
public boolean checkWebserverAvailability(String ipAddress, int port){
try {
InetAddress inetAddress = InetAddress.getByName(ipAddress);
Socket socket = new Socket(inetAddress, port);
socket.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public boolean checkDatabaseserverAvailability(String ipAddress, int port) throws SQLException {
try{
InetAddress inetAddress = InetAddress.getByName(ipAddress);
Socket socket = new Socket(inetAddress, port);
socket.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean checkFirewallAvailability(String ipAddress, int port){
try{
InetAddress inetAddress = InetAddress.getByName(ipAddress);
Socket socket = new Socket(inetAddress, port);
socket.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean getReachable(){
return this.reachable;
}
}
| True | 1,068 | 9 | 1,161 | 11 | 1,257 | 8 | 1,161 | 11 | 1,441 | 10 | false | false | false | false | false | true |
2,701 | 99656_1 | package com.rolfje.anonimatron.anonymizer;
import java.security.SecureRandom;
import org.apache.log4j.Logger;
import com.rolfje.anonimatron.synonyms.StringSynonym;
import com.rolfje.anonimatron.synonyms.Synonym;
/**
* Generates valid Dutch Bank Account number with the same length as the given
* number.
* <p>
* A Dutch Bank Account Number is passes the "11 proof" if it is 9 digits long.
* If it is less than 9 digits, there is no way to check the validity of the
* number.
* <p>
* See http://nl.wikipedia.org/wiki/Elfproef
*/
public class DutchBankAccountAnononymizer extends AbstractElevenProofAnonymizer implements BankAccountAnonymizer {
private static Logger LOG = Logger.getLogger(DutchBankAccountAnononymizer.class);
private static int LENGTH = 9;
private final SecureRandom random = new SecureRandom();
@Override
public String getType() {
return "DUTCHBANKACCOUNT";
}
@Override
public Synonym anonymize(Object from, int size) {
if (size < LENGTH) {
throw new UnsupportedOperationException(
"Can not generate a Dutch Bank Account number that fits in a " + size + " character string. Must be " + LENGTH
+ " characters or more.");
}
int originalLength = ((String) from).length();
if (originalLength > LENGTH) {
LOG.warn("Original bank account number had more than " + LENGTH
+ " digits. The resulting anonymous bank account number with the same length will not be a valid account number.");
}
StringSynonym s = new StringSynonym();
s.setType(getType());
s.setFrom(from);
do {
// Never generate identical number
s.setTo(generateBankAccount(originalLength));
} while (s.getFrom().equals(s.getTo()));
return s;
}
@Override
public String generateBankAccount(int numberOfDigits) {
if (numberOfDigits == LENGTH) {
// Generate 11-proof bank account number
int[] elevenProof = generate11ProofNumber(numberOfDigits);
return digitsAsNumber(elevenProof);
} else {
// Generate non-11 proof bank account number
int[] randomnumber = getRandomDigits(numberOfDigits);
return digitsAsNumber(randomnumber);
}
}
@Override
public String generateBankCode() {
DutchBankCode bankCode = DutchBankCode.values()[random.nextInt(DutchBankCode.values().length)];
return bankCode.bankCode;
}
/**
* Enumeration of the Dutch bank codes, used to generate valid IBAN for Dutch bank accounts.
*
* @see <a href="Bank Identifier Codes">https://www.betaalvereniging.nl/aandachtsgebieden/giraal-betalingsverkeer/bic-sepa-transacties/</a>
*/
private enum DutchBankCode {
ABNA("ABNANL2A", "ABNA", "ABN AMRO"),
FTSB("ABNANL2A", "FTSB", "ABN AMRO (ex FORTIS)"),
ADYB("ADYBNL2A", "ADYB", "ADYEN"),
AEGO("AEGONL2U", "AEGO", "AEGON BANK"),
ANAA("ANAANL21", "ANAA", "BRAND NEW DAY (ex ALLIANZ)"),
ANDL("ANDLNL2A", "ANDL", "ANADOLUBANK"),
ARBN("ARBNNL22", "ARBN", "ACHMEA BANK"),
ARSN("ARSNNL21", "ARSN", "ARGENTA SPAARBANK"),
ASNB("ASNBNL21", "ASNB", "ASN BANK"),
ATBA("ATBANL2A", "ATBA", "AMSTERDAM TRADE BANK"),
BCDM("BCDMNL22", "BCDM", "BANQUE CHAABI DU MAROC"),
BCIT("BCITNL2A", "BCIT", "INTESA SANPAOLO"),
BICK("BICKNL2A", "BICK", "BINCKBANK"),
BINK("BINKNL21", "BINK", "BINCKBANK, PROF"),
BKCH("BKCHNL2R", "BKCH", "BANK OF CHINA"),
BKMG("BKMGNL2A", "BKMG", "BANK MENDES GANS"),
BLGW("BLGWNL21", "BLGW", "BLG WONEN"),
BMEU("BMEUNL21", "BMEU", "BMCE EUROSERVICES"),
BNDA("BNDANL2A", "BNDA", "BRAND NEW DAY BANK"),
BNGH("BNGHNL2G", "BNGH", "BANK NEDERLANDSE GEMEENTEN"),
BNPA("BNPANL2A", "BNPA", "BNP PARIBAS"),
BOFA("BOFANLNX", "BOFA", "BANK OF AMERICA"),
BOFS("BOFSNL21002", "BOFS", "BANK OF SCOTLAND, AMSTERDAM"),
BOTK("BOTKNL2X", "BOTK", "MUFG BANK"),
BUNQ("BUNQNL2A", "BUNQ", "BUNQ"),
CHAS("CHASNL2X", "CHAS", "JPMORGAN CHASE"),
CITC("CITCNL2A", "CITC", "CITCO BANK"),
CITI("CITINL2X", "CITI", "CITIBANK INTERNATIONAL"),
COBA("COBANL2X", "COBA", "COMMERZBANK"),
DEUT("DEUTNL2A", "DEUT", "DEUTSCHE BANK (bij alle SEPA transacties)"),
DHBN("DHBNNL2R", "DHBN", "DEMIR-HALK BANK"),
DLBK("DLBKNL2A", "DLBK", "DELTA LLOYD BANK"),
DNIB("DNIBNL2G", "DNIB", "NIBC"),
EBUR("EBURNL21", "EBUR", "EBURY NETHERLANDS"),
FBHL("FBHLNL2A", "FBHL", "CREDIT EUROPE BANK"),
FLOR("FLORNL2A", "FLOR", "DE NEDERLANDSCHE BANK"),
FRGH("FRGHNL21", "FRGH", "FGH BANK"),
FRNX("FRNXNL2A", "FRNX", "FRANX"),
FVLB("FVLBNL22", "FVLB", "VAN LANSCHOT"),
GILL("GILLNL2A", "GILL", "INSINGERGILISSEN"),
HAND("HANDNL2A", "HAND", "SVENSKA HANDELSBANKEN"),
HHBA("HHBANL22", "HHBA", "HOF HOORNEMAN BANKIERS"),
HSBC("HSBCNL2A", "HSBC", "HSBC BANK"),
ICBK("ICBKNL2A", "ICBK", "INDUSTRIAL & COMMERCIAL BANK OF CHINA"),
INGB("INGBNL2A", "INGB", "ING"),
ISAE("ISAENL2A", "ISAE", "CACEIS BANK, Netherlands Branch"),
ISBK("ISBKNL2A", "ISBK", "ISBANK"),
KABA("KABANL2A", "KABA", "YAPI KREDI BANK"),
KASA("KASANL2A", "KASA", "KAS BANK"),
KNAB("KNABNL2H", "KNAB", "KNAB"),
KOEX("KOEXNL2A", "KOEX", "KOREA EXCHANGE BANK"),
KRED("KREDNL2X", "KRED", "KBC BANK"),
LOCY("LOCYNL2A", "LOCY", "LOMBARD ODIER DARIER HENTSCH & CIE"),
LOYD("LOYDNL2A", "LOYD", "LLOYDS TSB BANK"),
LPLN("LPLNNL2F", "LPLN", "LEASEPLAN CORPORATION"),
MHCB("MHCBNL2A", "MHCB", "MIZUHO BANK EUROPE"),
MOYO("MOYONL21", "MOYO", "MONEYOU"),
NNBA("NNBANL2G", "NNBA", "NATIONALE-NEDERLANDEN BANK"),
NWAB("NWABNL2G", "NWAB", "NEDERLANDSE WATERSCHAPSBANK"),
PCBC("PCBCNL2A", "PCBC", "CHINA CONSTRUCTION BANK, AMSTERDAM BRANCH"),
RABO("RABONL2U", "RABO", "RABOBANK"),
RBRB("RBRBNL21", "RBRB", "REGIOBANK"),
SOGE("SOGENL2A", "SOGE", "SOCIETE GENERALE"),
TEBU("TEBUNL2A", "TEBU", "THE ECONOMY BANK"),
TRIO("TRIONL2U", "TRIO", "TRIODOS BANK"),
UBSW("UBSWNL2A", "UBSW", "UBS EUROPE SE, NETHERLANDS BRANCH"),
UGBI("UGBINL2A", "UGBI", "GARANTIBANK INTERNATIONAL"),
VOWA("VOWANL21", "VOWA", "VOLKSWAGEN BANK"),
ZWLB("ZWLBNL21", "ZWLB", "SNS (ex ZWITSERLEVENBANK)");
private final String bic;
private final String bankCode;
private final String bankNaam;
DutchBankCode(String bic, String bankCode, String bankNaam) {
this.bic = bic;
this.bankCode = bankCode;
this.bankNaam = bankNaam;
}
}
}
| fbascheper/anonimatron | src/main/java/com/rolfje/anonimatron/anonymizer/DutchBankAccountAnononymizer.java | 2,692 | // Never generate identical number | line_comment | nl | package com.rolfje.anonimatron.anonymizer;
import java.security.SecureRandom;
import org.apache.log4j.Logger;
import com.rolfje.anonimatron.synonyms.StringSynonym;
import com.rolfje.anonimatron.synonyms.Synonym;
/**
* Generates valid Dutch Bank Account number with the same length as the given
* number.
* <p>
* A Dutch Bank Account Number is passes the "11 proof" if it is 9 digits long.
* If it is less than 9 digits, there is no way to check the validity of the
* number.
* <p>
* See http://nl.wikipedia.org/wiki/Elfproef
*/
public class DutchBankAccountAnononymizer extends AbstractElevenProofAnonymizer implements BankAccountAnonymizer {
private static Logger LOG = Logger.getLogger(DutchBankAccountAnononymizer.class);
private static int LENGTH = 9;
private final SecureRandom random = new SecureRandom();
@Override
public String getType() {
return "DUTCHBANKACCOUNT";
}
@Override
public Synonym anonymize(Object from, int size) {
if (size < LENGTH) {
throw new UnsupportedOperationException(
"Can not generate a Dutch Bank Account number that fits in a " + size + " character string. Must be " + LENGTH
+ " characters or more.");
}
int originalLength = ((String) from).length();
if (originalLength > LENGTH) {
LOG.warn("Original bank account number had more than " + LENGTH
+ " digits. The resulting anonymous bank account number with the same length will not be a valid account number.");
}
StringSynonym s = new StringSynonym();
s.setType(getType());
s.setFrom(from);
do {
// Never generate<SUF>
s.setTo(generateBankAccount(originalLength));
} while (s.getFrom().equals(s.getTo()));
return s;
}
@Override
public String generateBankAccount(int numberOfDigits) {
if (numberOfDigits == LENGTH) {
// Generate 11-proof bank account number
int[] elevenProof = generate11ProofNumber(numberOfDigits);
return digitsAsNumber(elevenProof);
} else {
// Generate non-11 proof bank account number
int[] randomnumber = getRandomDigits(numberOfDigits);
return digitsAsNumber(randomnumber);
}
}
@Override
public String generateBankCode() {
DutchBankCode bankCode = DutchBankCode.values()[random.nextInt(DutchBankCode.values().length)];
return bankCode.bankCode;
}
/**
* Enumeration of the Dutch bank codes, used to generate valid IBAN for Dutch bank accounts.
*
* @see <a href="Bank Identifier Codes">https://www.betaalvereniging.nl/aandachtsgebieden/giraal-betalingsverkeer/bic-sepa-transacties/</a>
*/
private enum DutchBankCode {
ABNA("ABNANL2A", "ABNA", "ABN AMRO"),
FTSB("ABNANL2A", "FTSB", "ABN AMRO (ex FORTIS)"),
ADYB("ADYBNL2A", "ADYB", "ADYEN"),
AEGO("AEGONL2U", "AEGO", "AEGON BANK"),
ANAA("ANAANL21", "ANAA", "BRAND NEW DAY (ex ALLIANZ)"),
ANDL("ANDLNL2A", "ANDL", "ANADOLUBANK"),
ARBN("ARBNNL22", "ARBN", "ACHMEA BANK"),
ARSN("ARSNNL21", "ARSN", "ARGENTA SPAARBANK"),
ASNB("ASNBNL21", "ASNB", "ASN BANK"),
ATBA("ATBANL2A", "ATBA", "AMSTERDAM TRADE BANK"),
BCDM("BCDMNL22", "BCDM", "BANQUE CHAABI DU MAROC"),
BCIT("BCITNL2A", "BCIT", "INTESA SANPAOLO"),
BICK("BICKNL2A", "BICK", "BINCKBANK"),
BINK("BINKNL21", "BINK", "BINCKBANK, PROF"),
BKCH("BKCHNL2R", "BKCH", "BANK OF CHINA"),
BKMG("BKMGNL2A", "BKMG", "BANK MENDES GANS"),
BLGW("BLGWNL21", "BLGW", "BLG WONEN"),
BMEU("BMEUNL21", "BMEU", "BMCE EUROSERVICES"),
BNDA("BNDANL2A", "BNDA", "BRAND NEW DAY BANK"),
BNGH("BNGHNL2G", "BNGH", "BANK NEDERLANDSE GEMEENTEN"),
BNPA("BNPANL2A", "BNPA", "BNP PARIBAS"),
BOFA("BOFANLNX", "BOFA", "BANK OF AMERICA"),
BOFS("BOFSNL21002", "BOFS", "BANK OF SCOTLAND, AMSTERDAM"),
BOTK("BOTKNL2X", "BOTK", "MUFG BANK"),
BUNQ("BUNQNL2A", "BUNQ", "BUNQ"),
CHAS("CHASNL2X", "CHAS", "JPMORGAN CHASE"),
CITC("CITCNL2A", "CITC", "CITCO BANK"),
CITI("CITINL2X", "CITI", "CITIBANK INTERNATIONAL"),
COBA("COBANL2X", "COBA", "COMMERZBANK"),
DEUT("DEUTNL2A", "DEUT", "DEUTSCHE BANK (bij alle SEPA transacties)"),
DHBN("DHBNNL2R", "DHBN", "DEMIR-HALK BANK"),
DLBK("DLBKNL2A", "DLBK", "DELTA LLOYD BANK"),
DNIB("DNIBNL2G", "DNIB", "NIBC"),
EBUR("EBURNL21", "EBUR", "EBURY NETHERLANDS"),
FBHL("FBHLNL2A", "FBHL", "CREDIT EUROPE BANK"),
FLOR("FLORNL2A", "FLOR", "DE NEDERLANDSCHE BANK"),
FRGH("FRGHNL21", "FRGH", "FGH BANK"),
FRNX("FRNXNL2A", "FRNX", "FRANX"),
FVLB("FVLBNL22", "FVLB", "VAN LANSCHOT"),
GILL("GILLNL2A", "GILL", "INSINGERGILISSEN"),
HAND("HANDNL2A", "HAND", "SVENSKA HANDELSBANKEN"),
HHBA("HHBANL22", "HHBA", "HOF HOORNEMAN BANKIERS"),
HSBC("HSBCNL2A", "HSBC", "HSBC BANK"),
ICBK("ICBKNL2A", "ICBK", "INDUSTRIAL & COMMERCIAL BANK OF CHINA"),
INGB("INGBNL2A", "INGB", "ING"),
ISAE("ISAENL2A", "ISAE", "CACEIS BANK, Netherlands Branch"),
ISBK("ISBKNL2A", "ISBK", "ISBANK"),
KABA("KABANL2A", "KABA", "YAPI KREDI BANK"),
KASA("KASANL2A", "KASA", "KAS BANK"),
KNAB("KNABNL2H", "KNAB", "KNAB"),
KOEX("KOEXNL2A", "KOEX", "KOREA EXCHANGE BANK"),
KRED("KREDNL2X", "KRED", "KBC BANK"),
LOCY("LOCYNL2A", "LOCY", "LOMBARD ODIER DARIER HENTSCH & CIE"),
LOYD("LOYDNL2A", "LOYD", "LLOYDS TSB BANK"),
LPLN("LPLNNL2F", "LPLN", "LEASEPLAN CORPORATION"),
MHCB("MHCBNL2A", "MHCB", "MIZUHO BANK EUROPE"),
MOYO("MOYONL21", "MOYO", "MONEYOU"),
NNBA("NNBANL2G", "NNBA", "NATIONALE-NEDERLANDEN BANK"),
NWAB("NWABNL2G", "NWAB", "NEDERLANDSE WATERSCHAPSBANK"),
PCBC("PCBCNL2A", "PCBC", "CHINA CONSTRUCTION BANK, AMSTERDAM BRANCH"),
RABO("RABONL2U", "RABO", "RABOBANK"),
RBRB("RBRBNL21", "RBRB", "REGIOBANK"),
SOGE("SOGENL2A", "SOGE", "SOCIETE GENERALE"),
TEBU("TEBUNL2A", "TEBU", "THE ECONOMY BANK"),
TRIO("TRIONL2U", "TRIO", "TRIODOS BANK"),
UBSW("UBSWNL2A", "UBSW", "UBS EUROPE SE, NETHERLANDS BRANCH"),
UGBI("UGBINL2A", "UGBI", "GARANTIBANK INTERNATIONAL"),
VOWA("VOWANL21", "VOWA", "VOLKSWAGEN BANK"),
ZWLB("ZWLBNL21", "ZWLB", "SNS (ex ZWITSERLEVENBANK)");
private final String bic;
private final String bankCode;
private final String bankNaam;
DutchBankCode(String bic, String bankCode, String bankNaam) {
this.bic = bic;
this.bankCode = bankCode;
this.bankNaam = bankNaam;
}
}
}
| False | 2,340 | 5 | 2,526 | 5 | 2,289 | 5 | 2,526 | 5 | 3,025 | 5 | false | false | false | false | false | true |
2,928 | 179161_0 | package io.github.biezhi.jedis;
import redis.clients.jedis.Jedis;
import java.util.List;
/**
* Redis mget 操作
*
* @author biezhi
* @date 2018/1/19
*/
public class MGetExample {
public static void main(String[] args) {
try (Jedis jedis = JedisUtil.getInstance().getJedis()) {
jedis.rpush("ids", "aa");
jedis.rpush("ids", "bb");
jedis.rpush("ids", "cc");
List<String> ids = jedis.lrange("ids", 0, -1);
jedis.set("aa", "{'name':'zhoujie','age':20}");
jedis.set("bb", "{'name':'yilin','age':28}");
jedis.set("cc", "{'name':'lucy','age':21}");
List<String> list = jedis.mget(ids.toArray(new String[ids.size()]));
System.out.println(list);
}
}
}
| hellokaton/java-library-examples | cache-example/jedis-example/src/main/java/io/github/biezhi/jedis/MGetExample.java | 295 | /**
* Redis mget 操作
*
* @author biezhi
* @date 2018/1/19
*/ | block_comment | nl | package io.github.biezhi.jedis;
import redis.clients.jedis.Jedis;
import java.util.List;
/**
* Redis mget 操作<SUF>*/
public class MGetExample {
public static void main(String[] args) {
try (Jedis jedis = JedisUtil.getInstance().getJedis()) {
jedis.rpush("ids", "aa");
jedis.rpush("ids", "bb");
jedis.rpush("ids", "cc");
List<String> ids = jedis.lrange("ids", 0, -1);
jedis.set("aa", "{'name':'zhoujie','age':20}");
jedis.set("bb", "{'name':'yilin','age':28}");
jedis.set("cc", "{'name':'lucy','age':21}");
List<String> list = jedis.mget(ids.toArray(new String[ids.size()]));
System.out.println(list);
}
}
}
| False | 219 | 31 | 267 | 33 | 256 | 31 | 267 | 33 | 296 | 35 | false | false | false | false | false | true |
1,740 | 724_9 | package tillerino.tillerinobot.lang;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import org.tillerino.osuApiModel.Mods;
import org.tillerino.osuApiModel.OsuApiUser;
import org.tillerino.ppaddict.chat.GameChatResponse;
import org.tillerino.ppaddict.chat.GameChatResponse.Action;
import org.tillerino.ppaddict.chat.GameChatResponse.Message;
/**
* Dutch language implementation by https://osu.ppy.sh/u/PudiPudi and https://github.com/notadecent and https://osu.ppy.sh/u/2756335
*/
public class Nederlands extends AbstractMutableLanguage {
@Override
public String unknownBeatmap() {
return "Het spijt me, ik ken die map niet. Hij kan gloednieuw zijn, heel erg moeilijk of hij is niet voor osu standard mode.";
}
@Override
public String internalException(String marker) {
return "Ugh... Lijkt er op dat Tillerino een oelewapper is geweest en mijn bedrading kapot heeft gemaakt."
+ " Als hij het zelf niet merkt, kan je hem dan [https://github.com/Tillerino/Tillerinobot/wiki/Contact op de hoogte stellen]? (reference "
+ marker + ")";
}
@Override
public String externalException(String marker) {
return "Wat gebeurt er? Ik krijg alleen maar onzin van de osu server. Kan je me vertellen wat dit betekent? 00111010 01011110 00101001"
+ " De menselijke Tillerino zegt dat we ons er geen zorgen over hoeven te maken en dat we het opnieuw moeten proberen."
+ " Als je je heel erg zorgen maakt hierover, kan je het aan Tillerino [https://github.com/Tillerino/Tillerinobot/wiki/Contact vertellen]. (reference "
+ marker + ")";
}
@Override
public String noInformationForModsShort() {
return "Geen informatie beschikbaar voor opgevraagde mods";
}
@Override
public GameChatResponse welcomeUser(OsuApiUser apiUser, long inactiveTime) {
if(inactiveTime < 60 * 1000) {
return new Message("beep boop");
} else if(inactiveTime < 24 * 60 * 60 * 1000) {
return new Message("Welkom terug, " + apiUser.getUserName() + ".");
} else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) {
return new Message(apiUser.getUserName() + "...")
.then(new Message("...ben jij dat? Dat is lang geleden!"))
.then(new Message("Het is goed om je weer te zien. Kan ik je wellicht een recommandatie geven?"));
} else {
String[] messages = {
"jij ziet er uit alsof je een recommandatie wilt.",
"leuk om je te zien! :)",
"mijn favoriete mens. (Vertel het niet aan de andere mensen!)",
"wat een leuke verrassing! ^.^",
"Ik hoopte al dat je op kwam dagen. Al die andere mensen zijn saai, maar vertel ze niet dat ik dat zei! :3",
"waar heb je zin in vandaag?",
};
String message = messages[ThreadLocalRandom.current().nextInt(messages.length)];
return new Message(apiUser.getUserName() + ", " + message);
}
}
@Override
public String unknownCommand(String command) {
return "Ik snap niet helemaal wat je bedoelt met \"" + command
+ "\". Typ !help als je hulp nodig hebt!";
}
@Override
public String noInformationForMods() {
return "Sorry, ik kan je op het moment geen informatie geven over die mods.";
}
@Override
public String malformattedMods(String mods) {
return "Die mods zien er niet goed uit. Mods kunnen elke combinatie zijn van DT HR HD HT EZ NC FL SO NF. Combineer ze zonder spaties of speciale tekens, bijvoorbeeld: '!with HDHR' of '!with DTEZ'";
}
@Override
public String noLastSongInfo() {
return "Ik kan me niet herinneren dat je al een map had opgevraagd...";
}
@Override
public String tryWithMods() {
return "Probeer deze map met wat mods!";
}
@Override
public String tryWithMods(List<Mods> mods) {
return "Probeer deze map eens met " + Mods.toShortNamesContinuous(mods);
}
@Override
public String excuseForError() {
return "Het spijt me, een prachtige rij van enen en nullen kwam langs en dat leidde me af. Wat wou je ook al weer?";
}
@Override
public String complaint() {
return "Je klacht is ingediend. Tillerino zal er naar kijken als hij tijd heeft.";
}
@Override
public GameChatResponse hug(OsuApiUser apiUser) {
return new Message("Kom eens hier jij!")
.then(new Action("knuffelt " + apiUser.getUserName()));
}
@Override
public String help() {
return "Hallo! Ik ben de robot die Tillerino heeft gedood en zijn account heeft overgenomen! Grapje, maar ik gebruik wel zijn account."
+ " Check https://twitter.com/Tillerinobot voor status en updates!"
+ " Zie https://github.com/Tillerino/Tillerinobot/wiki voor commandos!";
}
@Override
public String faq() {
return "Zie https://github.com/Tillerino/Tillerinobot/wiki/FAQ voor veelgestelde vragen!";
}
@Override
public String featureRankRestricted(String feature, int minRank, OsuApiUser user) {
return "Sorry, " + feature + " is op het moment alleen beschikbaar voor spelers boven rank " + minRank ;
}
@Override
public String mixedNomodAndMods() {
return "Hoe bedoel je, nomod met mods?";
}
@Override
public String outOfRecommendations() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do"
+ " Ik heb je alles wat ik me kan bedenken al aanbevolen]."
+ " Probeer andere aanbevelingsopties of gebruik !reset. Als je het niet zeker weet, check !help.";
}
@Override
public String notRanked() {
return "Lijkt erop dat die beatmap niet ranked is.";
}
@Override
public String invalidAccuracy(String acc) {
return "Ongeldige accuracy: \"" + acc + "\"";
}
@Override
public GameChatResponse optionalCommentOnLanguage(OsuApiUser apiUser) {
return new Message("PudiPudi heeft me geleerd Nederlands te spreken.");
}
@Override
public String invalidChoice(String invalid, String choices) {
return "Het spijt me, maar \"" + invalid
+ "\" werkt niet. Probeer deze: " + choices + "!";
}
@Override
public String setFormat() {
return "De syntax om een parameter in te stellen is '!set optie waarde'. Typ !help als je meer aanwijzingen nodig hebt.";
}
StringShuffler apiTimeoutShuffler = new StringShuffler(ThreadLocalRandom.current());
@Override
public String apiTimeoutException() {
registerModification();
final String message = "De osu! servers zijn nu heel erg traag, dus ik kan op dit moment niets voor je doen. ";
return message + apiTimeoutShuffler.get(
"Zeg... Wanneer heb je voor het laatst met je oma gesproken?",
"Wat dacht je ervan om je kamer eens op te ruimen en dan nog eens te proberen?",
"Ik weet zeker dat je vast erg zin hebt in een wandeling. Jeweetwel... daarbuiten?",
"Ik weet gewoon zeker dat er een helehoop andere dingen zijn die je nog moet doen. Wat dacht je ervan om ze nu te doen?",
"Je ziet eruit alsof je wel wat slaap kan gebruiken...",
"Maat moet je deze superinteressante pagina op [https://nl.wikipedia.org/wiki/Special:Random wikipedia] eens zien!",
"Laten we eens kijken of er een goed iemand aan het [http://www.twitch.tv/directory/game/Osu! streamen] is!",
"Kijk, hier is een ander [http://dagobah.net/flash/Cursor_Invisible.swf spel] waar je waarschijnlijk superslecht in bent!",
"Dit moet je tijd zat geven om [https://github.com/Tillerino/Tillerinobot/wiki mijn handleiding] te bestuderen.",
"Geen zorgen, met deze [https://www.reddit.com/r/osugame dank memes] kun je de tijd dooden.",
"Terwijl je je verveelt, probeer [http://gabrielecirulli.github.io/2048/ 2048] eens een keer!",
"Leuke vraag: Als je harde schijf op dit moment zou crashen, hoeveel van je persoonlijke gegevens ben je dan voor eeuwig kwijt?",
"Dus... Heb je wel eens de [https://www.google.nl/search?q=bring%20sally%20up%20push%20up%20challenge sally up push up challenge] geprobeerd?",
"Je kunt wat anders gaan doen of we kunnen elkaar in de ogen gaan staren. In stilte."
);
}
@Override
public String noRecentPlays() {
return "Ik heb je de afgelopen tijd niet zien spelen.";
}
@Override
public String isSetId() {
return "Dit refereerd naar een beatmap-verzameling in plaats van een beatmap zelf.";
}
}
| Tillerino/Tillerinobot | tillerinobot/src/main/java/tillerino/tillerinobot/lang/Nederlands.java | 2,664 | //github.com/Tillerino/Tillerinobot/wiki mijn handleiding] te bestuderen.", | line_comment | nl | package tillerino.tillerinobot.lang;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import org.tillerino.osuApiModel.Mods;
import org.tillerino.osuApiModel.OsuApiUser;
import org.tillerino.ppaddict.chat.GameChatResponse;
import org.tillerino.ppaddict.chat.GameChatResponse.Action;
import org.tillerino.ppaddict.chat.GameChatResponse.Message;
/**
* Dutch language implementation by https://osu.ppy.sh/u/PudiPudi and https://github.com/notadecent and https://osu.ppy.sh/u/2756335
*/
public class Nederlands extends AbstractMutableLanguage {
@Override
public String unknownBeatmap() {
return "Het spijt me, ik ken die map niet. Hij kan gloednieuw zijn, heel erg moeilijk of hij is niet voor osu standard mode.";
}
@Override
public String internalException(String marker) {
return "Ugh... Lijkt er op dat Tillerino een oelewapper is geweest en mijn bedrading kapot heeft gemaakt."
+ " Als hij het zelf niet merkt, kan je hem dan [https://github.com/Tillerino/Tillerinobot/wiki/Contact op de hoogte stellen]? (reference "
+ marker + ")";
}
@Override
public String externalException(String marker) {
return "Wat gebeurt er? Ik krijg alleen maar onzin van de osu server. Kan je me vertellen wat dit betekent? 00111010 01011110 00101001"
+ " De menselijke Tillerino zegt dat we ons er geen zorgen over hoeven te maken en dat we het opnieuw moeten proberen."
+ " Als je je heel erg zorgen maakt hierover, kan je het aan Tillerino [https://github.com/Tillerino/Tillerinobot/wiki/Contact vertellen]. (reference "
+ marker + ")";
}
@Override
public String noInformationForModsShort() {
return "Geen informatie beschikbaar voor opgevraagde mods";
}
@Override
public GameChatResponse welcomeUser(OsuApiUser apiUser, long inactiveTime) {
if(inactiveTime < 60 * 1000) {
return new Message("beep boop");
} else if(inactiveTime < 24 * 60 * 60 * 1000) {
return new Message("Welkom terug, " + apiUser.getUserName() + ".");
} else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) {
return new Message(apiUser.getUserName() + "...")
.then(new Message("...ben jij dat? Dat is lang geleden!"))
.then(new Message("Het is goed om je weer te zien. Kan ik je wellicht een recommandatie geven?"));
} else {
String[] messages = {
"jij ziet er uit alsof je een recommandatie wilt.",
"leuk om je te zien! :)",
"mijn favoriete mens. (Vertel het niet aan de andere mensen!)",
"wat een leuke verrassing! ^.^",
"Ik hoopte al dat je op kwam dagen. Al die andere mensen zijn saai, maar vertel ze niet dat ik dat zei! :3",
"waar heb je zin in vandaag?",
};
String message = messages[ThreadLocalRandom.current().nextInt(messages.length)];
return new Message(apiUser.getUserName() + ", " + message);
}
}
@Override
public String unknownCommand(String command) {
return "Ik snap niet helemaal wat je bedoelt met \"" + command
+ "\". Typ !help als je hulp nodig hebt!";
}
@Override
public String noInformationForMods() {
return "Sorry, ik kan je op het moment geen informatie geven over die mods.";
}
@Override
public String malformattedMods(String mods) {
return "Die mods zien er niet goed uit. Mods kunnen elke combinatie zijn van DT HR HD HT EZ NC FL SO NF. Combineer ze zonder spaties of speciale tekens, bijvoorbeeld: '!with HDHR' of '!with DTEZ'";
}
@Override
public String noLastSongInfo() {
return "Ik kan me niet herinneren dat je al een map had opgevraagd...";
}
@Override
public String tryWithMods() {
return "Probeer deze map met wat mods!";
}
@Override
public String tryWithMods(List<Mods> mods) {
return "Probeer deze map eens met " + Mods.toShortNamesContinuous(mods);
}
@Override
public String excuseForError() {
return "Het spijt me, een prachtige rij van enen en nullen kwam langs en dat leidde me af. Wat wou je ook al weer?";
}
@Override
public String complaint() {
return "Je klacht is ingediend. Tillerino zal er naar kijken als hij tijd heeft.";
}
@Override
public GameChatResponse hug(OsuApiUser apiUser) {
return new Message("Kom eens hier jij!")
.then(new Action("knuffelt " + apiUser.getUserName()));
}
@Override
public String help() {
return "Hallo! Ik ben de robot die Tillerino heeft gedood en zijn account heeft overgenomen! Grapje, maar ik gebruik wel zijn account."
+ " Check https://twitter.com/Tillerinobot voor status en updates!"
+ " Zie https://github.com/Tillerino/Tillerinobot/wiki voor commandos!";
}
@Override
public String faq() {
return "Zie https://github.com/Tillerino/Tillerinobot/wiki/FAQ voor veelgestelde vragen!";
}
@Override
public String featureRankRestricted(String feature, int minRank, OsuApiUser user) {
return "Sorry, " + feature + " is op het moment alleen beschikbaar voor spelers boven rank " + minRank ;
}
@Override
public String mixedNomodAndMods() {
return "Hoe bedoel je, nomod met mods?";
}
@Override
public String outOfRecommendations() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do"
+ " Ik heb je alles wat ik me kan bedenken al aanbevolen]."
+ " Probeer andere aanbevelingsopties of gebruik !reset. Als je het niet zeker weet, check !help.";
}
@Override
public String notRanked() {
return "Lijkt erop dat die beatmap niet ranked is.";
}
@Override
public String invalidAccuracy(String acc) {
return "Ongeldige accuracy: \"" + acc + "\"";
}
@Override
public GameChatResponse optionalCommentOnLanguage(OsuApiUser apiUser) {
return new Message("PudiPudi heeft me geleerd Nederlands te spreken.");
}
@Override
public String invalidChoice(String invalid, String choices) {
return "Het spijt me, maar \"" + invalid
+ "\" werkt niet. Probeer deze: " + choices + "!";
}
@Override
public String setFormat() {
return "De syntax om een parameter in te stellen is '!set optie waarde'. Typ !help als je meer aanwijzingen nodig hebt.";
}
StringShuffler apiTimeoutShuffler = new StringShuffler(ThreadLocalRandom.current());
@Override
public String apiTimeoutException() {
registerModification();
final String message = "De osu! servers zijn nu heel erg traag, dus ik kan op dit moment niets voor je doen. ";
return message + apiTimeoutShuffler.get(
"Zeg... Wanneer heb je voor het laatst met je oma gesproken?",
"Wat dacht je ervan om je kamer eens op te ruimen en dan nog eens te proberen?",
"Ik weet zeker dat je vast erg zin hebt in een wandeling. Jeweetwel... daarbuiten?",
"Ik weet gewoon zeker dat er een helehoop andere dingen zijn die je nog moet doen. Wat dacht je ervan om ze nu te doen?",
"Je ziet eruit alsof je wel wat slaap kan gebruiken...",
"Maat moet je deze superinteressante pagina op [https://nl.wikipedia.org/wiki/Special:Random wikipedia] eens zien!",
"Laten we eens kijken of er een goed iemand aan het [http://www.twitch.tv/directory/game/Osu! streamen] is!",
"Kijk, hier is een ander [http://dagobah.net/flash/Cursor_Invisible.swf spel] waar je waarschijnlijk superslecht in bent!",
"Dit moet je tijd zat geven om [https://github.com/Tillerino/Tillerinobot/wiki mijn<SUF>
"Geen zorgen, met deze [https://www.reddit.com/r/osugame dank memes] kun je de tijd dooden.",
"Terwijl je je verveelt, probeer [http://gabrielecirulli.github.io/2048/ 2048] eens een keer!",
"Leuke vraag: Als je harde schijf op dit moment zou crashen, hoeveel van je persoonlijke gegevens ben je dan voor eeuwig kwijt?",
"Dus... Heb je wel eens de [https://www.google.nl/search?q=bring%20sally%20up%20push%20up%20challenge sally up push up challenge] geprobeerd?",
"Je kunt wat anders gaan doen of we kunnen elkaar in de ogen gaan staren. In stilte."
);
}
@Override
public String noRecentPlays() {
return "Ik heb je de afgelopen tijd niet zien spelen.";
}
@Override
public String isSetId() {
return "Dit refereerd naar een beatmap-verzameling in plaats van een beatmap zelf.";
}
}
| False | 2,311 | 20 | 2,767 | 25 | 2,409 | 24 | 2,767 | 25 | 3,006 | 26 | false | false | false | false | false | true |
4,824 | 17524_1 | /*
* Copyright 2018 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.client.j2se;
import com.beust.jcommander.JCommander;
import org.junit.Assert;
import org.junit.Test;
import java.net.URI;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
/**
* Tests {@link DecodeWorker}.
*/
public final class DecodeWorkerTestCase extends Assert {
static final String IMAGE_DATA_URI =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACEAAAAhAQAAAAB/n//CAAAAkklEQVR42mP4DwQNDJjkB4" +
"E77A0M369N/d7A8CV6rjiQjPMFkWG1QPL7RVGg%2BAfREKCa/5/vA9V/nFSQ3sDwb7/KdiDJqX4dSH4pXN/A8DfyDVD2" +
"988HQPUfPVaqA0XKz%2BgD9bIk1AP1fgwvB7KlS9VBdqXbA82PT9AH2fiaH2SXGdDM71fDgeIfhIvKsbkTTAIAKYVr0N" +
"z5IloAAAAASUVORK5CYII=";
static final String IMAGE_NOBARCODE_DATA_URI =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAACE1BMVEUAAAAYsPIXsPL//+" +
"2J6/CI6vB74/Alt/IXr/LL/++M7PD//+UZsPIXr/ISrfIRrPIXsPIYsPIYsPIKqfIQrPITrvIZsfImt/IouPImt/IZsf" +
"IXr/IXsPIbsfIWr/IcsvInuPImuPIvvPJt3PB54vBt3PAasfIXsPIXr/IUrvIYsPIwvfJx3vB54vCE6PCS7/B64/Bt3P" +
"AktvIXr/IYsPIYsPIasfIlt/IwvPKJ6/CM7PCW8fCQ7vCB5vAmt/IXr/IYsPIYsPIXsPKI6vCI6vCI6vAYsfMYsPIYsP" +
"KI6vCI6vCI6vAYrO0YsPGI6vCI6vCI6vCJ6/CH6vBw3vB64/CE6PAwvPJr2/FLy/ESrfIYsPIjtvIasfIYsPIYsPIYsP" +
"IYsPIYsPIYsPIYsPIYsPIYre4vvPIktvJ64/Bx3vCI6vAitfJj1/F74/CH6vAbsfI7wvF/5fCJ6vAXsPJw3fAWmNEYre" +
"0mt/J85PCJ6/Bw3vAXqukYr/EYsPIZsPIwvPJ95PAjtvIVksgWmtQYre4VlMsXpuUVkccWl9AXquouu/Jy3/AWl88Wm9" +
"QXpuQYrO0ZsfIVkcgVlMwWmNAXqekVisIVkMcVkscWm9UTXaQVgr0VisMVlcwTT5oTVZ4TXKMVhL4TTpoTTZoTW6MVg7" +
"4Vj8YVicIVkMYVi8MUfbkTVZ8UfLkUY6gTVJ4Vg70TT5sTVp/hyCW0AAAAZnRSTlMAAAAAAAAAAAAAAAACGx8fHxsCAh" +
"k2yeTi4uLJMgEZNsnm++fi5s80GTbJ5v3NNhzJ4uCvFwHJ5v3mNgIbHx8cBDHN/ckZOcz+5jYC5f3k4Bzk/f3NMv7NNh" +
"0f/eTg4jYd/eQZ5v3GzkXBAAAByUlEQVQ4y73TvW4TQRSG4e/dtbHx2hv/FBEIEBWIEgmLhoaGittJRYeEfAUUFBS+Ai" +
"qIoIBQgGQRFKWwoAxgKYog3vXf2uvx7lAkBDvyio7TnkffnDOaQf8o/h/4C+06gOQB1oHgnEASosZZ9VYFQvLqp837vO" +
"NnsAqQdwXg3oeTI+DzOXDn8DLcZo8OdwF4vwqaZW4BXdiRrAPxuRkewE3gC7wxa+/hITfGlXkXdrQebJHkoLvICBBbJO" +
"PG+BsvlQEeAbAfZydccCI//jrMnOExxMDrWtYWT4iI/LiTtQYtGIsybwd7GLMOKB84UqUDrxbzNe+hJeNNY+F2AbYJlp" +
"r2BKQX6UvR1U/AbpP5aXebQLKipRIQxlJUknr8GYPdZu5FINGSpNSPRsVZcVhYyu+5H5vMxVMIJZHW+5VJ2UxiqTArep" +
"NZcXaUGIlnYAaS0sR1lG5O+X4tjiuWUT2yhXBW5DlwWA3PktPNo8RN8sZN3MT1RwFtrMO0FNaCoXzVDyTper8WVF17IO" +
"OWaUsLTDWsTfIyc+eXr6EuWS+oM/shX9CWhKmGeVPRtHxcMtqIbIqpOmNKAxnaS1/E+migDR3nJGnR0GDR+A23fMFDA8" +
"6WRQAAAABJRU5ErkJggg==";
@Test
public void testWorker() throws Exception {
DecoderConfig config = new DecoderConfig();
JCommander jCommander = new JCommander(config);
jCommander.parse("--pure_barcode", IMAGE_DATA_URI);
Queue<URI> inputs = new LinkedList<>(Collections.singletonList(new URI(IMAGE_DATA_URI)));
DecodeWorker worker = new DecodeWorker(config, inputs);
assertEquals(1, worker.call().intValue());
}
}
| zxing/zxing | javase/src/test/java/com/google/zxing/client/j2se/DecodeWorkerTestCase.java | 1,982 | /**
* Tests {@link DecodeWorker}.
*/ | block_comment | nl | /*
* Copyright 2018 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.client.j2se;
import com.beust.jcommander.JCommander;
import org.junit.Assert;
import org.junit.Test;
import java.net.URI;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
/**
* Tests {@link DecodeWorker}.<SUF>*/
public final class DecodeWorkerTestCase extends Assert {
static final String IMAGE_DATA_URI =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACEAAAAhAQAAAAB/n//CAAAAkklEQVR42mP4DwQNDJjkB4" +
"E77A0M369N/d7A8CV6rjiQjPMFkWG1QPL7RVGg%2BAfREKCa/5/vA9V/nFSQ3sDwb7/KdiDJqX4dSH4pXN/A8DfyDVD2" +
"988HQPUfPVaqA0XKz%2BgD9bIk1AP1fgwvB7KlS9VBdqXbA82PT9AH2fiaH2SXGdDM71fDgeIfhIvKsbkTTAIAKYVr0N" +
"z5IloAAAAASUVORK5CYII=";
static final String IMAGE_NOBARCODE_DATA_URI =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAACE1BMVEUAAAAYsPIXsPL//+" +
"2J6/CI6vB74/Alt/IXr/LL/++M7PD//+UZsPIXr/ISrfIRrPIXsPIYsPIYsPIKqfIQrPITrvIZsfImt/IouPImt/IZsf" +
"IXr/IXsPIbsfIWr/IcsvInuPImuPIvvPJt3PB54vBt3PAasfIXsPIXr/IUrvIYsPIwvfJx3vB54vCE6PCS7/B64/Bt3P" +
"AktvIXr/IYsPIYsPIasfIlt/IwvPKJ6/CM7PCW8fCQ7vCB5vAmt/IXr/IYsPIYsPIXsPKI6vCI6vCI6vAYsfMYsPIYsP" +
"KI6vCI6vCI6vAYrO0YsPGI6vCI6vCI6vCJ6/CH6vBw3vB64/CE6PAwvPJr2/FLy/ESrfIYsPIjtvIasfIYsPIYsPIYsP" +
"IYsPIYsPIYsPIYsPIYsPIYre4vvPIktvJ64/Bx3vCI6vAitfJj1/F74/CH6vAbsfI7wvF/5fCJ6vAXsPJw3fAWmNEYre" +
"0mt/J85PCJ6/Bw3vAXqukYr/EYsPIZsPIwvPJ95PAjtvIVksgWmtQYre4VlMsXpuUVkccWl9AXquouu/Jy3/AWl88Wm9" +
"QXpuQYrO0ZsfIVkcgVlMwWmNAXqekVisIVkMcVkscWm9UTXaQVgr0VisMVlcwTT5oTVZ4TXKMVhL4TTpoTTZoTW6MVg7" +
"4Vj8YVicIVkMYVi8MUfbkTVZ8UfLkUY6gTVJ4Vg70TT5sTVp/hyCW0AAAAZnRSTlMAAAAAAAAAAAAAAAACGx8fHxsCAh" +
"k2yeTi4uLJMgEZNsnm++fi5s80GTbJ5v3NNhzJ4uCvFwHJ5v3mNgIbHx8cBDHN/ckZOcz+5jYC5f3k4Bzk/f3NMv7NNh" +
"0f/eTg4jYd/eQZ5v3GzkXBAAAByUlEQVQ4y73TvW4TQRSG4e/dtbHx2hv/FBEIEBWIEgmLhoaGittJRYeEfAUUFBS+Ai" +
"qIoIBQgGQRFKWwoAxgKYog3vXf2uvx7lAkBDvyio7TnkffnDOaQf8o/h/4C+06gOQB1oHgnEASosZZ9VYFQvLqp837vO" +
"NnsAqQdwXg3oeTI+DzOXDn8DLcZo8OdwF4vwqaZW4BXdiRrAPxuRkewE3gC7wxa+/hITfGlXkXdrQebJHkoLvICBBbJO" +
"PG+BsvlQEeAbAfZydccCI//jrMnOExxMDrWtYWT4iI/LiTtQYtGIsybwd7GLMOKB84UqUDrxbzNe+hJeNNY+F2AbYJlp" +
"r2BKQX6UvR1U/AbpP5aXebQLKipRIQxlJUknr8GYPdZu5FINGSpNSPRsVZcVhYyu+5H5vMxVMIJZHW+5VJ2UxiqTArep" +
"NZcXaUGIlnYAaS0sR1lG5O+X4tjiuWUT2yhXBW5DlwWA3PktPNo8RN8sZN3MT1RwFtrMO0FNaCoXzVDyTper8WVF17IO" +
"OWaUsLTDWsTfIyc+eXr6EuWS+oM/shX9CWhKmGeVPRtHxcMtqIbIqpOmNKAxnaS1/E+migDR3nJGnR0GDR+A23fMFDA8" +
"6WRQAAAABJRU5ErkJggg==";
@Test
public void testWorker() throws Exception {
DecoderConfig config = new DecoderConfig();
JCommander jCommander = new JCommander(config);
jCommander.parse("--pure_barcode", IMAGE_DATA_URI);
Queue<URI> inputs = new LinkedList<>(Collections.singletonList(new URI(IMAGE_DATA_URI)));
DecodeWorker worker = new DecodeWorker(config, inputs);
assertEquals(1, worker.call().intValue());
}
}
| False | 1,714 | 9 | 1,707 | 11 | 1,713 | 11 | 1,707 | 11 | 2,039 | 13 | false | false | false | false | false | true |
3,610 | 22285_2 | package ipsen1.quarto.form;
import ipsen1.quarto.QuartoApplication;
import ipsen1.quarto.form.menu.MenuButton;
import ipsen1.quarto.util.FontOpenSans;
import ipsen1.quarto.util.QuartoColor;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Instructies extends Form {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(background, 0, 0, null);
}
public Instructies() {
// Instellen Formaat en layout
setPreferredSize(new Dimension(1024, 768));
setLayout(new BorderLayout(10, 10));
setBackground(QuartoColor.DARK_BROWN);
// Defineren Titel koptekst
JLabel titelLabel = new JLabel("Instructies", SwingConstants.CENTER);
titelLabel.setFont(FontOpenSans.create(48));
titelLabel.setForeground(QuartoColor.WHITE);
// Defineren Instructie tekst
JLabel instructieTekst = new JLabel();
instructieTekst.setForeground(QuartoColor.WHITE);
final int side_margin = 1024 / 6;
setBorder(new EmptyBorder(0, side_margin, 55, side_margin));
// Vullen instructie tekst
StringBuilder sb = new StringBuilder();
sb.append("<HTML>");
sb.append("Quarto is een bordspel dat bestaat uit 16 stukken met elk een unieke combinatie van 4 eigenschappen:<br>");
sb.append("<br>");
sb.append("- Hoog of laag<br>");
sb.append("- Vol of hol<br>");
sb.append("- Licht of donker<br>");
sb.append("- Rond of vierkant<br>");
sb.append("<br>");
sb.append("Aan het begin van elke beurt kan de speler een spelstuk plaatsen op het bord, en vervolgens een spelstuk uitkiezen uitkiezen" +
" die de tegenstander tijdens zijn beurt moet plaatsen. Spelstukken die op het bord geplaatst zijn behoren niet tot een" +
" bepaalde speler en zijn dus neutraal<br>");
sb.append("<br><br>");
sb.append("Doel:<br>");
sb.append("<br>");
sb.append("Het doel van Quarto is, is om 4 op een rij te creëren op het bord met stukken die 1 eigenschap delen, voorbeeld hiervan is 4 lichte spelstukken" +
" of 4 ronde spelstukken.");
sb.append("Op het moment dat een spelstuk geplaatst is en de speler ziet een rij met gelijke eigenschappen, mag de huidige speler Quarto roepen. " +
"Door deze roep te doen, is het mogelijk dat de speler de beurt wint. Als de speler de Quarto niet ziet, kan de tegenstander dit alsnog afroepen, " +
"voordat deze zijn gegeven spelstuk plaatst. Mochten beide spelers de Quarto niet zien binnen 1 beurt, zal de Quarto als ongeldig gerekend worden" +
" en is deze niet meer geldig. Mocht een speler onterecht Quarto roepen, zal diens beurt eindigen en is de volgende speler aan zet.<br>");
sb.append("Het spel eindigt in gelijkspel als beide spelers geen Quarto afroepen nadat alle spelstukken geplaatst zijn.<br>");
sb.append("</HTML>");
instructieTekst.setText(sb.toString());
// Knop aanmaken en invullen
JButton okKnop = new MenuButton("OK, Terug naar menu");
okKnop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
QuartoApplication.currentApplication().popForm();
}
});
okKnop.setSize(20,20);
okKnop.setBorder(new EmptyBorder(0,0,0,0));
// Toevoegen Labels
add(titelLabel, BorderLayout.NORTH);
add(instructieTekst, BorderLayout.CENTER);
add(okKnop, BorderLayout.SOUTH);
}
} | mbernson/ipsen1-quarto | src/main/java/ipsen1/quarto/form/Instructies.java | 1,200 | // Defineren Instructie tekst | line_comment | nl | package ipsen1.quarto.form;
import ipsen1.quarto.QuartoApplication;
import ipsen1.quarto.form.menu.MenuButton;
import ipsen1.quarto.util.FontOpenSans;
import ipsen1.quarto.util.QuartoColor;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Instructies extends Form {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(background, 0, 0, null);
}
public Instructies() {
// Instellen Formaat en layout
setPreferredSize(new Dimension(1024, 768));
setLayout(new BorderLayout(10, 10));
setBackground(QuartoColor.DARK_BROWN);
// Defineren Titel koptekst
JLabel titelLabel = new JLabel("Instructies", SwingConstants.CENTER);
titelLabel.setFont(FontOpenSans.create(48));
titelLabel.setForeground(QuartoColor.WHITE);
// Defineren Instructie<SUF>
JLabel instructieTekst = new JLabel();
instructieTekst.setForeground(QuartoColor.WHITE);
final int side_margin = 1024 / 6;
setBorder(new EmptyBorder(0, side_margin, 55, side_margin));
// Vullen instructie tekst
StringBuilder sb = new StringBuilder();
sb.append("<HTML>");
sb.append("Quarto is een bordspel dat bestaat uit 16 stukken met elk een unieke combinatie van 4 eigenschappen:<br>");
sb.append("<br>");
sb.append("- Hoog of laag<br>");
sb.append("- Vol of hol<br>");
sb.append("- Licht of donker<br>");
sb.append("- Rond of vierkant<br>");
sb.append("<br>");
sb.append("Aan het begin van elke beurt kan de speler een spelstuk plaatsen op het bord, en vervolgens een spelstuk uitkiezen uitkiezen" +
" die de tegenstander tijdens zijn beurt moet plaatsen. Spelstukken die op het bord geplaatst zijn behoren niet tot een" +
" bepaalde speler en zijn dus neutraal<br>");
sb.append("<br><br>");
sb.append("Doel:<br>");
sb.append("<br>");
sb.append("Het doel van Quarto is, is om 4 op een rij te creëren op het bord met stukken die 1 eigenschap delen, voorbeeld hiervan is 4 lichte spelstukken" +
" of 4 ronde spelstukken.");
sb.append("Op het moment dat een spelstuk geplaatst is en de speler ziet een rij met gelijke eigenschappen, mag de huidige speler Quarto roepen. " +
"Door deze roep te doen, is het mogelijk dat de speler de beurt wint. Als de speler de Quarto niet ziet, kan de tegenstander dit alsnog afroepen, " +
"voordat deze zijn gegeven spelstuk plaatst. Mochten beide spelers de Quarto niet zien binnen 1 beurt, zal de Quarto als ongeldig gerekend worden" +
" en is deze niet meer geldig. Mocht een speler onterecht Quarto roepen, zal diens beurt eindigen en is de volgende speler aan zet.<br>");
sb.append("Het spel eindigt in gelijkspel als beide spelers geen Quarto afroepen nadat alle spelstukken geplaatst zijn.<br>");
sb.append("</HTML>");
instructieTekst.setText(sb.toString());
// Knop aanmaken en invullen
JButton okKnop = new MenuButton("OK, Terug naar menu");
okKnop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
QuartoApplication.currentApplication().popForm();
}
});
okKnop.setSize(20,20);
okKnop.setBorder(new EmptyBorder(0,0,0,0));
// Toevoegen Labels
add(titelLabel, BorderLayout.NORTH);
add(instructieTekst, BorderLayout.CENTER);
add(okKnop, BorderLayout.SOUTH);
}
} | True | 971 | 8 | 1,133 | 9 | 1,001 | 7 | 1,133 | 9 | 1,212 | 9 | false | false | false | false | false | true |
4,700 | 26253_2 | package whitetea.magicmatrix.model;
import java.awt.Color;
import java.awt.image.BufferedImage;
/**
*
* @author WhiteTea
*
*/
public class Frame implements Cloneable {
//TODO overal met x y & width heigthwerken ipv rowNr & colNr
private final int rows, cols;
private Color[][] colors;
public Frame(int rows, int cols) {
if(rows <= 0)
throw new IllegalArgumentException("The number of rows must be strictly positive.");
if(cols <= 0)
throw new IllegalArgumentException("The number of columns must be strictly positive.");
this.rows = rows;
this.cols = cols;
colors = new Color[rows][cols];
fill(new Color(0, 0, 0));
}
public Frame(Frame frame) {
this.rows = frame.getNbOfRows();
this.cols = frame.getNbOfColumns();
colors = new Color[rows][cols];
for (int y = 0; y < this.rows; y++)
for (int x = 0; x < this.cols; x++)
setPixelColor(y, x, frame.getPixelColor(y, x));
}
public int getNbOfRows() {
return rows;
}
public int getNbOfColumns() {
return cols;
}
public boolean isValidRowNr(int rowNr) {
return rowNr >= 0 && rowNr < rows;
}
public boolean isValidColNr(int colNr) {
return colNr >= 0 && colNr < cols;
}
public void setPixelColor(int rowNr, int colNr, Color c) {
if (!isValidRowNr(rowNr) || !isValidColNr(colNr))
throw new IllegalArgumentException(
"The given indices are not valid for this matrix size."
+ "\nMatrix size: " + rows + "x" + cols
+ "\nGiven indices: " + rowNr + ", " + colNr);
colors[rowNr][colNr] = c;
}
public Color getPixelColor(int rowNr, int colNr) {
if (!isValidRowNr(rowNr) || !isValidColNr(colNr))
throw new IllegalArgumentException(
"The given indices are not valid for this matrix size."
+ "\nMatrix size: " + rows + "x" + cols
+ "\nGiven indices: " + rowNr + ", " + colNr);
return colors[rowNr][colNr];
}
public void fill(Color c) {
for (int i = 0; i < rows; i++) {
fillRow(i, c);
}
}
public void fillRow(int rowNr, Color c) {
if (!isValidRowNr(rowNr))
throw new IllegalArgumentException("Invalid row number: " + rowNr
+ ". Matrix size is: " + rows + "x" + cols);
for (int i = 0; i < cols; i++)
setPixelColor(rowNr, i, c);
}
public void fillColumn(int colNr, Color c) {
if (!isValidColNr(colNr))
throw new IllegalArgumentException("Invalid column number: "
+ colNr + ". Matrix size is: " + rows + "x" + cols);
for (int i = 0; i < rows; i++)
setPixelColor(i, colNr, c);
}
//TODO laatste rij kleuren van eerste rij met boolean
//TODO strategy met color voor laatste rij
public void shiftLeft() {
for (int x = 0; x < this.cols; x++)
for (int y = 0; y < this.rows; y++)
setPixelColor(y, x,
(x < this.cols - 1) ? getPixelColor(y, x+1) : new Color(0,0,0));
}
public void shiftRight() {
for (int y = 0; y < this.rows; y++) {
for (int x = this.cols - 1; x >= 0; x--) {
setPixelColor(y, x, (x > 0) ? getPixelColor(y,x - 1) : new Color(0,0,0));
}
}
}
public void shiftUp() {
for (int y = 0; y < this.rows; y++) {
for (int x = 0; x < this.cols; x++) {
setPixelColor(y, x,
(y < this.rows - 1) ? getPixelColor(y + 1, x) : new Color(0,0,0));
}
}
}
public void shiftDown() {
for (int y = this.rows - 1; y >= 0; y--) {
for (int x = 0; x < this.cols; x++) {
setPixelColor(y, x, (y > 0) ? getPixelColor(y - 1, x) : new Color(0,0,0));
}
}
}
public BufferedImage getImage() {
BufferedImage bufferedImage = new BufferedImage(colors[0].length, colors.length,
BufferedImage.TYPE_INT_RGB);
// Set each pixel of the BufferedImage to the color from the Color[][].
for (int x = 0; x < getNbOfColumns(); x++)
for (int y = 0; y < getNbOfRows(); y++)
bufferedImage.setRGB(x, y, colors[y][x].getRGB());
return bufferedImage;
}
@Override
public Frame clone() {
return new Frame(this);
}
}
| wietsebuseyne/MagicMatrix | MagicMatrix/src/whitetea/magicmatrix/model/Frame.java | 1,549 | //TODO laatste rij kleuren van eerste rij met boolean | line_comment | nl | package whitetea.magicmatrix.model;
import java.awt.Color;
import java.awt.image.BufferedImage;
/**
*
* @author WhiteTea
*
*/
public class Frame implements Cloneable {
//TODO overal met x y & width heigthwerken ipv rowNr & colNr
private final int rows, cols;
private Color[][] colors;
public Frame(int rows, int cols) {
if(rows <= 0)
throw new IllegalArgumentException("The number of rows must be strictly positive.");
if(cols <= 0)
throw new IllegalArgumentException("The number of columns must be strictly positive.");
this.rows = rows;
this.cols = cols;
colors = new Color[rows][cols];
fill(new Color(0, 0, 0));
}
public Frame(Frame frame) {
this.rows = frame.getNbOfRows();
this.cols = frame.getNbOfColumns();
colors = new Color[rows][cols];
for (int y = 0; y < this.rows; y++)
for (int x = 0; x < this.cols; x++)
setPixelColor(y, x, frame.getPixelColor(y, x));
}
public int getNbOfRows() {
return rows;
}
public int getNbOfColumns() {
return cols;
}
public boolean isValidRowNr(int rowNr) {
return rowNr >= 0 && rowNr < rows;
}
public boolean isValidColNr(int colNr) {
return colNr >= 0 && colNr < cols;
}
public void setPixelColor(int rowNr, int colNr, Color c) {
if (!isValidRowNr(rowNr) || !isValidColNr(colNr))
throw new IllegalArgumentException(
"The given indices are not valid for this matrix size."
+ "\nMatrix size: " + rows + "x" + cols
+ "\nGiven indices: " + rowNr + ", " + colNr);
colors[rowNr][colNr] = c;
}
public Color getPixelColor(int rowNr, int colNr) {
if (!isValidRowNr(rowNr) || !isValidColNr(colNr))
throw new IllegalArgumentException(
"The given indices are not valid for this matrix size."
+ "\nMatrix size: " + rows + "x" + cols
+ "\nGiven indices: " + rowNr + ", " + colNr);
return colors[rowNr][colNr];
}
public void fill(Color c) {
for (int i = 0; i < rows; i++) {
fillRow(i, c);
}
}
public void fillRow(int rowNr, Color c) {
if (!isValidRowNr(rowNr))
throw new IllegalArgumentException("Invalid row number: " + rowNr
+ ". Matrix size is: " + rows + "x" + cols);
for (int i = 0; i < cols; i++)
setPixelColor(rowNr, i, c);
}
public void fillColumn(int colNr, Color c) {
if (!isValidColNr(colNr))
throw new IllegalArgumentException("Invalid column number: "
+ colNr + ". Matrix size is: " + rows + "x" + cols);
for (int i = 0; i < rows; i++)
setPixelColor(i, colNr, c);
}
//TODO laatste<SUF>
//TODO strategy met color voor laatste rij
public void shiftLeft() {
for (int x = 0; x < this.cols; x++)
for (int y = 0; y < this.rows; y++)
setPixelColor(y, x,
(x < this.cols - 1) ? getPixelColor(y, x+1) : new Color(0,0,0));
}
public void shiftRight() {
for (int y = 0; y < this.rows; y++) {
for (int x = this.cols - 1; x >= 0; x--) {
setPixelColor(y, x, (x > 0) ? getPixelColor(y,x - 1) : new Color(0,0,0));
}
}
}
public void shiftUp() {
for (int y = 0; y < this.rows; y++) {
for (int x = 0; x < this.cols; x++) {
setPixelColor(y, x,
(y < this.rows - 1) ? getPixelColor(y + 1, x) : new Color(0,0,0));
}
}
}
public void shiftDown() {
for (int y = this.rows - 1; y >= 0; y--) {
for (int x = 0; x < this.cols; x++) {
setPixelColor(y, x, (y > 0) ? getPixelColor(y - 1, x) : new Color(0,0,0));
}
}
}
public BufferedImage getImage() {
BufferedImage bufferedImage = new BufferedImage(colors[0].length, colors.length,
BufferedImage.TYPE_INT_RGB);
// Set each pixel of the BufferedImage to the color from the Color[][].
for (int x = 0; x < getNbOfColumns(); x++)
for (int y = 0; y < getNbOfRows(); y++)
bufferedImage.setRGB(x, y, colors[y][x].getRGB());
return bufferedImage;
}
@Override
public Frame clone() {
return new Frame(this);
}
}
| True | 1,210 | 12 | 1,398 | 18 | 1,390 | 10 | 1,398 | 18 | 1,657 | 15 | false | false | false | false | false | true |
3,953 | 95733_2 | package com.matchfixing.minor.matchfixing;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Invitation extends Activity {
String MATCHID, MATCHDATE, MATCHTIME, MATCHTYPE, MATCHLANE, MATCHDESCRIPTION;
int userID;
String s;
List<String> matches = null;
List<String> matchDates = null;
List<String> matchTimes = null;
List<String> matchLanes = null;
List<String> matchTypes = null;
Map<String, Integer> matchIDs = null;
List<String> matchDescriptionsList = null;
GridView matchGrid;
TextView txtView;
private int previousSelectedPosition = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.matches_today);
userID = Integer.parseInt(PersonaliaSingleton.getInstance().getUserID());
matches = new ArrayList<String>();
matchIDs = new HashMap<String, Integer>();
matchDescriptionsList = new ArrayList<>();
matchDates = new ArrayList<>();
matchTimes = new ArrayList<>();
matchLanes = new ArrayList<>();
matchTypes = new ArrayList<>();
s = Integer.toString(userID);
txtView = (TextView) findViewById(R.id.textView2);
txtView.setText("Hier vind je matches waar mensen jou persoonlijk voor uitgenodigd hebben. Klik een match aan om de details te kunnen zien.");
matchGrid = (GridView) findViewById(R.id.gridView);
SetupView();
String databaseInfo = "userID="+userID;
String fileName = "GetInvitations.php";
Invitation.BackGround b = new Invitation.BackGround();
b.execute(s);
}
public void home_home(View view){
startActivity(new Intent(this, Home.class));
}
public void SetupView()
{
final GridView gv = (GridView) findViewById(R.id.gridView);
gv.setAdapter(new GridViewAdapter(Invitation.this, matches){
public View getView(int position, View convertView, ViewGroup parent){
View view = super.getView(position, convertView, parent);
TextView tv = (TextView) view;
tv.setTextColor(Color.WHITE);
tv.setBackgroundColor(Color.parseColor("#23db4e"));
tv.setTextSize(25);
return tv;
}
});
gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView tv = (TextView) view;
tv.setTextColor(Color.RED);
TextView previousSelectedView = (TextView) gv.getChildAt(previousSelectedPosition);
int clickedMatchID = -1;
//with thclickedMatchIDis method we retrieve the matchID. We need this to implement in the upcoming "MATCH ATTENDEES" table.
if(matchIDs != null) {
clickedMatchID = matchIDs.get(matches.get(position));
}
String matchDescription = matches.get(position);
String description = matchDescriptionsList.get(position);
String matchDate = matchDates.get(position);
String matchTime = matchTimes.get(position);
String matchLane = matchLanes.get(position);
String matchType = matchTypes.get(position);
int matchID = clickedMatchID;
Intent Popup = new Intent(Invitation.this, Popup.class);
Popup.putExtra("matchDescription", matchDescription);
Popup.putExtra("desc", description);
Popup.putExtra("matchID", matchID);
Popup.putExtra("matchDate", matchDate);
Popup.putExtra("matchTime", matchTime);
Popup.putExtra("matchLane", matchLane);
Popup.putExtra("matchType", matchType);
startActivity(Popup);
// If there is a previous selected view exists
if (previousSelectedPosition != -1)
{
previousSelectedView.setSelected(false);
previousSelectedView.setTextColor(Color.WHITE);
}
previousSelectedPosition = position;
}
});
}
// //onPostExecute samen ff nakijken.
// // Waarom kan hier wel findViewById en in mijn classe niet.
class BackGround extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
String userID = params[0];
String data = "";
int tmp;
try {
URL url = new URL("http://141.252.218.158:80/GetInvitations.php");
String urlParams = "userID=" + userID;
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(urlParams.getBytes());
os.flush();
os.close();
InputStream is = httpURLConnection.getInputStream();
while ((tmp = is.read()) != -1) {
data += (char) tmp;
}
is.close();
httpURLConnection.disconnect();
return data;
} catch (MalformedURLException e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
}
}
@Override
protected void onPostExecute(String s) {
String err = null;
String[] matchStrings = s.split("&");
int fieldID = -1;
for(int i = 0; i < matchStrings.length; ++i)
{
try {
JSONObject root = new JSONObject(matchStrings[i]);
JSONObject user_data = root.getJSONObject("user_data");
MATCHID = user_data.getString("MatchID");
MATCHDATE = user_data.getString("matchDate");
MATCHTIME = user_data.getString("matchTime");
MATCHTYPE = user_data.getString("MatchType");
MATCHLANE = user_data.getString("lane");
MATCHDESCRIPTION = user_data.getString("description");
//dates times lanes types
matchDates.add(MATCHDATE);
matchTimes.add(MATCHTIME);
matchTypes.add(MATCHTYPE);
matchLanes.add(MATCHLANE);
matches.add(MATCHDATE + " " + MATCHTIME + " " + MATCHTYPE + " " + MATCHLANE);
matchIDs.put(MATCHDATE + " " + MATCHTIME + " " + MATCHTYPE + " " + MATCHLANE, Integer.parseInt(MATCHID));
matchDescriptionsList.add(MATCHDESCRIPTION);
} catch (JSONException e) {
e.printStackTrace();
err = "Exception: " + e.getMessage();
}
}
SetupView();
}
}
}
| pasibun/MatchFixing | app/src/main/java/com/matchfixing/minor/matchfixing/Invitation.java | 2,144 | // //onPostExecute samen ff nakijken. | line_comment | nl | package com.matchfixing.minor.matchfixing;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Invitation extends Activity {
String MATCHID, MATCHDATE, MATCHTIME, MATCHTYPE, MATCHLANE, MATCHDESCRIPTION;
int userID;
String s;
List<String> matches = null;
List<String> matchDates = null;
List<String> matchTimes = null;
List<String> matchLanes = null;
List<String> matchTypes = null;
Map<String, Integer> matchIDs = null;
List<String> matchDescriptionsList = null;
GridView matchGrid;
TextView txtView;
private int previousSelectedPosition = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.matches_today);
userID = Integer.parseInt(PersonaliaSingleton.getInstance().getUserID());
matches = new ArrayList<String>();
matchIDs = new HashMap<String, Integer>();
matchDescriptionsList = new ArrayList<>();
matchDates = new ArrayList<>();
matchTimes = new ArrayList<>();
matchLanes = new ArrayList<>();
matchTypes = new ArrayList<>();
s = Integer.toString(userID);
txtView = (TextView) findViewById(R.id.textView2);
txtView.setText("Hier vind je matches waar mensen jou persoonlijk voor uitgenodigd hebben. Klik een match aan om de details te kunnen zien.");
matchGrid = (GridView) findViewById(R.id.gridView);
SetupView();
String databaseInfo = "userID="+userID;
String fileName = "GetInvitations.php";
Invitation.BackGround b = new Invitation.BackGround();
b.execute(s);
}
public void home_home(View view){
startActivity(new Intent(this, Home.class));
}
public void SetupView()
{
final GridView gv = (GridView) findViewById(R.id.gridView);
gv.setAdapter(new GridViewAdapter(Invitation.this, matches){
public View getView(int position, View convertView, ViewGroup parent){
View view = super.getView(position, convertView, parent);
TextView tv = (TextView) view;
tv.setTextColor(Color.WHITE);
tv.setBackgroundColor(Color.parseColor("#23db4e"));
tv.setTextSize(25);
return tv;
}
});
gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView tv = (TextView) view;
tv.setTextColor(Color.RED);
TextView previousSelectedView = (TextView) gv.getChildAt(previousSelectedPosition);
int clickedMatchID = -1;
//with thclickedMatchIDis method we retrieve the matchID. We need this to implement in the upcoming "MATCH ATTENDEES" table.
if(matchIDs != null) {
clickedMatchID = matchIDs.get(matches.get(position));
}
String matchDescription = matches.get(position);
String description = matchDescriptionsList.get(position);
String matchDate = matchDates.get(position);
String matchTime = matchTimes.get(position);
String matchLane = matchLanes.get(position);
String matchType = matchTypes.get(position);
int matchID = clickedMatchID;
Intent Popup = new Intent(Invitation.this, Popup.class);
Popup.putExtra("matchDescription", matchDescription);
Popup.putExtra("desc", description);
Popup.putExtra("matchID", matchID);
Popup.putExtra("matchDate", matchDate);
Popup.putExtra("matchTime", matchTime);
Popup.putExtra("matchLane", matchLane);
Popup.putExtra("matchType", matchType);
startActivity(Popup);
// If there is a previous selected view exists
if (previousSelectedPosition != -1)
{
previousSelectedView.setSelected(false);
previousSelectedView.setTextColor(Color.WHITE);
}
previousSelectedPosition = position;
}
});
}
// //onPostExecute samen<SUF>
// // Waarom kan hier wel findViewById en in mijn classe niet.
class BackGround extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
String userID = params[0];
String data = "";
int tmp;
try {
URL url = new URL("http://141.252.218.158:80/GetInvitations.php");
String urlParams = "userID=" + userID;
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(urlParams.getBytes());
os.flush();
os.close();
InputStream is = httpURLConnection.getInputStream();
while ((tmp = is.read()) != -1) {
data += (char) tmp;
}
is.close();
httpURLConnection.disconnect();
return data;
} catch (MalformedURLException e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
}
}
@Override
protected void onPostExecute(String s) {
String err = null;
String[] matchStrings = s.split("&");
int fieldID = -1;
for(int i = 0; i < matchStrings.length; ++i)
{
try {
JSONObject root = new JSONObject(matchStrings[i]);
JSONObject user_data = root.getJSONObject("user_data");
MATCHID = user_data.getString("MatchID");
MATCHDATE = user_data.getString("matchDate");
MATCHTIME = user_data.getString("matchTime");
MATCHTYPE = user_data.getString("MatchType");
MATCHLANE = user_data.getString("lane");
MATCHDESCRIPTION = user_data.getString("description");
//dates times lanes types
matchDates.add(MATCHDATE);
matchTimes.add(MATCHTIME);
matchTypes.add(MATCHTYPE);
matchLanes.add(MATCHLANE);
matches.add(MATCHDATE + " " + MATCHTIME + " " + MATCHTYPE + " " + MATCHLANE);
matchIDs.put(MATCHDATE + " " + MATCHTIME + " " + MATCHTYPE + " " + MATCHLANE, Integer.parseInt(MATCHID));
matchDescriptionsList.add(MATCHDESCRIPTION);
} catch (JSONException e) {
e.printStackTrace();
err = "Exception: " + e.getMessage();
}
}
SetupView();
}
}
}
| True | 1,439 | 10 | 1,692 | 14 | 1,788 | 11 | 1,693 | 14 | 2,050 | 12 | false | false | false | false | false | true |
2,197 | 190297_8 | package nl.avans.android.todos.service;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import nl.avans.android.todos.R;
import nl.avans.android.todos.domain.ToDo;
import nl.avans.android.todos.domain.ToDoMapper;
/**
* Deze class handelt requests naar de API server af. De JSON objecten die we terug krijgen
* worden door de ToDoMapper vertaald naar (lijsten van) ToDo items.
*/
public class ToDoRequest {
private Context context;
public final String TAG = this.getClass().getSimpleName();
// De aanroepende class implementeert deze interface.
private ToDoRequest.ToDoListener listener;
/**
* Constructor
*
* @param context
* @param listener
*/
public ToDoRequest(Context context, ToDoRequest.ToDoListener listener) {
this.context = context;
this.listener = listener;
}
/**
* Verstuur een GET request om alle ToDo's op te halen.
*/
public void handleGetAllToDos() {
Log.i(TAG, "handleGetAllToDos");
// Haal het token uit de prefs
SharedPreferences sharedPref = context.getSharedPreferences(
context.getString(R.string.preference_file_key), Context.MODE_PRIVATE);
final String token = sharedPref.getString(context.getString(R.string.saved_token), "dummy default token");
if(token != null && !token.equals("dummy default token")) {
Log.i(TAG, "Token gevonden, we gaan het request uitvoeren");
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, Config.URL_TODOS, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// Succesvol response
Log.i(TAG, response.toString());
ArrayList<ToDo> result = ToDoMapper.mapToDoList(response);
listener.onToDosAvailable(result);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// handleErrorResponse(error);
Log.e(TAG, error.toString());
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer " + token);
return headers;
}
};
// Access the RequestQueue through your singleton class.
VolleyRequestQueue.getInstance(context).addToRequestQueue(jsObjRequest);
}
}
/**
* Verstuur een POST met nieuwe ToDo.
*/
public void handlePostToDo(final ToDo newTodo) {
Log.i(TAG, "handlePostToDo");
// Haal het token uit de prefs
SharedPreferences sharedPref = context.getSharedPreferences(
context.getString(R.string.preference_file_key), Context.MODE_PRIVATE);
final String token = sharedPref.getString(context.getString(R.string.saved_token), "dummy default token");
if(token != null && !token.equals("dummy default token")) {
//
// Maak een JSON object met username en password. Dit object sturen we mee
// als request body (zoals je ook met Postman hebt gedaan)
//
String body = "{\"Titel\":\"" + newTodo.getTitle() + "\",\"Beschrijving\":\"" + newTodo.getContents() + "\"}";
try {
JSONObject jsonBody = new JSONObject(body);
Log.i(TAG, "handlePostToDo - body = " + jsonBody);
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.POST, Config.URL_TODOS, jsonBody, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i(TAG, response.toString());
// Het toevoegen is gelukt
// Hier kun je kiezen: of een refresh van de hele lijst ophalen
// en de ListView bijwerken ... Of alleen de ene update toevoegen
// aan de ArrayList. Wij doen dat laatste.
listener.onToDoAvailable(newTodo);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Error - send back to caller
listener.onToDosError(error.toString());
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer " + token);
return headers;
}
};
// Access the RequestQueue through your singleton class.
VolleyRequestQueue.getInstance(context).addToRequestQueue(jsObjRequest);
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
listener.onToDosError(e.getMessage());
}
}
}
//
// Callback interface - implemented by the calling class (MainActivity in our case).
//
public interface ToDoListener {
// Callback function to return a fresh list of ToDos
void onToDosAvailable(ArrayList<ToDo> toDos);
// Callback function to handle a single added ToDo.
void onToDoAvailable(ToDo todo);
// Callback to handle serverside API errors
void onToDosError(String message);
}
}
| baspalinckx/android-todolist | app/src/main/java/nl/avans/android/todos/service/ToDoRequest.java | 1,733 | // Maak een JSON object met username en password. Dit object sturen we mee | line_comment | nl | package nl.avans.android.todos.service;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import nl.avans.android.todos.R;
import nl.avans.android.todos.domain.ToDo;
import nl.avans.android.todos.domain.ToDoMapper;
/**
* Deze class handelt requests naar de API server af. De JSON objecten die we terug krijgen
* worden door de ToDoMapper vertaald naar (lijsten van) ToDo items.
*/
public class ToDoRequest {
private Context context;
public final String TAG = this.getClass().getSimpleName();
// De aanroepende class implementeert deze interface.
private ToDoRequest.ToDoListener listener;
/**
* Constructor
*
* @param context
* @param listener
*/
public ToDoRequest(Context context, ToDoRequest.ToDoListener listener) {
this.context = context;
this.listener = listener;
}
/**
* Verstuur een GET request om alle ToDo's op te halen.
*/
public void handleGetAllToDos() {
Log.i(TAG, "handleGetAllToDos");
// Haal het token uit de prefs
SharedPreferences sharedPref = context.getSharedPreferences(
context.getString(R.string.preference_file_key), Context.MODE_PRIVATE);
final String token = sharedPref.getString(context.getString(R.string.saved_token), "dummy default token");
if(token != null && !token.equals("dummy default token")) {
Log.i(TAG, "Token gevonden, we gaan het request uitvoeren");
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, Config.URL_TODOS, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// Succesvol response
Log.i(TAG, response.toString());
ArrayList<ToDo> result = ToDoMapper.mapToDoList(response);
listener.onToDosAvailable(result);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// handleErrorResponse(error);
Log.e(TAG, error.toString());
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer " + token);
return headers;
}
};
// Access the RequestQueue through your singleton class.
VolleyRequestQueue.getInstance(context).addToRequestQueue(jsObjRequest);
}
}
/**
* Verstuur een POST met nieuwe ToDo.
*/
public void handlePostToDo(final ToDo newTodo) {
Log.i(TAG, "handlePostToDo");
// Haal het token uit de prefs
SharedPreferences sharedPref = context.getSharedPreferences(
context.getString(R.string.preference_file_key), Context.MODE_PRIVATE);
final String token = sharedPref.getString(context.getString(R.string.saved_token), "dummy default token");
if(token != null && !token.equals("dummy default token")) {
//
// Maak een<SUF>
// als request body (zoals je ook met Postman hebt gedaan)
//
String body = "{\"Titel\":\"" + newTodo.getTitle() + "\",\"Beschrijving\":\"" + newTodo.getContents() + "\"}";
try {
JSONObject jsonBody = new JSONObject(body);
Log.i(TAG, "handlePostToDo - body = " + jsonBody);
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.POST, Config.URL_TODOS, jsonBody, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i(TAG, response.toString());
// Het toevoegen is gelukt
// Hier kun je kiezen: of een refresh van de hele lijst ophalen
// en de ListView bijwerken ... Of alleen de ene update toevoegen
// aan de ArrayList. Wij doen dat laatste.
listener.onToDoAvailable(newTodo);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Error - send back to caller
listener.onToDosError(error.toString());
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer " + token);
return headers;
}
};
// Access the RequestQueue through your singleton class.
VolleyRequestQueue.getInstance(context).addToRequestQueue(jsObjRequest);
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
listener.onToDosError(e.getMessage());
}
}
}
//
// Callback interface - implemented by the calling class (MainActivity in our case).
//
public interface ToDoListener {
// Callback function to return a fresh list of ToDos
void onToDosAvailable(ArrayList<ToDo> toDos);
// Callback function to handle a single added ToDo.
void onToDoAvailable(ToDo todo);
// Callback to handle serverside API errors
void onToDosError(String message);
}
}
| True | 1,200 | 17 | 1,428 | 19 | 1,454 | 16 | 1,428 | 19 | 1,694 | 18 | false | false | false | false | false | true |
988 | 33329_4 | package domein;
import java.io.File;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import persistentie.PersistentieController;
public class Garage {
private final File auto;
private final File onderhoud;
private Map<String, Auto> autoMap;
private Map<String, List<Onderhoud>> autoOnderhoudMap;
private List<Set<Auto>> overzichtLijstVanAutos;
private final int AANTAL_OVERZICHTEN = 3;
private int overzichtteller;
public Garage(String bestandAuto, String bestandOnderhoud) {
auto = new File(bestandAuto);
onderhoud = new File(bestandOnderhoud);
initGarage();
}
private void initGarage() {
PersistentieController persistentieController = new PersistentieController(auto, onderhoud);
// Set<Auto> inlezen - stap1
Set<Auto> autoSet = new HashSet<>(persistentieController.geefAutos());
System.out.println("STAP 1");
autoSet.forEach(auto -> System.out.println(auto));
// Maak map van auto's: volgens nummerplaat - stap2
autoMap = omzettenNaarAutoMap(autoSet);
System.out.println("STAP 2");
autoMap.forEach((k, v) -> System.out.printf("%s %s%n", k, v));
// Onderhoud inlezen - stap3
List<Onderhoud> onderhoudLijst = persistentieController.geefOnderhoudVanAutos();
System.out.println("STAP 3 : " + onderhoudLijst);
onderhoudLijst.forEach(o->System.out.println(o));
// lijst sorteren - stap4
sorteren(onderhoudLijst);
System.out.println("STAP 4");
onderhoudLijst.forEach(o->System.out.println(o));
// lijst samenvoegen - stap5
aangrenzendePeriodenSamenvoegen(onderhoudLijst);
System.out.println("STAP 5");
onderhoudLijst.forEach(o->System.out.println(o));
// Maak map van onderhoud: volgens nummerplaat - stap6
autoOnderhoudMap = omzettenNaarOnderhoudMap(onderhoudLijst);
System.out.println("STAP 6");
autoOnderhoudMap.forEach((k,v)->System.out.printf("%s %s%n",k,v));
// Maak overzicht: set van auto's - stap7
overzichtLijstVanAutos = maakOverzicht(autoOnderhoudMap);
System.out.println("STAP 7");
overzichtLijstVanAutos.forEach(System.out::println);
}
// Maak map van auto's: volgens nummerplaat - stap2
private Map<String, Auto> omzettenNaarAutoMap(Set<Auto> autoSet) {
return autoSet.stream().collect(Collectors.toMap(Auto::getNummerplaat, a -> a));
}
// lijst sorteren - stap4
private void sorteren(List<Onderhoud> lijstOnderhoud) {
lijstOnderhoud.sort(Comparator.comparing(Onderhoud::getNummerplaat).thenComparing(Onderhoud::getBegindatum));
}
// lijst samenvoegen - stap5
private void aangrenzendePeriodenSamenvoegen(List<Onderhoud> lijstOnderhoud) {
//java 7
Onderhoud onderhoud = null;
Onderhoud onderhoudNext = null;
Iterator<Onderhoud> it = lijstOnderhoud.iterator();
while (it.hasNext()) {
onderhoud = onderhoudNext;
onderhoudNext = it.next();
if (onderhoud != null && onderhoud.getNummerplaat().equals(onderhoudNext.getNummerplaat())) {
if (onderhoud.getEinddatum().plusDays(1).equals(onderhoudNext.getBegindatum())) {// samenvoegen:
onderhoud.setEinddatum(onderhoudNext.getEinddatum());
it.remove();
onderhoudNext = onderhoud;
}
}
}
}
// Maak map van onderhoud: volgens nummerplaat - stap6
private Map<String, List<Onderhoud>> omzettenNaarOnderhoudMap(List<Onderhoud> onderhoudLijst) {
return onderhoudLijst.stream().collect(Collectors.groupingBy(Onderhoud::getNummerplaat));
}
// Hulpmethode - nodig voor stap 7
private int sizeToCategorie(int size) {
return switch (size) {
case 0, 1 -> 0;
case 2, 3 -> 1;
default -> 2;
};
}
// Maak overzicht: set van auto's - stap7
private List<Set<Auto>> maakOverzicht(Map<String, List<Onderhoud>> autoOnderhoudMap) {
// Hint:
// van Map<String, List<Onderhoud>>
// naar Map<Integer, Set<Auto>> (hulpmethode gebruiken)
// naar List<Set<Auto>>
return autoOnderhoudMap.entrySet().stream().collect(Collectors.groupingBy(entry->sizeToCategory(entry.getValue().size()),
TreeMap::new,Collectors.mapping(entry-> autoMap.get(entry.getKey()),Collectors.toSet()).values().stream()
.collect(Collectors.toList());
}
//Oefening DomeinController:
public String autoMap_ToString() {
// String res = autoMap.
return null;
}
public String autoOnderhoudMap_ToString() {
String res = autoOnderhoudMap.toString();
return res;
}
public String overzicht_ToString() {
overzichtteller = 1;
// String res = overzichtLijstVanAutos.
return null;
}
}
| LuccaVanVeerdeghem/asd | ASDI_Java_Garage_start/src/domein/Garage.java | 1,740 | // lijst samenvoegen - stap5 | line_comment | nl | package domein;
import java.io.File;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import persistentie.PersistentieController;
public class Garage {
private final File auto;
private final File onderhoud;
private Map<String, Auto> autoMap;
private Map<String, List<Onderhoud>> autoOnderhoudMap;
private List<Set<Auto>> overzichtLijstVanAutos;
private final int AANTAL_OVERZICHTEN = 3;
private int overzichtteller;
public Garage(String bestandAuto, String bestandOnderhoud) {
auto = new File(bestandAuto);
onderhoud = new File(bestandOnderhoud);
initGarage();
}
private void initGarage() {
PersistentieController persistentieController = new PersistentieController(auto, onderhoud);
// Set<Auto> inlezen - stap1
Set<Auto> autoSet = new HashSet<>(persistentieController.geefAutos());
System.out.println("STAP 1");
autoSet.forEach(auto -> System.out.println(auto));
// Maak map van auto's: volgens nummerplaat - stap2
autoMap = omzettenNaarAutoMap(autoSet);
System.out.println("STAP 2");
autoMap.forEach((k, v) -> System.out.printf("%s %s%n", k, v));
// Onderhoud inlezen - stap3
List<Onderhoud> onderhoudLijst = persistentieController.geefOnderhoudVanAutos();
System.out.println("STAP 3 : " + onderhoudLijst);
onderhoudLijst.forEach(o->System.out.println(o));
// lijst sorteren - stap4
sorteren(onderhoudLijst);
System.out.println("STAP 4");
onderhoudLijst.forEach(o->System.out.println(o));
// lijst samenvoegen<SUF>
aangrenzendePeriodenSamenvoegen(onderhoudLijst);
System.out.println("STAP 5");
onderhoudLijst.forEach(o->System.out.println(o));
// Maak map van onderhoud: volgens nummerplaat - stap6
autoOnderhoudMap = omzettenNaarOnderhoudMap(onderhoudLijst);
System.out.println("STAP 6");
autoOnderhoudMap.forEach((k,v)->System.out.printf("%s %s%n",k,v));
// Maak overzicht: set van auto's - stap7
overzichtLijstVanAutos = maakOverzicht(autoOnderhoudMap);
System.out.println("STAP 7");
overzichtLijstVanAutos.forEach(System.out::println);
}
// Maak map van auto's: volgens nummerplaat - stap2
private Map<String, Auto> omzettenNaarAutoMap(Set<Auto> autoSet) {
return autoSet.stream().collect(Collectors.toMap(Auto::getNummerplaat, a -> a));
}
// lijst sorteren - stap4
private void sorteren(List<Onderhoud> lijstOnderhoud) {
lijstOnderhoud.sort(Comparator.comparing(Onderhoud::getNummerplaat).thenComparing(Onderhoud::getBegindatum));
}
// lijst samenvoegen - stap5
private void aangrenzendePeriodenSamenvoegen(List<Onderhoud> lijstOnderhoud) {
//java 7
Onderhoud onderhoud = null;
Onderhoud onderhoudNext = null;
Iterator<Onderhoud> it = lijstOnderhoud.iterator();
while (it.hasNext()) {
onderhoud = onderhoudNext;
onderhoudNext = it.next();
if (onderhoud != null && onderhoud.getNummerplaat().equals(onderhoudNext.getNummerplaat())) {
if (onderhoud.getEinddatum().plusDays(1).equals(onderhoudNext.getBegindatum())) {// samenvoegen:
onderhoud.setEinddatum(onderhoudNext.getEinddatum());
it.remove();
onderhoudNext = onderhoud;
}
}
}
}
// Maak map van onderhoud: volgens nummerplaat - stap6
private Map<String, List<Onderhoud>> omzettenNaarOnderhoudMap(List<Onderhoud> onderhoudLijst) {
return onderhoudLijst.stream().collect(Collectors.groupingBy(Onderhoud::getNummerplaat));
}
// Hulpmethode - nodig voor stap 7
private int sizeToCategorie(int size) {
return switch (size) {
case 0, 1 -> 0;
case 2, 3 -> 1;
default -> 2;
};
}
// Maak overzicht: set van auto's - stap7
private List<Set<Auto>> maakOverzicht(Map<String, List<Onderhoud>> autoOnderhoudMap) {
// Hint:
// van Map<String, List<Onderhoud>>
// naar Map<Integer, Set<Auto>> (hulpmethode gebruiken)
// naar List<Set<Auto>>
return autoOnderhoudMap.entrySet().stream().collect(Collectors.groupingBy(entry->sizeToCategory(entry.getValue().size()),
TreeMap::new,Collectors.mapping(entry-> autoMap.get(entry.getKey()),Collectors.toSet()).values().stream()
.collect(Collectors.toList());
}
//Oefening DomeinController:
public String autoMap_ToString() {
// String res = autoMap.
return null;
}
public String autoOnderhoudMap_ToString() {
String res = autoOnderhoudMap.toString();
return res;
}
public String overzicht_ToString() {
overzichtteller = 1;
// String res = overzichtLijstVanAutos.
return null;
}
}
| True | 1,444 | 10 | 1,687 | 12 | 1,465 | 7 | 1,687 | 12 | 1,844 | 10 | false | false | false | false | false | true |
2,030 | 14669_0 | package communitycommons;_x000D_
_x000D_
import java.util.Calendar;_x000D_
import java.util.Date;_x000D_
_x000D_
import communitycommons.proxies.DatePartSelector;_x000D_
_x000D_
public class DateTime_x000D_
{_x000D_
/**_x000D_
* @author mwe_x000D_
* Berekent aantal jaar sinds een bepaalde datum. Als einddatum == null, het huidige tijdstip wordt gebruikt_x000D_
* Code is gebaseerd op http://stackoverflow.com/questions/1116123/how-do-i-calculate-someones-age-in-java _x000D_
*/_x000D_
public static long yearsBetween(Date birthdate, Date comparedate) {_x000D_
if (birthdate == null)_x000D_
return -1L; _x000D_
_x000D_
Calendar now = Calendar.getInstance();_x000D_
if (comparedate != null)_x000D_
now.setTime(comparedate);_x000D_
Calendar dob = Calendar.getInstance();_x000D_
dob.setTime(birthdate);_x000D_
if (dob.after(now)) _x000D_
return -1L;_x000D_
_x000D_
int year1 = now.get(Calendar.YEAR);_x000D_
int year2 = dob.get(Calendar.YEAR);_x000D_
long age = year1 - year2;_x000D_
int month1 = now.get(Calendar.MONTH);_x000D_
int month2 = dob.get(Calendar.MONTH);_x000D_
if (month2 > month1) {_x000D_
age--;_x000D_
} else if (month1 == month2) {_x000D_
int day1 = now.get(Calendar.DAY_OF_MONTH);_x000D_
int day2 = dob.get(Calendar.DAY_OF_MONTH);_x000D_
if (day2 > day1) {_x000D_
age--;_x000D_
}_x000D_
}_x000D_
return age; _x000D_
}_x000D_
_x000D_
public static long dateTimeToLong(Date date)_x000D_
{_x000D_
return date.getTime();_x000D_
}_x000D_
_x000D_
public static Date longToDateTime(Long value)_x000D_
{_x000D_
return new Date(value);_x000D_
}_x000D_
_x000D_
public static long dateTimeToInteger(Date date, DatePartSelector selectorObj)_x000D_
{_x000D_
Calendar newDate = Calendar.getInstance();_x000D_
newDate.setTime(date);_x000D_
int value = -1;_x000D_
switch (selectorObj) {_x000D_
case year : value = newDate.get(Calendar.YEAR); break;_x000D_
case month : value = newDate.get(Calendar.MONTH)+1; break; // Return starts at 0_x000D_
case day : value = newDate.get(Calendar.DAY_OF_MONTH); break;_x000D_
default : break;_x000D_
}_x000D_
return value;_x000D_
}_x000D_
_x000D_
}_x000D_
| amadeobrands/RestServices | javasource/communitycommons/DateTime.java | 669 | /**_x000D_
* @author mwe_x000D_
* Berekent aantal jaar sinds een bepaalde datum. Als einddatum == null, het huidige tijdstip wordt gebruikt_x000D_
* Code is gebaseerd op http://stackoverflow.com/questions/1116123/how-do-i-calculate-someones-age-in-java _x000D_
*/ | block_comment | nl | package communitycommons;_x000D_
_x000D_
import java.util.Calendar;_x000D_
import java.util.Date;_x000D_
_x000D_
import communitycommons.proxies.DatePartSelector;_x000D_
_x000D_
public class DateTime_x000D_
{_x000D_
/**_x000D_
* @author mwe_x000D_
<SUF>*/_x000D_
public static long yearsBetween(Date birthdate, Date comparedate) {_x000D_
if (birthdate == null)_x000D_
return -1L; _x000D_
_x000D_
Calendar now = Calendar.getInstance();_x000D_
if (comparedate != null)_x000D_
now.setTime(comparedate);_x000D_
Calendar dob = Calendar.getInstance();_x000D_
dob.setTime(birthdate);_x000D_
if (dob.after(now)) _x000D_
return -1L;_x000D_
_x000D_
int year1 = now.get(Calendar.YEAR);_x000D_
int year2 = dob.get(Calendar.YEAR);_x000D_
long age = year1 - year2;_x000D_
int month1 = now.get(Calendar.MONTH);_x000D_
int month2 = dob.get(Calendar.MONTH);_x000D_
if (month2 > month1) {_x000D_
age--;_x000D_
} else if (month1 == month2) {_x000D_
int day1 = now.get(Calendar.DAY_OF_MONTH);_x000D_
int day2 = dob.get(Calendar.DAY_OF_MONTH);_x000D_
if (day2 > day1) {_x000D_
age--;_x000D_
}_x000D_
}_x000D_
return age; _x000D_
}_x000D_
_x000D_
public static long dateTimeToLong(Date date)_x000D_
{_x000D_
return date.getTime();_x000D_
}_x000D_
_x000D_
public static Date longToDateTime(Long value)_x000D_
{_x000D_
return new Date(value);_x000D_
}_x000D_
_x000D_
public static long dateTimeToInteger(Date date, DatePartSelector selectorObj)_x000D_
{_x000D_
Calendar newDate = Calendar.getInstance();_x000D_
newDate.setTime(date);_x000D_
int value = -1;_x000D_
switch (selectorObj) {_x000D_
case year : value = newDate.get(Calendar.YEAR); break;_x000D_
case month : value = newDate.get(Calendar.MONTH)+1; break; // Return starts at 0_x000D_
case day : value = newDate.get(Calendar.DAY_OF_MONTH); break;_x000D_
default : break;_x000D_
}_x000D_
return value;_x000D_
}_x000D_
_x000D_
}_x000D_
| False | 905 | 101 | 1,032 | 112 | 1,036 | 105 | 1,032 | 112 | 1,129 | 116 | false | false | false | false | false | true |
4,251 | 30552_23 | package nl.highco.thuglife;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import nl.saxion.act.playground.model.Game;
import nl.saxion.act.playground.model.GameBoard;
import nl.highco.thuglife.objects.*;
import android.media.AudioManager;
import android.media.MediaPlayer;
public class ThugGame extends Game implements Observer {
public static final String TAG = "thug game";
private MainActivity activity;
private int money, score, wiet;
private int highscore = 0;
private int politieScore = 50;
private MediaPlayer mPlayer;
public boolean isPlaying = false;
// map size
private final static int MAP_WIDTH = 100;
private final static int MAP_HIGHT = 100;
// map
private int[][] map;
// player
private Player player;
private ArrayList<Police> politie = new ArrayList<Police>();
//handlers
final Handler POLICEHANDLER = new Handler();
final Handler PLAYERHANDLER = new Handler();
// gameboard
private GameBoard gameBoard;
// timers
private Timer policeTimer;
private Timer playerTimer;
public ThugGame(MainActivity activity) {
super(new ThugGameboard(MAP_WIDTH, MAP_HIGHT));
this.activity = activity;
// starts the game
initGame();
// sets the game view to the game board
ThugGameBoardView gameView = activity.getGameBoardView();
gameBoard = getGameBoard();
gameBoard.addObserver(this);
gameView.setGameBoard(gameBoard);
//Swipe controls/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
gameView.setOnTouchListener(new OnSwipeTouchListener(activity) {
public void onSwipeTop() {
Log.i("touchListener", "omhoog");
player.setRichtingOmhoog();
}
public void onSwipeRight() {
Log.i("touchListener", "rechts");
player.setRichtingRechts();
}
public void onSwipeLeft() {
Log.i("touchListener", "links");
player.setRichtingLinks();
}
public void onSwipeBottom() {
Log.i("touchListener", "onder");
player.setRichtingBeneden();
}
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
});
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// decides what kind of map format to use
gameView.setFixedGridSize(gameBoard.getWidth(), gameBoard.getHeight());
}
public void initGame() {
// getting a map
MapGenerator mapgen = new MapGenerator();
map = mapgen.getRandomMap();
// setting up the board
GameBoard board = getGameBoard();
board.removeAllObjects();
// score , money en wiet naar 0
score = 0;
money = 0;
wiet = 10;
// add player
player = new Player();
board.addGameObject(player, 55, 50);
// add shop
board.addGameObject(new Shop(), 50, 60);
// add wiet
board.addGameObject(new Weed(), 42, 51);
board.addGameObject(new Weed(), 80, 95);
board.addGameObject(new Weed(), 75, 76);
board.addGameObject(new Weed(), 31, 64);
board.addGameObject(new Weed(), 98, 98);
board.addGameObject(new Weed(), 83, 84);
// add Police
politie.clear();
Police p1 = new Police();
Police p2 = new Police();
Police p3 = new Police();
Police p4 = new Police();
Police p5 = new Police();
Police p6 = new Police();
board.addGameObject(p1, 28, 30);
board.addGameObject(p2, 31, 38);
board.addGameObject(p3, 46, 47);
board.addGameObject(p4, 76, 34);
board.addGameObject(p5, 84, 88);
board.addGameObject(p6, 52, 63);
politie.add(p1);
politie.add(p2);
politie.add(p3);
politie.add(p4);
politie.add(p5);
politie.add(p6);
// load walls onto the field
for (int x = 0; x < MAP_WIDTH; x++) {
for (int y = 0; y < MAP_HIGHT; y++) {
if (map[x][y] == 1) {
if (board.getObject(x, y) == null) {
board.addGameObject(new Wall(), x, y);
}
}
}
}
board.updateView();
}
// adds police on a random spot within the map
public void addPolice() {
int xSpot = randomX();
int ySpot = randomY();
if (gameBoard.getObject(xSpot, ySpot) == null && xSpot > 26
&& ySpot > 11) {
politie.add(new Police());
getGameBoard().addGameObject(politie.get(politie.size() - 1),
xSpot, ySpot);
} else {
addPolice();
}
}
// adds wiet on a random spot within the map
public void addWietToMap() {
int xSpot = randomX();
int ySpot = randomY();
if (gameBoard.getObject(xSpot, ySpot) == null && xSpot > 26
&& ySpot > 11) {
getGameBoard().addGameObject(new Weed(), xSpot, ySpot);
} else {
addWietToMap();
}
}
public int randomX() {
int randomX = (int) (Math.random() * MAP_WIDTH);
return randomX;
}
public int randomY() {
int randomY = (int) (Math.random() * MAP_HIGHT);
return randomY;
}
public void enterShop() {
activity.gotoShopView();
}
//resets the game
public void reset() {
activity.resetShop();
initGame();
}
/**
* adds money to total of players' money
* @param aantal amount of money to be added
*/
public void addMoney(int aantal) {
money += aantal;
gameBoard.updateView();
}
/**
* deducts money of total of players' money
* @param aantal amount of money to be deducted
*/
public void deductMoney(int aantal) {
money -= aantal;
gameBoard.updateView();
}
/**
* adds 50 points to score when player collides with weed object
*/
public void updateScoreWCWW() {
score += 50;
if (score > highscore) {
highscore = score;
}
gameBoard.updateView();
}
/**
* adds one weed to the weed variable
*/
public void addWiet() {
wiet++;
gameBoard.updateView();
}
/**
* deducts the weed according to the given value
* @param aantal
*/
public void deductWiet(int aantal) {
wiet -= aantal;
gameBoard.updateView();
}
/**
* @return total amount of money the player has
*/
public int getMoney() {
return money;
}
/**
* @return total score the player has
*/
public int getScore() {
return score;
}
/**
* @return high score
*/
public int getHighscore() {
return highscore;
}
/**
* @return total amount of wiet the player has
*/
public int getWiet() {
return wiet;
}
/**
* @return the player object
*/
public Player getPlayer() {
return player;
}
//Timer//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// police timer methods
public void startPoliceTimer() {
isPlaying = true;
// maakt een timer die de handler en de runnable oproept elke halve
// seconde.
policeTimer = new Timer();
policeTimer.schedule(new TimerTask() {
@Override
public void run() {
UpdateGUIPolice();
}
}, 0, 250);
}
private void stopPoliceTimer() {
policeTimer.cancel();
}
// player timer methods
public void startPlayerTimer(int speed) {
isPlaying = true;
// maakt een timer die de handler en de runnable oproept elke halve
// seconde.
playerTimer = new Timer();
playerTimer.schedule(new TimerTask() {
@Override
public void run() {
UpdateGUIPlayer();
}
}, 0, speed);
}
private void stopPlayerTimer() {
playerTimer.cancel();
}
// De runnable voor de police die je aan de handler meegeeft.
final Runnable policeRunnable = new Runnable() {
public void run() {
for (int i = 0; i < politie.size(); i++) {
politie.get(i).onUpdate(gameBoard);
}
gameBoard.updateView();
}
};
// De runnable voor de player die je aan de handler meegeeft.
final Runnable playerRunnable = new Runnable() {
public void run() {
player.onUpdate(gameBoard);
}
};
// Methode waarmee je de runnable aan de handler meegeeft.
public void UpdateGUIPolice() {
POLICEHANDLER.post(policeRunnable);
}
public void UpdateGUIPlayer() {
PLAYERHANDLER.post(playerRunnable);
}
// kijken of player alive is
private boolean isPlayerAlive() {
if(player.getAliveState()){
return true;
}
return false;
}
// stops the timers
public void stopTimers() {
stopPlayerTimer();
stopPoliceTimer();
isPlaying = false;
}
public void update(Observable observable, Object data) {
if (!isPlayerAlive()) {
stopTimers();
activity.gotoGameOverScreen();
}
activity.updateMoneyLabels();
activity.updateScoreLabel();
activity.updateWietLabels();
activity.updateHighscoreLabel();
//Voegt politie toe als de speler een wiet object opppakt.
if (getScore() == politieScore) {
addPolice();
policeMusic();
addWietToMap();
politieScore = politieScore + 50;
}
}
//music for when the player picks up a wiet object
private void policeMusic() {
mPlayer = MediaPlayer.create(activity, R.raw.soundofdapolice);
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mPlayer.start();
}
}
| saxion-speelveld/project | Source/ThugLife/src/nl/highco/thuglife/ThugGame.java | 3,192 | // maakt een timer die de handler en de runnable oproept elke halve | line_comment | nl | package nl.highco.thuglife;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import nl.saxion.act.playground.model.Game;
import nl.saxion.act.playground.model.GameBoard;
import nl.highco.thuglife.objects.*;
import android.media.AudioManager;
import android.media.MediaPlayer;
public class ThugGame extends Game implements Observer {
public static final String TAG = "thug game";
private MainActivity activity;
private int money, score, wiet;
private int highscore = 0;
private int politieScore = 50;
private MediaPlayer mPlayer;
public boolean isPlaying = false;
// map size
private final static int MAP_WIDTH = 100;
private final static int MAP_HIGHT = 100;
// map
private int[][] map;
// player
private Player player;
private ArrayList<Police> politie = new ArrayList<Police>();
//handlers
final Handler POLICEHANDLER = new Handler();
final Handler PLAYERHANDLER = new Handler();
// gameboard
private GameBoard gameBoard;
// timers
private Timer policeTimer;
private Timer playerTimer;
public ThugGame(MainActivity activity) {
super(new ThugGameboard(MAP_WIDTH, MAP_HIGHT));
this.activity = activity;
// starts the game
initGame();
// sets the game view to the game board
ThugGameBoardView gameView = activity.getGameBoardView();
gameBoard = getGameBoard();
gameBoard.addObserver(this);
gameView.setGameBoard(gameBoard);
//Swipe controls/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
gameView.setOnTouchListener(new OnSwipeTouchListener(activity) {
public void onSwipeTop() {
Log.i("touchListener", "omhoog");
player.setRichtingOmhoog();
}
public void onSwipeRight() {
Log.i("touchListener", "rechts");
player.setRichtingRechts();
}
public void onSwipeLeft() {
Log.i("touchListener", "links");
player.setRichtingLinks();
}
public void onSwipeBottom() {
Log.i("touchListener", "onder");
player.setRichtingBeneden();
}
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
});
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// decides what kind of map format to use
gameView.setFixedGridSize(gameBoard.getWidth(), gameBoard.getHeight());
}
public void initGame() {
// getting a map
MapGenerator mapgen = new MapGenerator();
map = mapgen.getRandomMap();
// setting up the board
GameBoard board = getGameBoard();
board.removeAllObjects();
// score , money en wiet naar 0
score = 0;
money = 0;
wiet = 10;
// add player
player = new Player();
board.addGameObject(player, 55, 50);
// add shop
board.addGameObject(new Shop(), 50, 60);
// add wiet
board.addGameObject(new Weed(), 42, 51);
board.addGameObject(new Weed(), 80, 95);
board.addGameObject(new Weed(), 75, 76);
board.addGameObject(new Weed(), 31, 64);
board.addGameObject(new Weed(), 98, 98);
board.addGameObject(new Weed(), 83, 84);
// add Police
politie.clear();
Police p1 = new Police();
Police p2 = new Police();
Police p3 = new Police();
Police p4 = new Police();
Police p5 = new Police();
Police p6 = new Police();
board.addGameObject(p1, 28, 30);
board.addGameObject(p2, 31, 38);
board.addGameObject(p3, 46, 47);
board.addGameObject(p4, 76, 34);
board.addGameObject(p5, 84, 88);
board.addGameObject(p6, 52, 63);
politie.add(p1);
politie.add(p2);
politie.add(p3);
politie.add(p4);
politie.add(p5);
politie.add(p6);
// load walls onto the field
for (int x = 0; x < MAP_WIDTH; x++) {
for (int y = 0; y < MAP_HIGHT; y++) {
if (map[x][y] == 1) {
if (board.getObject(x, y) == null) {
board.addGameObject(new Wall(), x, y);
}
}
}
}
board.updateView();
}
// adds police on a random spot within the map
public void addPolice() {
int xSpot = randomX();
int ySpot = randomY();
if (gameBoard.getObject(xSpot, ySpot) == null && xSpot > 26
&& ySpot > 11) {
politie.add(new Police());
getGameBoard().addGameObject(politie.get(politie.size() - 1),
xSpot, ySpot);
} else {
addPolice();
}
}
// adds wiet on a random spot within the map
public void addWietToMap() {
int xSpot = randomX();
int ySpot = randomY();
if (gameBoard.getObject(xSpot, ySpot) == null && xSpot > 26
&& ySpot > 11) {
getGameBoard().addGameObject(new Weed(), xSpot, ySpot);
} else {
addWietToMap();
}
}
public int randomX() {
int randomX = (int) (Math.random() * MAP_WIDTH);
return randomX;
}
public int randomY() {
int randomY = (int) (Math.random() * MAP_HIGHT);
return randomY;
}
public void enterShop() {
activity.gotoShopView();
}
//resets the game
public void reset() {
activity.resetShop();
initGame();
}
/**
* adds money to total of players' money
* @param aantal amount of money to be added
*/
public void addMoney(int aantal) {
money += aantal;
gameBoard.updateView();
}
/**
* deducts money of total of players' money
* @param aantal amount of money to be deducted
*/
public void deductMoney(int aantal) {
money -= aantal;
gameBoard.updateView();
}
/**
* adds 50 points to score when player collides with weed object
*/
public void updateScoreWCWW() {
score += 50;
if (score > highscore) {
highscore = score;
}
gameBoard.updateView();
}
/**
* adds one weed to the weed variable
*/
public void addWiet() {
wiet++;
gameBoard.updateView();
}
/**
* deducts the weed according to the given value
* @param aantal
*/
public void deductWiet(int aantal) {
wiet -= aantal;
gameBoard.updateView();
}
/**
* @return total amount of money the player has
*/
public int getMoney() {
return money;
}
/**
* @return total score the player has
*/
public int getScore() {
return score;
}
/**
* @return high score
*/
public int getHighscore() {
return highscore;
}
/**
* @return total amount of wiet the player has
*/
public int getWiet() {
return wiet;
}
/**
* @return the player object
*/
public Player getPlayer() {
return player;
}
//Timer//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// police timer methods
public void startPoliceTimer() {
isPlaying = true;
// maakt een timer die de handler en de runnable oproept elke halve
// seconde.
policeTimer = new Timer();
policeTimer.schedule(new TimerTask() {
@Override
public void run() {
UpdateGUIPolice();
}
}, 0, 250);
}
private void stopPoliceTimer() {
policeTimer.cancel();
}
// player timer methods
public void startPlayerTimer(int speed) {
isPlaying = true;
// maakt een<SUF>
// seconde.
playerTimer = new Timer();
playerTimer.schedule(new TimerTask() {
@Override
public void run() {
UpdateGUIPlayer();
}
}, 0, speed);
}
private void stopPlayerTimer() {
playerTimer.cancel();
}
// De runnable voor de police die je aan de handler meegeeft.
final Runnable policeRunnable = new Runnable() {
public void run() {
for (int i = 0; i < politie.size(); i++) {
politie.get(i).onUpdate(gameBoard);
}
gameBoard.updateView();
}
};
// De runnable voor de player die je aan de handler meegeeft.
final Runnable playerRunnable = new Runnable() {
public void run() {
player.onUpdate(gameBoard);
}
};
// Methode waarmee je de runnable aan de handler meegeeft.
public void UpdateGUIPolice() {
POLICEHANDLER.post(policeRunnable);
}
public void UpdateGUIPlayer() {
PLAYERHANDLER.post(playerRunnable);
}
// kijken of player alive is
private boolean isPlayerAlive() {
if(player.getAliveState()){
return true;
}
return false;
}
// stops the timers
public void stopTimers() {
stopPlayerTimer();
stopPoliceTimer();
isPlaying = false;
}
public void update(Observable observable, Object data) {
if (!isPlayerAlive()) {
stopTimers();
activity.gotoGameOverScreen();
}
activity.updateMoneyLabels();
activity.updateScoreLabel();
activity.updateWietLabels();
activity.updateHighscoreLabel();
//Voegt politie toe als de speler een wiet object opppakt.
if (getScore() == politieScore) {
addPolice();
policeMusic();
addWietToMap();
politieScore = politieScore + 50;
}
}
//music for when the player picks up a wiet object
private void policeMusic() {
mPlayer = MediaPlayer.create(activity, R.raw.soundofdapolice);
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mPlayer.start();
}
}
| True | 2,530 | 19 | 2,996 | 19 | 2,913 | 14 | 2,996 | 19 | 3,517 | 21 | false | false | false | false | false | true |
3,815 | 35873_0 | import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
public class Stat {
public BufferedImage img; // Een plaatje van de Statistieken (in child gedefineerd)
public int x, y, breedte, hoogte; // De plaats en afmeting van de Enemy in px (in child gedefineerd)
public Stat(BufferedImage image, int x, int y, int breedte, int hoogte){
this.img = image;
this.x = x;
this.y = y;
this.breedte = breedte;
this.hoogte = hoogte;
}
public void teken(Graphics2D tekenObject){
tekenObject.drawImage(img, x, y, breedte, hoogte, null);
}
}
| niekbr/Mario | Game/src/Stat.java | 219 | // Een plaatje van de Statistieken (in child gedefineerd) | line_comment | nl | import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
public class Stat {
public BufferedImage img; // Een plaatje<SUF>
public int x, y, breedte, hoogte; // De plaats en afmeting van de Enemy in px (in child gedefineerd)
public Stat(BufferedImage image, int x, int y, int breedte, int hoogte){
this.img = image;
this.x = x;
this.y = y;
this.breedte = breedte;
this.hoogte = hoogte;
}
public void teken(Graphics2D tekenObject){
tekenObject.drawImage(img, x, y, breedte, hoogte, null);
}
}
| True | 171 | 19 | 212 | 19 | 190 | 15 | 212 | 19 | 224 | 18 | false | false | false | false | false | true |
3,809 | 28761_1 | package nl.han.ica.waterworld;
import nl.han.ica.OOPDProcessingEngineHAN.Dashboard.Dashboard;
import nl.han.ica.OOPDProcessingEngineHAN.Engine.GameEngine;
import nl.han.ica.OOPDProcessingEngineHAN.Objects.Sprite;
import nl.han.ica.OOPDProcessingEngineHAN.Persistence.FilePersistence;
import nl.han.ica.OOPDProcessingEngineHAN.Persistence.IPersistence;
import nl.han.ica.OOPDProcessingEngineHAN.Sound.Sound;
import nl.han.ica.OOPDProcessingEngineHAN.Tile.TileMap;
import nl.han.ica.OOPDProcessingEngineHAN.Tile.TileType;
import nl.han.ica.OOPDProcessingEngineHAN.View.EdgeFollowingViewport;
import nl.han.ica.OOPDProcessingEngineHAN.View.View;
import nl.han.ica.waterworld.tiles.BoardsTile;
import processing.core.PApplet;
/**
* @author Ralph Niels
*/
@SuppressWarnings("serial")
public class WaterWorld extends GameEngine {
private Sound backgroundSound;
private Sound bubblePopSound;
private TextObject dashboardText;
private BubbleSpawner bubbleSpawner;
private int bubblesPopped;
private IPersistence persistence;
private Player player;
public static void main(String[] args) {
PApplet.main(new String[]{"nl.han.ica.waterworld.WaterWorld"});
}
/**
* In deze methode worden de voor het spel
* noodzakelijke zaken geïnitialiseerd
*/
@Override
public void setupGame() {
int worldWidth=1204;
int worldHeight=903;
initializeSound();
createDashboard(worldWidth, 100);
initializeTileMap();
initializePersistence();
createObjects();
createBubbleSpawner();
createViewWithoutViewport(worldWidth, worldHeight);
//createViewWithViewport(worldWidth, worldHeight, 800, 800, 1.1f);
}
/**
* Creeërt de view zonder viewport
* @param screenWidth Breedte van het scherm
* @param screenHeight Hoogte van het scherm
*/
private void createViewWithoutViewport(int screenWidth, int screenHeight) {
View view = new View(screenWidth,screenHeight);
view.setBackground(loadImage("src/main/java/nl/han/ica/waterworld/media/background.jpg"));
setView(view);
size(screenWidth, screenHeight);
}
/**
* Creeërt de view met viewport
* @param worldWidth Totale breedte van de wereld
* @param worldHeight Totale hoogte van de wereld
* @param screenWidth Breedte van het scherm
* @param screenHeight Hoogte van het scherm
* @param zoomFactor Factor waarmee wordt ingezoomd
*/
private void createViewWithViewport(int worldWidth,int worldHeight,int screenWidth,int screenHeight,float zoomFactor) {
EdgeFollowingViewport viewPort = new EdgeFollowingViewport(player, (int)Math.ceil(screenWidth/zoomFactor),(int)Math.ceil(screenHeight/zoomFactor),0,0);
viewPort.setTolerance(50, 50, 50, 50);
View view = new View(viewPort, worldWidth,worldHeight);
setView(view);
size(screenWidth, screenHeight);
view.setBackground(loadImage("src/main/java/nl/han/ica/waterworld/media/background.jpg"));
}
/**
* Initialiseert geluid
*/
private void initializeSound() {
backgroundSound = new Sound(this, "src/main/java/nl/han/ica/waterworld/media/Waterworld.mp3");
backgroundSound.loop(-1);
bubblePopSound = new Sound(this, "src/main/java/nl/han/ica/waterworld/media/pop.mp3");
}
/**
* Maakt de spelobjecten aan
*/
private void createObjects() {
player = new Player(this);
addGameObject(player, 100, 100);
Swordfish sf=new Swordfish(this);
addGameObject(sf,200,200);
}
/**
* Maakt de spawner voor de bellen aan
*/
public void createBubbleSpawner() {
bubbleSpawner=new BubbleSpawner(this,bubblePopSound,2);
}
/**
* Maakt het dashboard aan
* @param dashboardWidth Gewenste breedte van dashboard
* @param dashboardHeight Gewenste hoogte van dashboard
*/
private void createDashboard(int dashboardWidth,int dashboardHeight) {
Dashboard dashboard = new Dashboard(0,0, dashboardWidth, dashboardHeight);
dashboardText=new TextObject("");
dashboard.addGameObject(dashboardText);
addDashboard(dashboard);
}
/**
* Initialiseert de opslag van de bellenteller
* en laadt indien mogelijk de eerder opgeslagen
* waarde
*/
private void initializePersistence() {
persistence = new FilePersistence("main/java/nl/han/ica/waterworld/media/bubblesPopped.txt");
if (persistence.fileExists()) {
bubblesPopped = Integer.parseInt(persistence.loadDataString());
refreshDasboardText();
}
}
/**
* Initialiseert de tilemap
*/
private void initializeTileMap() {
/* TILES */
Sprite boardsSprite = new Sprite("src/main/java/nl/han/ica/waterworld/media/boards.jpg");
TileType<BoardsTile> boardTileType = new TileType<>(BoardsTile.class, boardsSprite);
TileType[] tileTypes = { boardTileType };
int tileSize=50;
int tilesMap[][]={
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1, 0, 0, 0, 0,-1,0 , 0},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}
};
tileMap = new TileMap(tileSize, tileTypes, tilesMap);
}
@Override
public void update() {
}
/**
* Vernieuwt het dashboard
*/
private void refreshDasboardText() {
dashboardText.setText("Bubbles popped: "+bubblesPopped);
}
/**
* Verhoogt de teller voor het aantal
* geknapte bellen met 1
*/
public void increaseBubblesPopped() {
bubblesPopped++;
persistence.saveData(Integer.toString(bubblesPopped));
refreshDasboardText();
}
}
| nickhartjes/OOPD-GameEngine | src/main/java/nl/han/ica/waterworld/WaterWorld.java | 2,092 | /**
* In deze methode worden de voor het spel
* noodzakelijke zaken geïnitialiseerd
*/ | block_comment | nl | package nl.han.ica.waterworld;
import nl.han.ica.OOPDProcessingEngineHAN.Dashboard.Dashboard;
import nl.han.ica.OOPDProcessingEngineHAN.Engine.GameEngine;
import nl.han.ica.OOPDProcessingEngineHAN.Objects.Sprite;
import nl.han.ica.OOPDProcessingEngineHAN.Persistence.FilePersistence;
import nl.han.ica.OOPDProcessingEngineHAN.Persistence.IPersistence;
import nl.han.ica.OOPDProcessingEngineHAN.Sound.Sound;
import nl.han.ica.OOPDProcessingEngineHAN.Tile.TileMap;
import nl.han.ica.OOPDProcessingEngineHAN.Tile.TileType;
import nl.han.ica.OOPDProcessingEngineHAN.View.EdgeFollowingViewport;
import nl.han.ica.OOPDProcessingEngineHAN.View.View;
import nl.han.ica.waterworld.tiles.BoardsTile;
import processing.core.PApplet;
/**
* @author Ralph Niels
*/
@SuppressWarnings("serial")
public class WaterWorld extends GameEngine {
private Sound backgroundSound;
private Sound bubblePopSound;
private TextObject dashboardText;
private BubbleSpawner bubbleSpawner;
private int bubblesPopped;
private IPersistence persistence;
private Player player;
public static void main(String[] args) {
PApplet.main(new String[]{"nl.han.ica.waterworld.WaterWorld"});
}
/**
* In deze methode<SUF>*/
@Override
public void setupGame() {
int worldWidth=1204;
int worldHeight=903;
initializeSound();
createDashboard(worldWidth, 100);
initializeTileMap();
initializePersistence();
createObjects();
createBubbleSpawner();
createViewWithoutViewport(worldWidth, worldHeight);
//createViewWithViewport(worldWidth, worldHeight, 800, 800, 1.1f);
}
/**
* Creeërt de view zonder viewport
* @param screenWidth Breedte van het scherm
* @param screenHeight Hoogte van het scherm
*/
private void createViewWithoutViewport(int screenWidth, int screenHeight) {
View view = new View(screenWidth,screenHeight);
view.setBackground(loadImage("src/main/java/nl/han/ica/waterworld/media/background.jpg"));
setView(view);
size(screenWidth, screenHeight);
}
/**
* Creeërt de view met viewport
* @param worldWidth Totale breedte van de wereld
* @param worldHeight Totale hoogte van de wereld
* @param screenWidth Breedte van het scherm
* @param screenHeight Hoogte van het scherm
* @param zoomFactor Factor waarmee wordt ingezoomd
*/
private void createViewWithViewport(int worldWidth,int worldHeight,int screenWidth,int screenHeight,float zoomFactor) {
EdgeFollowingViewport viewPort = new EdgeFollowingViewport(player, (int)Math.ceil(screenWidth/zoomFactor),(int)Math.ceil(screenHeight/zoomFactor),0,0);
viewPort.setTolerance(50, 50, 50, 50);
View view = new View(viewPort, worldWidth,worldHeight);
setView(view);
size(screenWidth, screenHeight);
view.setBackground(loadImage("src/main/java/nl/han/ica/waterworld/media/background.jpg"));
}
/**
* Initialiseert geluid
*/
private void initializeSound() {
backgroundSound = new Sound(this, "src/main/java/nl/han/ica/waterworld/media/Waterworld.mp3");
backgroundSound.loop(-1);
bubblePopSound = new Sound(this, "src/main/java/nl/han/ica/waterworld/media/pop.mp3");
}
/**
* Maakt de spelobjecten aan
*/
private void createObjects() {
player = new Player(this);
addGameObject(player, 100, 100);
Swordfish sf=new Swordfish(this);
addGameObject(sf,200,200);
}
/**
* Maakt de spawner voor de bellen aan
*/
public void createBubbleSpawner() {
bubbleSpawner=new BubbleSpawner(this,bubblePopSound,2);
}
/**
* Maakt het dashboard aan
* @param dashboardWidth Gewenste breedte van dashboard
* @param dashboardHeight Gewenste hoogte van dashboard
*/
private void createDashboard(int dashboardWidth,int dashboardHeight) {
Dashboard dashboard = new Dashboard(0,0, dashboardWidth, dashboardHeight);
dashboardText=new TextObject("");
dashboard.addGameObject(dashboardText);
addDashboard(dashboard);
}
/**
* Initialiseert de opslag van de bellenteller
* en laadt indien mogelijk de eerder opgeslagen
* waarde
*/
private void initializePersistence() {
persistence = new FilePersistence("main/java/nl/han/ica/waterworld/media/bubblesPopped.txt");
if (persistence.fileExists()) {
bubblesPopped = Integer.parseInt(persistence.loadDataString());
refreshDasboardText();
}
}
/**
* Initialiseert de tilemap
*/
private void initializeTileMap() {
/* TILES */
Sprite boardsSprite = new Sprite("src/main/java/nl/han/ica/waterworld/media/boards.jpg");
TileType<BoardsTile> boardTileType = new TileType<>(BoardsTile.class, boardsSprite);
TileType[] tileTypes = { boardTileType };
int tileSize=50;
int tilesMap[][]={
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1, 0, 0, 0, 0,-1,0 , 0},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}
};
tileMap = new TileMap(tileSize, tileTypes, tilesMap);
}
@Override
public void update() {
}
/**
* Vernieuwt het dashboard
*/
private void refreshDasboardText() {
dashboardText.setText("Bubbles popped: "+bubblesPopped);
}
/**
* Verhoogt de teller voor het aantal
* geknapte bellen met 1
*/
public void increaseBubblesPopped() {
bubblesPopped++;
persistence.saveData(Integer.toString(bubblesPopped));
refreshDasboardText();
}
}
| True | 1,682 | 30 | 1,844 | 32 | 1,867 | 25 | 1,845 | 32 | 2,153 | 32 | false | false | false | false | false | true |
4,793 | 173429_20 | package com.smart.om.rest.base;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.googlecode.jsonplugin.JSONException;
import com.googlecode.jsonplugin.JSONUtil;
import com.smart.om.util.Const;
/**
* 封装调研设备接口
* @author langyuk
*
*/
public class BaseController {
private static final Logger logger = Logger.getLogger(BaseController.class);
/**
* 返回预期结果
*/
private static final int RESULT_CODE_SUCCESS = 0;
/**
* 返回非预期结果
*/
private static final int RESULT_CODE_ERROR = 1;
/**
* 服务端返回json的键名:结果代码
*/
private static final String KEY_RESULT_CODE = "RESULT_CODE";
/**
* 服务端返回json的键名:结果数据
*/
private static final String KEY_RESULT_DATA = "RESULT_DATA";
/**
* 调用外部接口
* @param param
* @return
*/
public String extInf(String param,String requestMethod){
String result = "";
Map<String,String> map = new HashMap<String,String>();
String errInfo = "success";
String rTime="";
String str = "";
try{
long startTime = System.currentTimeMillis(); //请求起始时间_毫秒
URL url = new URL(Const.DEVICE_URL + param);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("contentType", "utf-8");
connection.setRequestMethod(requestMethod); //请求类型 POST or GET
InputStream inStream = connection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
//BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
long endTime = System.currentTimeMillis(); //请求结束时间_毫秒
String temp = "";
while((temp = in.readLine()) != null){
str = str + temp;
}
rTime = String.valueOf(endTime - startTime);
}
catch(Exception e){
errInfo = "error";
e.printStackTrace();
}
result = str;
return result;
}
/**
* 调用外部接口POST
* @param param
* @return
*/
public String extInf(String urlStr,String param,String requestMethod){
String result = "";
Map<String,String> map = new HashMap<String,String>();
String errInfo = "success";
try{
long startTime = System.currentTimeMillis(); //请求起始时间_毫秒
URL url = new URL(Const.DEVICE_URL+urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");//请求类型 POST or GET
connection.setDoInput(true);
connection.setDoOutput(true);//如果通过post提交数据,必须设置允许对外输出数据
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
osw.write(param);
osw.flush();
osw.close();
if(connection.getResponseCode() ==200){
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result += inputLine;
}
in.close();
}
}
catch(Exception e){
errInfo = "error";
e.printStackTrace();
}
// result = str;
return result;
}
/** 返回成功时,把Map转换成String **/
protected String toResultJsonSuccess(Object resultData) {
return this.toResultJson(RESULT_CODE_SUCCESS, resultData);
}
/** 把Map转换成String **/
protected String toResultJson(int resultCode, Object resultData) {
try {
Map<Object, Object> map = new HashMap<Object, Object>();
map.put(KEY_RESULT_CODE, resultCode);
map.put(KEY_RESULT_DATA, resultData);
return JSONUtil.serialize(map);
} catch (JSONException ex) {
return "{\"" + KEY_RESULT_CODE + "\":" + RESULT_CODE_ERROR + ",\""
+ KEY_RESULT_DATA + "\":\"转换为Json异常\"}";
}
}
/** 获得服务验证令牌 **/
public String getAccessToken(){
BaseController baseController = new BaseController();
String loginStr = baseController.extInf(Const.DEVICE_LOGIN,Const.REQUEST_METHOD_GET);
JSONObject jsonObject=JSONObject.fromObject(loginStr);
String accessKoken = jsonObject.getString("access_token");
return accessKoken;
}
/** 物料信息查询 **/
public String getFileName(String name,String msg){
String result = "";
StringBuffer param = new StringBuffer();
param.append("/PFPROWebAPI/api/JuicerApi/GetMediaInfo?");
param.append("pageIndex=1&pageSize=32767&");
param.append("access_token=" + this.getAccessToken());
param.append("&name=").append(name);
String mediaInfo = this.extInf(param.toString(), Const.REQUEST_METHOD_GET);
if(StringUtils.isNotBlank(mediaInfo)){
JSONObject jsonObject = JSONObject.fromObject(mediaInfo);
String mediaInfos = jsonObject.getString("MediaInfos");
System.out.println(mediaInfos);
if(StringUtils.isNotBlank(mediaInfos)){
JSONArray jsonArray = JSONArray.fromObject(mediaInfos);
if(jsonArray.size() > 0){
JSONObject json = jsonArray.getJSONObject(0);
result = json.getString(msg);
}
}
}
return result;
}
/** 广告信息查询 **/
public String getAdvertMsg(String deviceNo,String msg){
String result = "";
StringBuffer param = new StringBuffer();
param.append("/PFPROWebAPI/api/JuicerApi/GetAdvertisingInfos?");
param.append("pageIndex=1&pageSize=10&StartTime=&EndTime=&");
param.append("access_token=" + this.getAccessToken());
param.append("&JuicerCode=").append(deviceNo);
String advertInfo = this.extInf(param.toString(), Const.REQUEST_METHOD_GET);
if(StringUtils.isNotBlank(advertInfo)){
JSONObject jsonObject = JSONObject.fromObject(advertInfo);
String mediaInfos = jsonObject.getString("Advertisings");
if(StringUtils.isNotBlank(mediaInfos)){
JSONArray jsonArray = JSONArray.fromObject(mediaInfos);
if(jsonArray.size() > 0){
JSONObject json = jsonArray.getJSONObject(0);
result = json.getString(msg);
}
}
}
return result;
}
/** 创建广告 **/
public void createAdvert(String startTime,String endTime,String juicerCode,String name){
System.out.println("name:" + name);
String url = this.getFileName(name, "Url");
System.out.println("url:" + url);
if(StringUtils.isNotBlank(url)){
String param = Const.ACCESS_TOKEN + "=" + this.getAccessToken() + "&" + Const.START_TIME + "=" + startTime +
"&" + Const.END_TIME + "=" + endTime + "&" + Const.JUICER_CODE + "=" + juicerCode + "&" + Const.DOWN_LOAD_URL + "=" + url;
this.extInf("PFPROWebAPI/api/JuicerApi/AddAdvertising", param, Const.REQUEST_METHOD_POST);
}
}
/** 广告删除 **/
public void delAdvert(int code){
String param = Const.ACCESS_TOKEN + "=" + this.getAccessToken() + "&" + Const.CODE + "=" + code;
this.extInf("PFPROWebAPI/api/JuicerApi/DelAdvertising", param, Const.REQUEST_METHOD_POST);
}
/** 删除物料 **/
public void delFile(int code){
String param = Const.ACCESS_TOKEN + "=" + this.getAccessToken() + "&" + Const.CODE + "=" + code;
this.extInf("PFPROWebAPI/api/JuicerApi/DelMediaInfo", param, Const.REQUEST_METHOD_POST);
}
public static void main(String[] args) {
BaseController baseController = new BaseController();
String accessKoken = baseController.getAccessToken();
// StringBuffer param = new StringBuffer();
// String param = "Juicer?access_token="+accessKoken;
// String deviceList = baseController.extInf(param, Const.REQUEST_METHOD_GET);
// param.append("/PFPROWebAPI/api/JuicerApi/GetMediaInfo?");
// param.append("pageIndex=1&pageSize=32767&name=测试接口&");
// param.append("access_token=" + accessKoken);
// String mediaInfo = baseController.extInf(param.toString(), Const.REQUEST_METHOD_GET);
// JSONObject jsonObject = JSONObject.fromObject(mediaInfo);
// String ss = jsonObject.getString("MediaInfos");
// JSONArray jsonArray = JSONArray.fromObject(ss);
// JSONObject jsonObject2 = jsonArray.getJSONObject(0);
// String s = jsonObject2.getString("Url");
// logger.info(s);
// logger.info(mediaInfo);
// String s = "接口测试";
// String url = baseController.getFileName("接口测试2","Url");
// System.out.println(url);
// String code = baseController.getAdvertMsg("0000027", "Code");
// System.out.println(code);
// String param = Const.ACCESS_TOKEN + "=" + baseController.getAccessToken() + "&" + Const.CODE + "=" + 97;
// baseController.extInf("PFPROWebAPI/api/JuicerApi/DelAdvertising", param, Const.REQUEST_METHOD_POST);
// baseController.delAdvert(98);
// baseController.delFile(62);
baseController.createAdvert("2016-1-18 9:13", "2016-1-19 9:13", "0000027", "测试接口2");
}
}
| yujuekong/OM | src/main/com/smart/om/rest/base/BaseController.java | 3,017 | // JSONObject jsonObject2 = jsonArray.getJSONObject(0); | line_comment | nl | package com.smart.om.rest.base;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.googlecode.jsonplugin.JSONException;
import com.googlecode.jsonplugin.JSONUtil;
import com.smart.om.util.Const;
/**
* 封装调研设备接口
* @author langyuk
*
*/
public class BaseController {
private static final Logger logger = Logger.getLogger(BaseController.class);
/**
* 返回预期结果
*/
private static final int RESULT_CODE_SUCCESS = 0;
/**
* 返回非预期结果
*/
private static final int RESULT_CODE_ERROR = 1;
/**
* 服务端返回json的键名:结果代码
*/
private static final String KEY_RESULT_CODE = "RESULT_CODE";
/**
* 服务端返回json的键名:结果数据
*/
private static final String KEY_RESULT_DATA = "RESULT_DATA";
/**
* 调用外部接口
* @param param
* @return
*/
public String extInf(String param,String requestMethod){
String result = "";
Map<String,String> map = new HashMap<String,String>();
String errInfo = "success";
String rTime="";
String str = "";
try{
long startTime = System.currentTimeMillis(); //请求起始时间_毫秒
URL url = new URL(Const.DEVICE_URL + param);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("contentType", "utf-8");
connection.setRequestMethod(requestMethod); //请求类型 POST or GET
InputStream inStream = connection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
//BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
long endTime = System.currentTimeMillis(); //请求结束时间_毫秒
String temp = "";
while((temp = in.readLine()) != null){
str = str + temp;
}
rTime = String.valueOf(endTime - startTime);
}
catch(Exception e){
errInfo = "error";
e.printStackTrace();
}
result = str;
return result;
}
/**
* 调用外部接口POST
* @param param
* @return
*/
public String extInf(String urlStr,String param,String requestMethod){
String result = "";
Map<String,String> map = new HashMap<String,String>();
String errInfo = "success";
try{
long startTime = System.currentTimeMillis(); //请求起始时间_毫秒
URL url = new URL(Const.DEVICE_URL+urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");//请求类型 POST or GET
connection.setDoInput(true);
connection.setDoOutput(true);//如果通过post提交数据,必须设置允许对外输出数据
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
osw.write(param);
osw.flush();
osw.close();
if(connection.getResponseCode() ==200){
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result += inputLine;
}
in.close();
}
}
catch(Exception e){
errInfo = "error";
e.printStackTrace();
}
// result = str;
return result;
}
/** 返回成功时,把Map转换成String **/
protected String toResultJsonSuccess(Object resultData) {
return this.toResultJson(RESULT_CODE_SUCCESS, resultData);
}
/** 把Map转换成String **/
protected String toResultJson(int resultCode, Object resultData) {
try {
Map<Object, Object> map = new HashMap<Object, Object>();
map.put(KEY_RESULT_CODE, resultCode);
map.put(KEY_RESULT_DATA, resultData);
return JSONUtil.serialize(map);
} catch (JSONException ex) {
return "{\"" + KEY_RESULT_CODE + "\":" + RESULT_CODE_ERROR + ",\""
+ KEY_RESULT_DATA + "\":\"转换为Json异常\"}";
}
}
/** 获得服务验证令牌 **/
public String getAccessToken(){
BaseController baseController = new BaseController();
String loginStr = baseController.extInf(Const.DEVICE_LOGIN,Const.REQUEST_METHOD_GET);
JSONObject jsonObject=JSONObject.fromObject(loginStr);
String accessKoken = jsonObject.getString("access_token");
return accessKoken;
}
/** 物料信息查询 **/
public String getFileName(String name,String msg){
String result = "";
StringBuffer param = new StringBuffer();
param.append("/PFPROWebAPI/api/JuicerApi/GetMediaInfo?");
param.append("pageIndex=1&pageSize=32767&");
param.append("access_token=" + this.getAccessToken());
param.append("&name=").append(name);
String mediaInfo = this.extInf(param.toString(), Const.REQUEST_METHOD_GET);
if(StringUtils.isNotBlank(mediaInfo)){
JSONObject jsonObject = JSONObject.fromObject(mediaInfo);
String mediaInfos = jsonObject.getString("MediaInfos");
System.out.println(mediaInfos);
if(StringUtils.isNotBlank(mediaInfos)){
JSONArray jsonArray = JSONArray.fromObject(mediaInfos);
if(jsonArray.size() > 0){
JSONObject json = jsonArray.getJSONObject(0);
result = json.getString(msg);
}
}
}
return result;
}
/** 广告信息查询 **/
public String getAdvertMsg(String deviceNo,String msg){
String result = "";
StringBuffer param = new StringBuffer();
param.append("/PFPROWebAPI/api/JuicerApi/GetAdvertisingInfos?");
param.append("pageIndex=1&pageSize=10&StartTime=&EndTime=&");
param.append("access_token=" + this.getAccessToken());
param.append("&JuicerCode=").append(deviceNo);
String advertInfo = this.extInf(param.toString(), Const.REQUEST_METHOD_GET);
if(StringUtils.isNotBlank(advertInfo)){
JSONObject jsonObject = JSONObject.fromObject(advertInfo);
String mediaInfos = jsonObject.getString("Advertisings");
if(StringUtils.isNotBlank(mediaInfos)){
JSONArray jsonArray = JSONArray.fromObject(mediaInfos);
if(jsonArray.size() > 0){
JSONObject json = jsonArray.getJSONObject(0);
result = json.getString(msg);
}
}
}
return result;
}
/** 创建广告 **/
public void createAdvert(String startTime,String endTime,String juicerCode,String name){
System.out.println("name:" + name);
String url = this.getFileName(name, "Url");
System.out.println("url:" + url);
if(StringUtils.isNotBlank(url)){
String param = Const.ACCESS_TOKEN + "=" + this.getAccessToken() + "&" + Const.START_TIME + "=" + startTime +
"&" + Const.END_TIME + "=" + endTime + "&" + Const.JUICER_CODE + "=" + juicerCode + "&" + Const.DOWN_LOAD_URL + "=" + url;
this.extInf("PFPROWebAPI/api/JuicerApi/AddAdvertising", param, Const.REQUEST_METHOD_POST);
}
}
/** 广告删除 **/
public void delAdvert(int code){
String param = Const.ACCESS_TOKEN + "=" + this.getAccessToken() + "&" + Const.CODE + "=" + code;
this.extInf("PFPROWebAPI/api/JuicerApi/DelAdvertising", param, Const.REQUEST_METHOD_POST);
}
/** 删除物料 **/
public void delFile(int code){
String param = Const.ACCESS_TOKEN + "=" + this.getAccessToken() + "&" + Const.CODE + "=" + code;
this.extInf("PFPROWebAPI/api/JuicerApi/DelMediaInfo", param, Const.REQUEST_METHOD_POST);
}
public static void main(String[] args) {
BaseController baseController = new BaseController();
String accessKoken = baseController.getAccessToken();
// StringBuffer param = new StringBuffer();
// String param = "Juicer?access_token="+accessKoken;
// String deviceList = baseController.extInf(param, Const.REQUEST_METHOD_GET);
// param.append("/PFPROWebAPI/api/JuicerApi/GetMediaInfo?");
// param.append("pageIndex=1&pageSize=32767&name=测试接口&");
// param.append("access_token=" + accessKoken);
// String mediaInfo = baseController.extInf(param.toString(), Const.REQUEST_METHOD_GET);
// JSONObject jsonObject = JSONObject.fromObject(mediaInfo);
// String ss = jsonObject.getString("MediaInfos");
// JSONArray jsonArray = JSONArray.fromObject(ss);
// JSONObject jsonObject2<SUF>
// String s = jsonObject2.getString("Url");
// logger.info(s);
// logger.info(mediaInfo);
// String s = "接口测试";
// String url = baseController.getFileName("接口测试2","Url");
// System.out.println(url);
// String code = baseController.getAdvertMsg("0000027", "Code");
// System.out.println(code);
// String param = Const.ACCESS_TOKEN + "=" + baseController.getAccessToken() + "&" + Const.CODE + "=" + 97;
// baseController.extInf("PFPROWebAPI/api/JuicerApi/DelAdvertising", param, Const.REQUEST_METHOD_POST);
// baseController.delAdvert(98);
// baseController.delFile(62);
baseController.createAdvert("2016-1-18 9:13", "2016-1-19 9:13", "0000027", "测试接口2");
}
}
| False | 2,161 | 11 | 2,695 | 14 | 2,683 | 12 | 2,695 | 14 | 3,364 | 18 | false | false | false | false | false | true |
2,971 | 27355_3 | package nl.Novi;
// Importeer de Scanner class uit de java.util package, wat een basis onderdeel is van je jdk
// We hoeven Translator niet te importeren, omdat deze in hetzelfde package staat als Main, namelijk "nl.Novi"
import java.util.Scanner;
// Definieer de Main class, waarin we onze applicatie beginnen.
public class Main {
//Definieer de main methode, de voordeur van onze applicatie, waarmee we onze applicatie op starten.
public static void main(String[] args) {
// Een array van integers.
Integer[] numeric = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
// Een array van Strings.
String[] alphabetic = {"een", "twee", "drie", "vier", "vijf", "zes", "zeven", "acht", "negen", "nul"};
// We instatieren een nieuwe Translator. De Translator klasse hebben we zelf gemaakt en staat in de nl.Novi package.
// Met het new-keyword, roepen we de constructor van Translator aan.
// Deze vraagt als parameters om een array van integers en een array van Strings.
Translator translator = new Translator(alphabetic, numeric);
// We instantieren hier een nieuwe Scanner.
// We geven als parameter "System.in", dit betekent dat we de input via de terminal krijgen.
Scanner scanner = new Scanner(System.in);
// We maken een boolean (primitive) variabele genaamd "play" en geven die de waarde "true".
boolean play = true;
// We maken een String variabele genaamd "ongeldig" en geven die de waarde "ongeldige invoer".
String ongeldig = "ongeldige invoer";
// zolang play "true" is, voeren we de volgende code uit.
while (play) {
// Print een bericht voor de gebruiker, zodat deze weet wat hij/zij moet doen.
System.out.println("Type 'x' om te stoppen \nType 'v' om te vertalen");
// Lees de input van de gebruiker en sla dat op als een String "input".
String input = scanner.nextLine();
if (input.equals("x")) {
// Als de input van de gebruiker "x" is, dan zetten we "play" naar false, waardoor de while loop niet langer door gaat.
play = false;
} else if (input.equals("v")) {
// Als de input van de gebruiker "v" is, dan voeren we onderstaande code uit.
// We printen eerst weer een instructie voorde gebruiker.
System.out.println("Type een cijfer in van 0 t/m 9");
// Vervolgens lezen we het cijfer dat de gebruiker intypt en slaan we dat op.
int number = scanner.nextInt();
// We laten de scanner hier nog eens een lege regel lezen, omdat nextInt() van zichzelf niet op een nieuwe regel eindigd.
// We krijgen later problemen als we dit niet doen.
scanner.nextLine();
if (number < 10 && number >= 0) {
// Als het nummer onder de 10 is en groter of gelijk aan 0, dan vertalen we het met de translate methode en printen we het resultaat
String result = translator.translate(number);
System.out.println("De vertaling van " + number + " is " + result);
} else {
// Als het resultaat hoger dan 10 of lager dan 0 is, dan printen we het "ongeldig" bericht.
System.out.println(ongeldig);
}
} else {
// Als de gebruiker is anders dan "x" of "v" intypt, dan printen de het "ongeldig" bericht.
System.out.println(ongeldig);
}
}
}
}
| hogeschoolnovi/backend-java-collecties-lussen-uitwerkingen | src/nl/Novi/Main.java | 1,041 | //Definieer de main methode, de voordeur van onze applicatie, waarmee we onze applicatie op starten. | line_comment | nl | package nl.Novi;
// Importeer de Scanner class uit de java.util package, wat een basis onderdeel is van je jdk
// We hoeven Translator niet te importeren, omdat deze in hetzelfde package staat als Main, namelijk "nl.Novi"
import java.util.Scanner;
// Definieer de Main class, waarin we onze applicatie beginnen.
public class Main {
//Definieer de<SUF>
public static void main(String[] args) {
// Een array van integers.
Integer[] numeric = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
// Een array van Strings.
String[] alphabetic = {"een", "twee", "drie", "vier", "vijf", "zes", "zeven", "acht", "negen", "nul"};
// We instatieren een nieuwe Translator. De Translator klasse hebben we zelf gemaakt en staat in de nl.Novi package.
// Met het new-keyword, roepen we de constructor van Translator aan.
// Deze vraagt als parameters om een array van integers en een array van Strings.
Translator translator = new Translator(alphabetic, numeric);
// We instantieren hier een nieuwe Scanner.
// We geven als parameter "System.in", dit betekent dat we de input via de terminal krijgen.
Scanner scanner = new Scanner(System.in);
// We maken een boolean (primitive) variabele genaamd "play" en geven die de waarde "true".
boolean play = true;
// We maken een String variabele genaamd "ongeldig" en geven die de waarde "ongeldige invoer".
String ongeldig = "ongeldige invoer";
// zolang play "true" is, voeren we de volgende code uit.
while (play) {
// Print een bericht voor de gebruiker, zodat deze weet wat hij/zij moet doen.
System.out.println("Type 'x' om te stoppen \nType 'v' om te vertalen");
// Lees de input van de gebruiker en sla dat op als een String "input".
String input = scanner.nextLine();
if (input.equals("x")) {
// Als de input van de gebruiker "x" is, dan zetten we "play" naar false, waardoor de while loop niet langer door gaat.
play = false;
} else if (input.equals("v")) {
// Als de input van de gebruiker "v" is, dan voeren we onderstaande code uit.
// We printen eerst weer een instructie voorde gebruiker.
System.out.println("Type een cijfer in van 0 t/m 9");
// Vervolgens lezen we het cijfer dat de gebruiker intypt en slaan we dat op.
int number = scanner.nextInt();
// We laten de scanner hier nog eens een lege regel lezen, omdat nextInt() van zichzelf niet op een nieuwe regel eindigd.
// We krijgen later problemen als we dit niet doen.
scanner.nextLine();
if (number < 10 && number >= 0) {
// Als het nummer onder de 10 is en groter of gelijk aan 0, dan vertalen we het met de translate methode en printen we het resultaat
String result = translator.translate(number);
System.out.println("De vertaling van " + number + " is " + result);
} else {
// Als het resultaat hoger dan 10 of lager dan 0 is, dan printen we het "ongeldig" bericht.
System.out.println(ongeldig);
}
} else {
// Als de gebruiker is anders dan "x" of "v" intypt, dan printen de het "ongeldig" bericht.
System.out.println(ongeldig);
}
}
}
}
| True | 902 | 30 | 996 | 31 | 920 | 24 | 996 | 31 | 1,062 | 32 | false | false | false | false | false | true |
579 | 45572_20 | /* (c) 2014 Open Source Geospatial Foundation - all rights reserved
* (c) 2001 - 2013 OpenPlans
* This code is licensed under the GPL 2.0 license, available at the root
* application directory.
*/
package org.geoserver.kml;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.geoserver.ows.URLMangler.URLType;
import org.geoserver.ows.util.ResponseUtils;
import org.geoserver.wms.GetMapRequest;
import org.geoserver.wms.MapLayerInfo;
import org.geoserver.wms.WMS;
import org.geoserver.wms.WMSMapContent;
import org.geoserver.wms.WMSRequests;
import org.geotools.data.FeatureSource;
import org.geotools.data.Query;
import org.geotools.feature.FeatureCollection;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.map.Layer;
import org.geotools.referencing.CRS;
import org.geotools.styling.Style;
import org.geotools.xml.transform.TransformerBase;
import org.geotools.xml.transform.Translator;
import org.opengis.filter.Filter;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.xml.sax.ContentHandler;
import com.vividsolutions.jts.geom.Envelope;
/**
* Encodes a KML document contianing a network link.
* <p>
* This transformer transforms a {@link GetMapRequest} object.
* </p>
*
* @author Justin Deoliveira, The Open Planning Project, [email protected]
*
*/
public class KMLNetworkLinkTransformer extends TransformerBase {
/**
* logger
*/
static Logger LOGGER = org.geotools.util.logging.Logging.getLogger("org.geoserver.kml");
/**
* flag controlling whether the network link should be a super overlay.
*/
boolean encodeAsRegion = false;
/**
* flag controlling whether the network link should be a direct GWC one when possible
*/
boolean cachedMode = false;
private boolean standalone;
/**
* @see #setInline
*/
private boolean inline;
/**
* The map context
*/
private final WMSMapContent mapContent;
private WMS wms;
public KMLNetworkLinkTransformer(WMS wms, WMSMapContent mapContent) {
this.wms = wms;
this.mapContent = mapContent;
standalone = true;
}
public void setStandalone(boolean standalone){
this.standalone = standalone;
}
public boolean isStandalone(){
return standalone;
}
/**
* @return {@code true} if the document is to be generated inline (i.e. without an enclosing
* Folder element). Defaults to {@code false}
*/
public boolean isInline() {
return inline;
}
/**
* @param inline if {@code true} network links won't be enclosed inside a Folder element
*/
public void setInline(boolean inline) {
this.inline = inline;
}
public void setCachedMode(boolean cachedMode) {
this.cachedMode = cachedMode;
}
public Translator createTranslator(ContentHandler handler) {
return new KMLNetworkLinkTranslator(handler);
}
public void setEncodeAsRegion(boolean encodeAsRegion) {
this.encodeAsRegion = encodeAsRegion;
}
class KMLNetworkLinkTranslator extends TranslatorSupport {
public KMLNetworkLinkTranslator(ContentHandler contentHandler) {
super(contentHandler, null, null);
}
public void encode(Object o) throws IllegalArgumentException {
final WMSMapContent context = (WMSMapContent) o;
final GetMapRequest request = context.getRequest();
// restore target mime type for the network links
if (NetworkLinkMapOutputFormat.KML_MIME_TYPE.equals(request.getFormat())) {
request.setFormat(KMLMapOutputFormat.MIME_TYPE);
} else {
request.setFormat(KMZMapOutputFormat.MIME_TYPE);
}
if(standalone){
start("kml");
}
if (!inline) {
start("Folder");
if (standalone) {
String kmltitle = (String) mapContent.getRequest().getFormatOptions().get("kmltitle");
element("name", (kmltitle != null ? kmltitle : ""));
}
}
final List<MapLayerInfo> layers = request.getLayers();
final KMLLookAt lookAt = parseLookAtOptions(request);
ReferencedEnvelope aggregatedBounds;
List<ReferencedEnvelope> layerBounds;
layerBounds = new ArrayList<ReferencedEnvelope>(layers.size());
aggregatedBounds = computePerLayerQueryBounds(context, layerBounds, lookAt);
if (encodeAsRegion) {
encodeAsSuperOverlay(request, lookAt, layerBounds);
} else {
encodeAsOverlay(request, lookAt, layerBounds);
}
// look at
encodeLookAt(aggregatedBounds, lookAt);
if (!inline) {
end("Folder");
}
if (standalone) {
end("kml");
}
}
/**
* @return the aggregated bounds for all the requested layers, taking into account whether
* the whole layer or filtered bounds is used for each layer
*/
private ReferencedEnvelope computePerLayerQueryBounds(final WMSMapContent context,
final List<ReferencedEnvelope> target, final KMLLookAt lookAt) {
// no need to compute queried bounds if request explicitly specified the view area
final boolean computeQueryBounds = lookAt.getLookAt() == null;
ReferencedEnvelope aggregatedBounds;
try {
boolean longitudeFirst = true;
aggregatedBounds = new ReferencedEnvelope(CRS.decode("EPSG:4326", longitudeFirst));
} catch (Exception e) {
throw new RuntimeException(e);
}
aggregatedBounds.setToNull();
final List<Layer> mapLayers = context.layers();
final List<MapLayerInfo> layerInfos = context.getRequest().getLayers();
for (int i = 0; i < mapLayers.size(); i++) {
final Layer Layer = mapLayers.get(i);
final MapLayerInfo layerInfo = layerInfos.get(i);
ReferencedEnvelope layerLatLongBbox;
layerLatLongBbox = computeLayerBounds(Layer, layerInfo, computeQueryBounds);
try {
layerLatLongBbox = layerLatLongBbox.transform(aggregatedBounds.getCoordinateReferenceSystem(), true);
} catch (Exception e) {
throw new RuntimeException(e);
}
target.add(layerLatLongBbox);
aggregatedBounds.expandToInclude(layerLatLongBbox);
}
return aggregatedBounds;
}
@SuppressWarnings("rawtypes")
private ReferencedEnvelope computeLayerBounds(Layer layer, MapLayerInfo layerInfo,
boolean computeQueryBounds) {
final Query layerQuery = layer.getQuery();
// make sure if layer is gonna be filtered, the resulting bounds are obtained instead of
// the whole bounds
final Filter filter = layerQuery.getFilter();
if (layerQuery.getFilter() == null || Filter.INCLUDE.equals(filter)) {
computeQueryBounds = false;
}
if (!computeQueryBounds && !layerQuery.isMaxFeaturesUnlimited()) {
computeQueryBounds = true;
}
ReferencedEnvelope layerLatLongBbox = null;
if (computeQueryBounds) {
FeatureSource featureSource = layer.getFeatureSource();
try {
CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:4326");
FeatureCollection features = featureSource.getFeatures(layerQuery);
layerLatLongBbox = features.getBounds();
layerLatLongBbox = layerLatLongBbox.transform(targetCRS, true);
} catch (Exception e) {
LOGGER.info("Error computing bounds for " + featureSource.getName() + " with "
+ layerQuery);
}
}
if (layerLatLongBbox == null) {
try {
layerLatLongBbox = layerInfo.getLatLongBoundingBox();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return layerLatLongBbox;
}
@SuppressWarnings("unchecked")
private KMLLookAt parseLookAtOptions(final GetMapRequest request) {
final KMLLookAt lookAt;
if (request.getFormatOptions() == null) {
// use a default LookAt properties
lookAt = new KMLLookAt();
} else {
// use the requested LookAt properties
Map<String, Object> formatOptions;
formatOptions = new HashMap<String, Object>(request.getFormatOptions());
lookAt = new KMLLookAt(formatOptions);
/*
* remove LOOKATBBOX and LOOKATGEOM from format options so KMLUtils.getMapRequest
* does not include them in the network links, but do include the other options such
* as tilt, range, etc.
*/
request.getFormatOptions().remove("LOOKATBBOX");
request.getFormatOptions().remove("LOOKATGEOM");
}
return lookAt;
}
protected void encodeAsSuperOverlay(GetMapRequest request, KMLLookAt lookAt,
List<ReferencedEnvelope> layerBounds) {
List<MapLayerInfo> layers = request.getLayers();
List<Style> styles = request.getStyles();
for (int i = 0; i < layers.size(); i++) {
MapLayerInfo layer = layers.get(i);
if ("cached".equals(KMLUtils.getSuperoverlayMode(request, wms))
&& KMLUtils.isRequestGWCCompatible(request, i, wms)) {
encodeGWCLink(request, layer);
} else {
String styleName = i < styles.size() ? styles.get(i).getName() : null;
ReferencedEnvelope bounds = layerBounds.get(i);
encodeLayerSuperOverlay(request, layer, styleName, i, bounds, lookAt);
}
}
}
public void encodeGWCLink(GetMapRequest request, MapLayerInfo layer) {
start("NetworkLink");
String prefixedName = layer.getResource().getPrefixedName();
element("name", "GWC-" + prefixedName);
start("Link");
String type = layer.getType() == MapLayerInfo.TYPE_RASTER ? "png" : "kml";
String url = ResponseUtils.buildURL(request.getBaseUrl(), "gwc/service/kml/" +
prefixedName + "." + type + ".kml", null, URLType.SERVICE);
element("href", url);
element("viewRefreshMode", "never");
end("Link");
end("NetworkLink");
}
private void encodeLayerSuperOverlay(GetMapRequest request, MapLayerInfo layer,
String styleName, int layerIndex, ReferencedEnvelope bounds, KMLLookAt lookAt) {
start("NetworkLink");
element("name", layer.getName());
element("open", "1");
element("visibility", "1");
// look at for the network link for this single layer
if (bounds != null) {
encodeLookAt(bounds, lookAt);
}
// region
start("Region");
Envelope bbox = request.getBbox();
start("LatLonAltBox");
element("north", "" + bbox.getMaxY());
element("south", "" + bbox.getMinY());
element("east", "" + bbox.getMaxX());
element("west", "" + bbox.getMinX());
end("LatLonAltBox");
start("Lod");
element("minLodPixels", "128");
element("maxLodPixels", "-1");
end("Lod");
end("Region");
// link
start("Link");
String href = WMSRequests.getGetMapUrl(request, layer.getName(), layerIndex, styleName,
null, null);
try {
// WMSRequests.getGetMapUrl returns a URL encoded query string, but GoogleEarth
// 6 doesn't like URL encoded parameters. See GEOS-4483
href = URLDecoder.decode(href, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
start("href");
cdata(href);
end("href");
// element( "viewRefreshMode", "onRegion" );
end("Link");
end("NetworkLink");
}
protected void encodeAsOverlay(GetMapRequest request, KMLLookAt lookAt,
List<ReferencedEnvelope> layerBounds) {
final List<MapLayerInfo> layers = request.getLayers();
final List<Style> styles = request.getStyles();
for (int i = 0; i < layers.size(); i++) {
MapLayerInfo layerInfo = layers.get(i);
start("NetworkLink");
element("name", layerInfo.getName());
element("visibility", "1");
element("open", "1");
// look at for the network link for this single layer
ReferencedEnvelope latLongBoundingBox = layerBounds.get(i);
if (latLongBoundingBox != null) {
encodeLookAt(latLongBoundingBox, lookAt);
}
start("Url");
// set bbox to null so its not included in the request, google
// earth will append it for us
request.setBbox(null);
String style = i < styles.size() ? styles.get(i).getName() : null;
String href = WMSRequests.getGetMapUrl(request, layers.get(i).getName(), i, style,
null, null);
try {
// WMSRequests.getGetMapUrl returns a URL encoded query string, but GoogleEarth
// 6 doesn't like URL encoded parameters. See GEOS-4483
href = URLDecoder.decode(href, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
start("href");
cdata(href);
end("href");
element("viewRefreshMode", "onStop");
element("viewRefreshTime", "1");
end("Url");
end("NetworkLink");
}
}
private void encodeLookAt(Envelope bounds, KMLLookAt lookAt) {
Envelope lookAtEnvelope = null;
if (lookAt.getLookAt() == null) {
lookAtEnvelope = bounds;
}
KMLLookAtTransformer tr;
tr = new KMLLookAtTransformer(lookAtEnvelope, getIndentation(), getEncoding());
Translator translator = tr.createTranslator(contentHandler);
translator.encode(lookAt);
}
}
}
| Gaia3D/GeoServerForKaosG | src/community/kml-old/src/main/java/org/geoserver/kml/KMLNetworkLinkTransformer.java | 4,115 | // element( "viewRefreshMode", "onRegion" ); | line_comment | nl | /* (c) 2014 Open Source Geospatial Foundation - all rights reserved
* (c) 2001 - 2013 OpenPlans
* This code is licensed under the GPL 2.0 license, available at the root
* application directory.
*/
package org.geoserver.kml;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.geoserver.ows.URLMangler.URLType;
import org.geoserver.ows.util.ResponseUtils;
import org.geoserver.wms.GetMapRequest;
import org.geoserver.wms.MapLayerInfo;
import org.geoserver.wms.WMS;
import org.geoserver.wms.WMSMapContent;
import org.geoserver.wms.WMSRequests;
import org.geotools.data.FeatureSource;
import org.geotools.data.Query;
import org.geotools.feature.FeatureCollection;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.map.Layer;
import org.geotools.referencing.CRS;
import org.geotools.styling.Style;
import org.geotools.xml.transform.TransformerBase;
import org.geotools.xml.transform.Translator;
import org.opengis.filter.Filter;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.xml.sax.ContentHandler;
import com.vividsolutions.jts.geom.Envelope;
/**
* Encodes a KML document contianing a network link.
* <p>
* This transformer transforms a {@link GetMapRequest} object.
* </p>
*
* @author Justin Deoliveira, The Open Planning Project, [email protected]
*
*/
public class KMLNetworkLinkTransformer extends TransformerBase {
/**
* logger
*/
static Logger LOGGER = org.geotools.util.logging.Logging.getLogger("org.geoserver.kml");
/**
* flag controlling whether the network link should be a super overlay.
*/
boolean encodeAsRegion = false;
/**
* flag controlling whether the network link should be a direct GWC one when possible
*/
boolean cachedMode = false;
private boolean standalone;
/**
* @see #setInline
*/
private boolean inline;
/**
* The map context
*/
private final WMSMapContent mapContent;
private WMS wms;
public KMLNetworkLinkTransformer(WMS wms, WMSMapContent mapContent) {
this.wms = wms;
this.mapContent = mapContent;
standalone = true;
}
public void setStandalone(boolean standalone){
this.standalone = standalone;
}
public boolean isStandalone(){
return standalone;
}
/**
* @return {@code true} if the document is to be generated inline (i.e. without an enclosing
* Folder element). Defaults to {@code false}
*/
public boolean isInline() {
return inline;
}
/**
* @param inline if {@code true} network links won't be enclosed inside a Folder element
*/
public void setInline(boolean inline) {
this.inline = inline;
}
public void setCachedMode(boolean cachedMode) {
this.cachedMode = cachedMode;
}
public Translator createTranslator(ContentHandler handler) {
return new KMLNetworkLinkTranslator(handler);
}
public void setEncodeAsRegion(boolean encodeAsRegion) {
this.encodeAsRegion = encodeAsRegion;
}
class KMLNetworkLinkTranslator extends TranslatorSupport {
public KMLNetworkLinkTranslator(ContentHandler contentHandler) {
super(contentHandler, null, null);
}
public void encode(Object o) throws IllegalArgumentException {
final WMSMapContent context = (WMSMapContent) o;
final GetMapRequest request = context.getRequest();
// restore target mime type for the network links
if (NetworkLinkMapOutputFormat.KML_MIME_TYPE.equals(request.getFormat())) {
request.setFormat(KMLMapOutputFormat.MIME_TYPE);
} else {
request.setFormat(KMZMapOutputFormat.MIME_TYPE);
}
if(standalone){
start("kml");
}
if (!inline) {
start("Folder");
if (standalone) {
String kmltitle = (String) mapContent.getRequest().getFormatOptions().get("kmltitle");
element("name", (kmltitle != null ? kmltitle : ""));
}
}
final List<MapLayerInfo> layers = request.getLayers();
final KMLLookAt lookAt = parseLookAtOptions(request);
ReferencedEnvelope aggregatedBounds;
List<ReferencedEnvelope> layerBounds;
layerBounds = new ArrayList<ReferencedEnvelope>(layers.size());
aggregatedBounds = computePerLayerQueryBounds(context, layerBounds, lookAt);
if (encodeAsRegion) {
encodeAsSuperOverlay(request, lookAt, layerBounds);
} else {
encodeAsOverlay(request, lookAt, layerBounds);
}
// look at
encodeLookAt(aggregatedBounds, lookAt);
if (!inline) {
end("Folder");
}
if (standalone) {
end("kml");
}
}
/**
* @return the aggregated bounds for all the requested layers, taking into account whether
* the whole layer or filtered bounds is used for each layer
*/
private ReferencedEnvelope computePerLayerQueryBounds(final WMSMapContent context,
final List<ReferencedEnvelope> target, final KMLLookAt lookAt) {
// no need to compute queried bounds if request explicitly specified the view area
final boolean computeQueryBounds = lookAt.getLookAt() == null;
ReferencedEnvelope aggregatedBounds;
try {
boolean longitudeFirst = true;
aggregatedBounds = new ReferencedEnvelope(CRS.decode("EPSG:4326", longitudeFirst));
} catch (Exception e) {
throw new RuntimeException(e);
}
aggregatedBounds.setToNull();
final List<Layer> mapLayers = context.layers();
final List<MapLayerInfo> layerInfos = context.getRequest().getLayers();
for (int i = 0; i < mapLayers.size(); i++) {
final Layer Layer = mapLayers.get(i);
final MapLayerInfo layerInfo = layerInfos.get(i);
ReferencedEnvelope layerLatLongBbox;
layerLatLongBbox = computeLayerBounds(Layer, layerInfo, computeQueryBounds);
try {
layerLatLongBbox = layerLatLongBbox.transform(aggregatedBounds.getCoordinateReferenceSystem(), true);
} catch (Exception e) {
throw new RuntimeException(e);
}
target.add(layerLatLongBbox);
aggregatedBounds.expandToInclude(layerLatLongBbox);
}
return aggregatedBounds;
}
@SuppressWarnings("rawtypes")
private ReferencedEnvelope computeLayerBounds(Layer layer, MapLayerInfo layerInfo,
boolean computeQueryBounds) {
final Query layerQuery = layer.getQuery();
// make sure if layer is gonna be filtered, the resulting bounds are obtained instead of
// the whole bounds
final Filter filter = layerQuery.getFilter();
if (layerQuery.getFilter() == null || Filter.INCLUDE.equals(filter)) {
computeQueryBounds = false;
}
if (!computeQueryBounds && !layerQuery.isMaxFeaturesUnlimited()) {
computeQueryBounds = true;
}
ReferencedEnvelope layerLatLongBbox = null;
if (computeQueryBounds) {
FeatureSource featureSource = layer.getFeatureSource();
try {
CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:4326");
FeatureCollection features = featureSource.getFeatures(layerQuery);
layerLatLongBbox = features.getBounds();
layerLatLongBbox = layerLatLongBbox.transform(targetCRS, true);
} catch (Exception e) {
LOGGER.info("Error computing bounds for " + featureSource.getName() + " with "
+ layerQuery);
}
}
if (layerLatLongBbox == null) {
try {
layerLatLongBbox = layerInfo.getLatLongBoundingBox();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return layerLatLongBbox;
}
@SuppressWarnings("unchecked")
private KMLLookAt parseLookAtOptions(final GetMapRequest request) {
final KMLLookAt lookAt;
if (request.getFormatOptions() == null) {
// use a default LookAt properties
lookAt = new KMLLookAt();
} else {
// use the requested LookAt properties
Map<String, Object> formatOptions;
formatOptions = new HashMap<String, Object>(request.getFormatOptions());
lookAt = new KMLLookAt(formatOptions);
/*
* remove LOOKATBBOX and LOOKATGEOM from format options so KMLUtils.getMapRequest
* does not include them in the network links, but do include the other options such
* as tilt, range, etc.
*/
request.getFormatOptions().remove("LOOKATBBOX");
request.getFormatOptions().remove("LOOKATGEOM");
}
return lookAt;
}
protected void encodeAsSuperOverlay(GetMapRequest request, KMLLookAt lookAt,
List<ReferencedEnvelope> layerBounds) {
List<MapLayerInfo> layers = request.getLayers();
List<Style> styles = request.getStyles();
for (int i = 0; i < layers.size(); i++) {
MapLayerInfo layer = layers.get(i);
if ("cached".equals(KMLUtils.getSuperoverlayMode(request, wms))
&& KMLUtils.isRequestGWCCompatible(request, i, wms)) {
encodeGWCLink(request, layer);
} else {
String styleName = i < styles.size() ? styles.get(i).getName() : null;
ReferencedEnvelope bounds = layerBounds.get(i);
encodeLayerSuperOverlay(request, layer, styleName, i, bounds, lookAt);
}
}
}
public void encodeGWCLink(GetMapRequest request, MapLayerInfo layer) {
start("NetworkLink");
String prefixedName = layer.getResource().getPrefixedName();
element("name", "GWC-" + prefixedName);
start("Link");
String type = layer.getType() == MapLayerInfo.TYPE_RASTER ? "png" : "kml";
String url = ResponseUtils.buildURL(request.getBaseUrl(), "gwc/service/kml/" +
prefixedName + "." + type + ".kml", null, URLType.SERVICE);
element("href", url);
element("viewRefreshMode", "never");
end("Link");
end("NetworkLink");
}
private void encodeLayerSuperOverlay(GetMapRequest request, MapLayerInfo layer,
String styleName, int layerIndex, ReferencedEnvelope bounds, KMLLookAt lookAt) {
start("NetworkLink");
element("name", layer.getName());
element("open", "1");
element("visibility", "1");
// look at for the network link for this single layer
if (bounds != null) {
encodeLookAt(bounds, lookAt);
}
// region
start("Region");
Envelope bbox = request.getBbox();
start("LatLonAltBox");
element("north", "" + bbox.getMaxY());
element("south", "" + bbox.getMinY());
element("east", "" + bbox.getMaxX());
element("west", "" + bbox.getMinX());
end("LatLonAltBox");
start("Lod");
element("minLodPixels", "128");
element("maxLodPixels", "-1");
end("Lod");
end("Region");
// link
start("Link");
String href = WMSRequests.getGetMapUrl(request, layer.getName(), layerIndex, styleName,
null, null);
try {
// WMSRequests.getGetMapUrl returns a URL encoded query string, but GoogleEarth
// 6 doesn't like URL encoded parameters. See GEOS-4483
href = URLDecoder.decode(href, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
start("href");
cdata(href);
end("href");
// element( "viewRefreshMode",<SUF>
end("Link");
end("NetworkLink");
}
protected void encodeAsOverlay(GetMapRequest request, KMLLookAt lookAt,
List<ReferencedEnvelope> layerBounds) {
final List<MapLayerInfo> layers = request.getLayers();
final List<Style> styles = request.getStyles();
for (int i = 0; i < layers.size(); i++) {
MapLayerInfo layerInfo = layers.get(i);
start("NetworkLink");
element("name", layerInfo.getName());
element("visibility", "1");
element("open", "1");
// look at for the network link for this single layer
ReferencedEnvelope latLongBoundingBox = layerBounds.get(i);
if (latLongBoundingBox != null) {
encodeLookAt(latLongBoundingBox, lookAt);
}
start("Url");
// set bbox to null so its not included in the request, google
// earth will append it for us
request.setBbox(null);
String style = i < styles.size() ? styles.get(i).getName() : null;
String href = WMSRequests.getGetMapUrl(request, layers.get(i).getName(), i, style,
null, null);
try {
// WMSRequests.getGetMapUrl returns a URL encoded query string, but GoogleEarth
// 6 doesn't like URL encoded parameters. See GEOS-4483
href = URLDecoder.decode(href, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
start("href");
cdata(href);
end("href");
element("viewRefreshMode", "onStop");
element("viewRefreshTime", "1");
end("Url");
end("NetworkLink");
}
}
private void encodeLookAt(Envelope bounds, KMLLookAt lookAt) {
Envelope lookAtEnvelope = null;
if (lookAt.getLookAt() == null) {
lookAtEnvelope = bounds;
}
KMLLookAtTransformer tr;
tr = new KMLLookAtTransformer(lookAtEnvelope, getIndentation(), getEncoding());
Translator translator = tr.createTranslator(contentHandler);
translator.encode(lookAt);
}
}
}
| False | 3,167 | 13 | 3,413 | 13 | 3,674 | 13 | 3,413 | 13 | 4,074 | 13 | false | false | false | false | false | true |
4,235 | 83529_2 | package com.in28minutes.rest.webservices.restfulwebservices.helloworld;
import java.util.Locale;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
// REST API
@RestController
public class HelloWorldController {
private MessageSource messageSource;
public HelloWorldController(MessageSource messageSource) {
this.messageSource = messageSource;
}
// /hello-world
@GetMapping(path = "/hello-world")
public String helloWorld() {
return "Hello World";
}
@GetMapping(path = "/hello-world-bean")
public HelloWorldBean helloWorldBean() {
return new HelloWorldBean("hello world");
}
@GetMapping(path = "/hello-world/path-variable/{name}")
public HelloWorldBean helloWorldPathVariable(@PathVariable String name) {
return new HelloWorldBean("hello " + name);
}
@GetMapping(path = "/hello-world-internationalized")
public String helloWorldInternationalized() {
Locale locale = LocaleContextHolder.getLocale();
return messageSource.getMessage("good.morning.message", null, "Default Message", locale);
// return "Hello World";
// 1:
// 2:
// - Example: `en` - English (Good Morning)
// - Example: `nl` - Dutch (Goedemorgen)
// - Example: `fr` - French (Bonjour)
// - Example: `de` - Deutsch (Guten Morgen)
}
}
| sahuankit010/Spring-Project | restful-web-services/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/helloworld/HelloWorldController.java | 452 | // - Example: `nl` - Dutch (Goedemorgen) | line_comment | nl | package com.in28minutes.rest.webservices.restfulwebservices.helloworld;
import java.util.Locale;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
// REST API
@RestController
public class HelloWorldController {
private MessageSource messageSource;
public HelloWorldController(MessageSource messageSource) {
this.messageSource = messageSource;
}
// /hello-world
@GetMapping(path = "/hello-world")
public String helloWorld() {
return "Hello World";
}
@GetMapping(path = "/hello-world-bean")
public HelloWorldBean helloWorldBean() {
return new HelloWorldBean("hello world");
}
@GetMapping(path = "/hello-world/path-variable/{name}")
public HelloWorldBean helloWorldPathVariable(@PathVariable String name) {
return new HelloWorldBean("hello " + name);
}
@GetMapping(path = "/hello-world-internationalized")
public String helloWorldInternationalized() {
Locale locale = LocaleContextHolder.getLocale();
return messageSource.getMessage("good.morning.message", null, "Default Message", locale);
// return "Hello World";
// 1:
// 2:
// - Example: `en` - English (Good Morning)
// - Example:<SUF>
// - Example: `fr` - French (Bonjour)
// - Example: `de` - Deutsch (Guten Morgen)
}
}
| False | 330 | 17 | 436 | 19 | 415 | 16 | 436 | 19 | 471 | 17 | false | false | false | false | false | true |
3,771 | 113325_5 | package yolo.octo.dangerzone.beatdetection;
import java.util.List;
import ddf.minim.analysis.FFT;
/*
* FFTBeatDetector
* An extension of the SimpleBeatDetector.
* Uses a Fast Fourier Transform on a single array of samples
* to break it down into multiple frequency ranges.
* Uses the low freqency range (from 80 to 230) to determine if there is a beat.
* Uses three frequency bands to find sections in the song.
*
*/
public class FFTBeatDetector implements BeatDetector{
/* Has three simple beat detectors, one for each frequency range*/
private SimpleBeatDetector lowFrequency;
private SimpleBeatDetector highFrequency;
private SimpleBeatDetector midFrequency;
private FFT fft;
/* Constructor*/
public FFTBeatDetector(int sampleRate, int channels, int bufferSize) {
fft = new FFT(bufferSize, sampleRate);
fft.window(FFT.HAMMING);
fft.noAverages();
lowFrequency = new SimpleBeatDetector(sampleRate, channels);
highFrequency = new SimpleBeatDetector(sampleRate, channels);
midFrequency = new SimpleBeatDetector(sampleRate, channels);
}
@Override
/* Uses the newEnergy function from the simple beat detector to fill the
* list of sections in each frequency range.
*/
public boolean newSamples(float[] samples) {
fft.forward(samples);
/* Only the low frequency range is used to find a beat*/
boolean lowBeat = lowFrequency.newEnergy(fft.calcAvg(80, 230), 1024);
highFrequency.newEnergy(fft.calcAvg(9000, 17000), 1024);
midFrequency.newEnergy(fft.calcAvg(280, 2800), 1024);
return lowBeat;
}
@Override
/*
* Wraps up the song.
* Calculates a total intensity by adding the intensity of the beats found in the
* high frequency range to the intensity in the low frequency range if both beats
* occur at the same time.
* Beat intensities will be scaled so they fall between 0 and 1.
*
* Then it uses the sections found in the middle frequency range and matches the
* beats in the low frequency range with the sections in the middle frequency range.
*/
public void finishSong() {
lowFrequency.finishSong();
highFrequency.finishSong();
List<Beat> lowBeats = lowFrequency.getBeats();
List<Beat> highBeats = highFrequency.getBeats();
int lbIndex = 0;
for (Beat hb : highBeats) {
for (; lbIndex < lowBeats.size(); lbIndex++) {
Beat lb = lowBeats.get(lbIndex);
if (lb.startTime > hb.startTime) {
break;
}
// Als een hb binnen een lb valt, draagt deze bij aan de intensiteit
if (lb.startTime <= hb.startTime
&& lb.endTime > hb.startTime) {
lb.intensity += hb.intensity / 2;
}
}
}
float maxBeatIntensity = 1;
for (Beat b : lowBeats) {
if (b.intensity > maxBeatIntensity) {
maxBeatIntensity = b.intensity;
}
}
for (Beat b : lowBeats) {
b.intensity /= maxBeatIntensity;
}
float maxSectionIntensity = 0;
lbIndex = 0;
/* Looks for the best match in the low frequency range for the start and end
* of the section fills the section with the beats between the start and the end.
*/
for (Section s : midFrequency.getSections()) {
int bestMatch = 0;
long timeDiff = Long.MAX_VALUE;
/* finds the start beat*/
for (; lbIndex < lowBeats.size(); lbIndex++) {
Beat b = lowBeats.get(lbIndex);
long newTimeDiff = Math.abs(s.startTime - b.startTime);
if (newTimeDiff < timeDiff) {
timeDiff = newTimeDiff;
bestMatch = lbIndex;
} else if (b.startTime > s.startTime) {
break;
}
}
int startBeat = bestMatch;
timeDiff = Long.MAX_VALUE;
/* Finds the end beat*/
for (; lbIndex < lowBeats.size(); lbIndex++) {
Beat b = lowBeats.get(lbIndex);
long newTimeDiff = Math.abs(s.endTime - b.endTime);
if (newTimeDiff < timeDiff) {
timeDiff = newTimeDiff;
bestMatch = lbIndex;
} else if (b.endTime > s.endTime) {
break;
}
}
int endBeat = bestMatch;
s.beats.clear();
/* Adds all beats from start to end to the section list*/
s.beats.addAll(lowBeats.subList(startBeat, endBeat));
if (s.intensity > maxSectionIntensity) {
/* Sets the maxsection intensity*/
maxSectionIntensity = (float) s.intensity;
}
}
/* Scales the intensities in the sections to fall between 0 and 1*/
/* for (Section s : midFrequency.getSections()) {
s.intensity /= maxSectionIntensity;
} */
}
@Override
/* See explanation at SimpleBeatDetector*/
public double estimateTempo() {
return lowFrequency.estimateTempo();
}
@Override
/* See explanation at SimpleBeatDetector*/
public List<Beat> getBeats() {
return lowFrequency.getBeats();
}
@Override
/* Only the middle frequency range is used for the section*/
public List<Section> getSections() {
if (midFrequency.getSections().isEmpty())
return lowFrequency.getSections();
return midFrequency.getSections();
}
}
| nardi/yolo-octo-dangerzone | GameTest/src/yolo/octo/dangerzone/beatdetection/FFTBeatDetector.java | 1,643 | // Als een hb binnen een lb valt, draagt deze bij aan de intensiteit | line_comment | nl | package yolo.octo.dangerzone.beatdetection;
import java.util.List;
import ddf.minim.analysis.FFT;
/*
* FFTBeatDetector
* An extension of the SimpleBeatDetector.
* Uses a Fast Fourier Transform on a single array of samples
* to break it down into multiple frequency ranges.
* Uses the low freqency range (from 80 to 230) to determine if there is a beat.
* Uses three frequency bands to find sections in the song.
*
*/
public class FFTBeatDetector implements BeatDetector{
/* Has three simple beat detectors, one for each frequency range*/
private SimpleBeatDetector lowFrequency;
private SimpleBeatDetector highFrequency;
private SimpleBeatDetector midFrequency;
private FFT fft;
/* Constructor*/
public FFTBeatDetector(int sampleRate, int channels, int bufferSize) {
fft = new FFT(bufferSize, sampleRate);
fft.window(FFT.HAMMING);
fft.noAverages();
lowFrequency = new SimpleBeatDetector(sampleRate, channels);
highFrequency = new SimpleBeatDetector(sampleRate, channels);
midFrequency = new SimpleBeatDetector(sampleRate, channels);
}
@Override
/* Uses the newEnergy function from the simple beat detector to fill the
* list of sections in each frequency range.
*/
public boolean newSamples(float[] samples) {
fft.forward(samples);
/* Only the low frequency range is used to find a beat*/
boolean lowBeat = lowFrequency.newEnergy(fft.calcAvg(80, 230), 1024);
highFrequency.newEnergy(fft.calcAvg(9000, 17000), 1024);
midFrequency.newEnergy(fft.calcAvg(280, 2800), 1024);
return lowBeat;
}
@Override
/*
* Wraps up the song.
* Calculates a total intensity by adding the intensity of the beats found in the
* high frequency range to the intensity in the low frequency range if both beats
* occur at the same time.
* Beat intensities will be scaled so they fall between 0 and 1.
*
* Then it uses the sections found in the middle frequency range and matches the
* beats in the low frequency range with the sections in the middle frequency range.
*/
public void finishSong() {
lowFrequency.finishSong();
highFrequency.finishSong();
List<Beat> lowBeats = lowFrequency.getBeats();
List<Beat> highBeats = highFrequency.getBeats();
int lbIndex = 0;
for (Beat hb : highBeats) {
for (; lbIndex < lowBeats.size(); lbIndex++) {
Beat lb = lowBeats.get(lbIndex);
if (lb.startTime > hb.startTime) {
break;
}
// Als een<SUF>
if (lb.startTime <= hb.startTime
&& lb.endTime > hb.startTime) {
lb.intensity += hb.intensity / 2;
}
}
}
float maxBeatIntensity = 1;
for (Beat b : lowBeats) {
if (b.intensity > maxBeatIntensity) {
maxBeatIntensity = b.intensity;
}
}
for (Beat b : lowBeats) {
b.intensity /= maxBeatIntensity;
}
float maxSectionIntensity = 0;
lbIndex = 0;
/* Looks for the best match in the low frequency range for the start and end
* of the section fills the section with the beats between the start and the end.
*/
for (Section s : midFrequency.getSections()) {
int bestMatch = 0;
long timeDiff = Long.MAX_VALUE;
/* finds the start beat*/
for (; lbIndex < lowBeats.size(); lbIndex++) {
Beat b = lowBeats.get(lbIndex);
long newTimeDiff = Math.abs(s.startTime - b.startTime);
if (newTimeDiff < timeDiff) {
timeDiff = newTimeDiff;
bestMatch = lbIndex;
} else if (b.startTime > s.startTime) {
break;
}
}
int startBeat = bestMatch;
timeDiff = Long.MAX_VALUE;
/* Finds the end beat*/
for (; lbIndex < lowBeats.size(); lbIndex++) {
Beat b = lowBeats.get(lbIndex);
long newTimeDiff = Math.abs(s.endTime - b.endTime);
if (newTimeDiff < timeDiff) {
timeDiff = newTimeDiff;
bestMatch = lbIndex;
} else if (b.endTime > s.endTime) {
break;
}
}
int endBeat = bestMatch;
s.beats.clear();
/* Adds all beats from start to end to the section list*/
s.beats.addAll(lowBeats.subList(startBeat, endBeat));
if (s.intensity > maxSectionIntensity) {
/* Sets the maxsection intensity*/
maxSectionIntensity = (float) s.intensity;
}
}
/* Scales the intensities in the sections to fall between 0 and 1*/
/* for (Section s : midFrequency.getSections()) {
s.intensity /= maxSectionIntensity;
} */
}
@Override
/* See explanation at SimpleBeatDetector*/
public double estimateTempo() {
return lowFrequency.estimateTempo();
}
@Override
/* See explanation at SimpleBeatDetector*/
public List<Beat> getBeats() {
return lowFrequency.getBeats();
}
@Override
/* Only the middle frequency range is used for the section*/
public List<Section> getSections() {
if (midFrequency.getSections().isEmpty())
return lowFrequency.getSections();
return midFrequency.getSections();
}
}
| True | 1,309 | 18 | 1,467 | 23 | 1,463 | 18 | 1,467 | 23 | 1,861 | 19 | false | false | false | false | false | true |
1,603 | 108250_1 | /*
GanttProject is an opensource project management tool.
Copyright (C) 2010-2011 GanttProject Team
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.sourceforge.ganttproject.gui.options;
import biz.ganttproject.core.calendar.GPCalendarCalc;
import biz.ganttproject.core.calendar.WeekendCalendarImpl;
import net.sourceforge.ganttproject.GPLogger;
import net.sourceforge.ganttproject.IGanttProject;
import net.sourceforge.ganttproject.gui.UIFacade;
import net.sourceforge.ganttproject.gui.projectwizard.I18N;
import net.sourceforge.ganttproject.gui.projectwizard.WeekendConfigurationPage;
import net.sourceforge.ganttproject.task.TaskManager;
import net.sourceforge.ganttproject.task.dependency.TaskDependencyException;
/**
* Panel to edit the weekend settings
*
* @author Maarten Bezemer
*/
public class WeekendsSettingsPanel extends GeneralOptionPanel {
private final IGanttProject project;
private WeekendConfigurationPage weekendConfigurationPanel;
private GPCalendarCalc calendar;
public WeekendsSettingsPanel(IGanttProject project, UIFacade uiFacade) {
super(uiFacade, language.getCorrectedLabel("weekends"), language.getText("settingsWeekends"));
this.project = project;
calendar = new WeekendCalendarImpl();
weekendConfigurationPanel = null;
}
@Override
public boolean applyChanges(boolean askForApply) {
weekendConfigurationPanel.setActive(false);
GPCalendarCalc projectCalendar = project.getActiveCalendar();
boolean hasChange = weekendConfigurationPanel.isChanged();
for (int i = 1; !hasChange && i < 8; i++) {
if (calendar.getWeekDayType(i) != projectCalendar.getWeekDayType(i)) {
hasChange = true;
}
}
for (int i = 1; i < 8; i++) {
projectCalendar.setWeekDayType(i, calendar.getWeekDayType(i));
}
if (hasChange) {
projectCalendar.setBaseCalendarID(calendar.getBaseCalendarID());
projectCalendar.setPublicHolidays(calendar.getPublicHolidays());
projectCalendar.setOnlyShowWeekends(calendar.getOnlyShowWeekends());
try {
TaskManager taskManager = project.getTaskManager();
taskManager.getAlgorithmCollection().getRecalculateTaskScheduleAlgorithm().run();
taskManager.getAlgorithmCollection().getAdjustTaskBoundsAlgorithm().adjustNestedTasks(taskManager.getRootTask());
} catch (TaskDependencyException e) {
GPLogger.log(e);
}
}
return hasChange;
}
// TODO It would be nicer to just update the checkboxes,
// but WeekendConfigurationPage does not allow it ATM
@Override
public void initialize() {
if (weekendConfigurationPanel != null) {
vb.remove(weekendConfigurationPanel.getComponent());
}
// Make a copy of the WeekDayTypes
calendar = project.getActiveCalendar().copy();
weekendConfigurationPanel = new WeekendConfigurationPage(calendar, new I18N(), getUIFacade());
vb.add(weekendConfigurationPanel.getComponent());
}
}
| Site-Command/ganttproject | ganttproject/src/main/java/net/sourceforge/ganttproject/gui/options/WeekendsSettingsPanel.java | 1,059 | /**
* Panel to edit the weekend settings
*
* @author Maarten Bezemer
*/ | block_comment | nl | /*
GanttProject is an opensource project management tool.
Copyright (C) 2010-2011 GanttProject Team
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.sourceforge.ganttproject.gui.options;
import biz.ganttproject.core.calendar.GPCalendarCalc;
import biz.ganttproject.core.calendar.WeekendCalendarImpl;
import net.sourceforge.ganttproject.GPLogger;
import net.sourceforge.ganttproject.IGanttProject;
import net.sourceforge.ganttproject.gui.UIFacade;
import net.sourceforge.ganttproject.gui.projectwizard.I18N;
import net.sourceforge.ganttproject.gui.projectwizard.WeekendConfigurationPage;
import net.sourceforge.ganttproject.task.TaskManager;
import net.sourceforge.ganttproject.task.dependency.TaskDependencyException;
/**
* Panel to edit<SUF>*/
public class WeekendsSettingsPanel extends GeneralOptionPanel {
private final IGanttProject project;
private WeekendConfigurationPage weekendConfigurationPanel;
private GPCalendarCalc calendar;
public WeekendsSettingsPanel(IGanttProject project, UIFacade uiFacade) {
super(uiFacade, language.getCorrectedLabel("weekends"), language.getText("settingsWeekends"));
this.project = project;
calendar = new WeekendCalendarImpl();
weekendConfigurationPanel = null;
}
@Override
public boolean applyChanges(boolean askForApply) {
weekendConfigurationPanel.setActive(false);
GPCalendarCalc projectCalendar = project.getActiveCalendar();
boolean hasChange = weekendConfigurationPanel.isChanged();
for (int i = 1; !hasChange && i < 8; i++) {
if (calendar.getWeekDayType(i) != projectCalendar.getWeekDayType(i)) {
hasChange = true;
}
}
for (int i = 1; i < 8; i++) {
projectCalendar.setWeekDayType(i, calendar.getWeekDayType(i));
}
if (hasChange) {
projectCalendar.setBaseCalendarID(calendar.getBaseCalendarID());
projectCalendar.setPublicHolidays(calendar.getPublicHolidays());
projectCalendar.setOnlyShowWeekends(calendar.getOnlyShowWeekends());
try {
TaskManager taskManager = project.getTaskManager();
taskManager.getAlgorithmCollection().getRecalculateTaskScheduleAlgorithm().run();
taskManager.getAlgorithmCollection().getAdjustTaskBoundsAlgorithm().adjustNestedTasks(taskManager.getRootTask());
} catch (TaskDependencyException e) {
GPLogger.log(e);
}
}
return hasChange;
}
// TODO It would be nicer to just update the checkboxes,
// but WeekendConfigurationPage does not allow it ATM
@Override
public void initialize() {
if (weekendConfigurationPanel != null) {
vb.remove(weekendConfigurationPanel.getComponent());
}
// Make a copy of the WeekDayTypes
calendar = project.getActiveCalendar().copy();
weekendConfigurationPanel = new WeekendConfigurationPage(calendar, new I18N(), getUIFacade());
vb.add(weekendConfigurationPanel.getComponent());
}
}
| False | 792 | 19 | 919 | 22 | 928 | 21 | 919 | 22 | 1,045 | 24 | false | false | false | false | false | true |
898 | 84759_1 | package be.kuleuven.scorebord;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Scorebord {
private List<Speler> spelers;
private Gson gsonInstance;
public Scorebord() {
spelers = new ArrayList<>();
gsonInstance = new Gson();
if(Files.exists(Paths.get("score.json"))) {
loadFromFile();
}
}
/**
* Voegt speler toe aan scorebord. Indien reeds aanwezig, telt score op bij huidige score.
* @param spelerNaam de naam van de speler.
* @param score de score van de speler.
*/
public void voegToe(String spelerNaam, int score) {
var current = spelers.stream().filter(s -> s.getNaam().equals(spelerNaam)).findFirst();
if(current.isPresent()) {
current.get().scoor(score);
} else {
spelers.add(new Speler(spelerNaam, score));
}
save();
}
private void save() {
try {
var json = gsonInstance.toJson(spelers);
Files.write(Paths.get("score.json"), json.getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Wie is gewonnen? (huidige speler met hoogste score)
* @return naam van speler in tekst
*/
public String getWinnaar() {
return spelers.stream()
.sorted(Comparator.comparing(Speler::getScore))
.findFirst()
.orElseGet(() -> new Speler("GEEN")).getNaam();
}
/**
* Geef huidige totale score van de speler
* @param spelerNaam speler naam
* @return score vanuit het bord
*/
public int getTotaleScore(String spelerNaam) {
var result = spelers.stream().filter(s -> s.getNaam().equals(spelerNaam)).findFirst();
return result.isEmpty() ? 0 : result.get().getScore();
}
private void loadFromFile() {
try {
var collectionType = new TypeToken<List<Speler>>(){}.getType();
var json = Files.readString(Paths.get("score.json"));
spelers = gsonInstance.fromJson(json, collectionType);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| KULeuven-Diepenbeek/ses-course | examples/java/scorebord/src/main/java/be/kuleuven/scorebord/Scorebord.java | 744 | /**
* Wie is gewonnen? (huidige speler met hoogste score)
* @return naam van speler in tekst
*/ | block_comment | nl | package be.kuleuven.scorebord;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Scorebord {
private List<Speler> spelers;
private Gson gsonInstance;
public Scorebord() {
spelers = new ArrayList<>();
gsonInstance = new Gson();
if(Files.exists(Paths.get("score.json"))) {
loadFromFile();
}
}
/**
* Voegt speler toe aan scorebord. Indien reeds aanwezig, telt score op bij huidige score.
* @param spelerNaam de naam van de speler.
* @param score de score van de speler.
*/
public void voegToe(String spelerNaam, int score) {
var current = spelers.stream().filter(s -> s.getNaam().equals(spelerNaam)).findFirst();
if(current.isPresent()) {
current.get().scoor(score);
} else {
spelers.add(new Speler(spelerNaam, score));
}
save();
}
private void save() {
try {
var json = gsonInstance.toJson(spelers);
Files.write(Paths.get("score.json"), json.getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Wie is gewonnen?<SUF>*/
public String getWinnaar() {
return spelers.stream()
.sorted(Comparator.comparing(Speler::getScore))
.findFirst()
.orElseGet(() -> new Speler("GEEN")).getNaam();
}
/**
* Geef huidige totale score van de speler
* @param spelerNaam speler naam
* @return score vanuit het bord
*/
public int getTotaleScore(String spelerNaam) {
var result = spelers.stream().filter(s -> s.getNaam().equals(spelerNaam)).findFirst();
return result.isEmpty() ? 0 : result.get().getScore();
}
private void loadFromFile() {
try {
var collectionType = new TypeToken<List<Speler>>(){}.getType();
var json = Files.readString(Paths.get("score.json"));
spelers = gsonInstance.fromJson(json, collectionType);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| True | 563 | 32 | 650 | 36 | 655 | 33 | 650 | 36 | 741 | 35 | false | false | false | false | false | true |
3,958 | 106406_2 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.cpc;
import static java.lang.Math.pow;
import static java.lang.Math.round;
import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssert;
import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssertEquals;
/**
* @author Lee Rhodes
*/
public class TestUtil {
static final double pwrLaw10NextDouble(final int ppb, final double curPoint) {
final double cur = (curPoint < 1.0) ? 1.0 : curPoint;
double gi = round(Math.log10(cur) * ppb); //current generating index
double next;
do {
next = round(pow(10.0, ++gi / ppb));
} while (next <= curPoint);
return next;
}
static boolean specialEquals(final CpcSketch sk1, final CpcSketch sk2,
final boolean sk1wasMerged, final boolean sk2wasMerged) {
rtAssertEquals(sk1.seed, sk2.seed);
rtAssertEquals(sk1.lgK, sk2.lgK);
rtAssertEquals(sk1.numCoupons, sk2.numCoupons);
rtAssertEquals(sk1.windowOffset, sk2.windowOffset);
rtAssertEquals(sk1.slidingWindow, sk2.slidingWindow);
PairTable.equals(sk1.pairTable, sk2.pairTable);
// fiCol is only updated occasionally while stream processing,
// therefore, the stream sketch could be behind the merged sketch.
// So we have to recalculate the FiCol on the stream sketch.
final int ficolA = sk1.fiCol;
final int ficolB = sk2.fiCol;
if (!sk1wasMerged && sk2wasMerged) {
rtAssert(!sk1.mergeFlag && sk2.mergeFlag);
final int fiCol1 = calculateFirstInterestingColumn(sk1);
rtAssertEquals(fiCol1, sk2.fiCol);
} else if (sk1wasMerged && !sk2wasMerged) {
rtAssert(sk1.mergeFlag && !sk2.mergeFlag);
final int fiCol2 = calculateFirstInterestingColumn(sk2);
rtAssertEquals(fiCol2,sk1.fiCol);
} else {
rtAssertEquals(sk1.mergeFlag, sk2.mergeFlag);
rtAssertEquals(ficolA, ficolB);
rtAssertEquals(sk1.kxp, sk2.kxp, .01 * sk1.kxp); //1% tolerance
rtAssertEquals(sk1.hipEstAccum, sk2.hipEstAccum, 01 * sk1.hipEstAccum); //1% tolerance
}
return true;
}
static int calculateFirstInterestingColumn(final CpcSketch sketch) {
final int offset = sketch.windowOffset;
if (offset == 0) {
return 0;
}
final PairTable table = sketch.pairTable;
assert (table != null);
final int[] slots = table.getSlotsArr();
final int numSlots = 1 << table.getLgSizeInts();
int i;
int result = offset;
for (i = 0; i < numSlots; i++) {
final int rowCol = slots[i];
if (rowCol != -1) {
final int col = rowCol & 63;
if (col < result) { result = col; }
}
}
return result;
}
}
| paulk-asert/incubator-datasketches-java | src/main/java/org/apache/datasketches/cpc/TestUtil.java | 1,115 | //current generating index | line_comment | nl | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.cpc;
import static java.lang.Math.pow;
import static java.lang.Math.round;
import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssert;
import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssertEquals;
/**
* @author Lee Rhodes
*/
public class TestUtil {
static final double pwrLaw10NextDouble(final int ppb, final double curPoint) {
final double cur = (curPoint < 1.0) ? 1.0 : curPoint;
double gi = round(Math.log10(cur) * ppb); //current generating<SUF>
double next;
do {
next = round(pow(10.0, ++gi / ppb));
} while (next <= curPoint);
return next;
}
static boolean specialEquals(final CpcSketch sk1, final CpcSketch sk2,
final boolean sk1wasMerged, final boolean sk2wasMerged) {
rtAssertEquals(sk1.seed, sk2.seed);
rtAssertEquals(sk1.lgK, sk2.lgK);
rtAssertEquals(sk1.numCoupons, sk2.numCoupons);
rtAssertEquals(sk1.windowOffset, sk2.windowOffset);
rtAssertEquals(sk1.slidingWindow, sk2.slidingWindow);
PairTable.equals(sk1.pairTable, sk2.pairTable);
// fiCol is only updated occasionally while stream processing,
// therefore, the stream sketch could be behind the merged sketch.
// So we have to recalculate the FiCol on the stream sketch.
final int ficolA = sk1.fiCol;
final int ficolB = sk2.fiCol;
if (!sk1wasMerged && sk2wasMerged) {
rtAssert(!sk1.mergeFlag && sk2.mergeFlag);
final int fiCol1 = calculateFirstInterestingColumn(sk1);
rtAssertEquals(fiCol1, sk2.fiCol);
} else if (sk1wasMerged && !sk2wasMerged) {
rtAssert(sk1.mergeFlag && !sk2.mergeFlag);
final int fiCol2 = calculateFirstInterestingColumn(sk2);
rtAssertEquals(fiCol2,sk1.fiCol);
} else {
rtAssertEquals(sk1.mergeFlag, sk2.mergeFlag);
rtAssertEquals(ficolA, ficolB);
rtAssertEquals(sk1.kxp, sk2.kxp, .01 * sk1.kxp); //1% tolerance
rtAssertEquals(sk1.hipEstAccum, sk2.hipEstAccum, 01 * sk1.hipEstAccum); //1% tolerance
}
return true;
}
static int calculateFirstInterestingColumn(final CpcSketch sketch) {
final int offset = sketch.windowOffset;
if (offset == 0) {
return 0;
}
final PairTable table = sketch.pairTable;
assert (table != null);
final int[] slots = table.getSlotsArr();
final int numSlots = 1 << table.getLgSizeInts();
int i;
int result = offset;
for (i = 0; i < numSlots; i++) {
final int rowCol = slots[i];
if (rowCol != -1) {
final int col = rowCol & 63;
if (col < result) { result = col; }
}
}
return result;
}
}
| False | 926 | 4 | 1,012 | 4 | 1,049 | 4 | 1,009 | 4 | 1,149 | 4 | false | false | false | false | false | true |
749 | 206460_5 | package simulation.src.main.java;
import java.util.ArrayList;
class War {
private ArrayList<Integer> deck;
public War(ArrayList<Integer> deck) {
this.deck = deck;
}
public int drawCard(ArrayList<Integer> stack) {
int myCard;
myCard= stack.get(0);
return myCard;
}
public int simulateGame() {
/// ...
int score = 0;
ArrayList<ArrayList<Integer>> A$B = card_delen(deck);
ArrayList<Integer> A = A$B.get(0); //Lijst van speler A
ArrayList<Integer> B = A$B.get(1); //Lijst van speler B.
boolean simulating = true;
while (simulating){
if(A.isEmpty()){return -1;}
if(B.isEmpty()){return 1;}
if(A.isEmpty() && B.isEmpty()){return 0;}
if(drawCard(A) > drawCard(B)){
A.add(B.get(0));
A.add(A.get(0));
B.remove(0);
A.remove(0);
}
else if(drawCard(A) < drawCard(B)){
B.add(B.get(0));
B.add(A.get(0));
A.remove(0);
B.remove(0);
}
else if(drawCard(A) == drawCard(B)){
//verklaar oorlog
int cards = 3;
while (true){
if(A.size() < cards){return -1;}
if(B.size() < cards){return 1;}
if(A.size() < cards && B.size() <cards){return 0;}
if(A.get(cards) > B.get(cards)){
for(int x=0; x < cards; x++){
A.add(B.get(0));
A.add(A.get(0));
B.remove(0);
A.remove(0);
}
break;
}
else if(A.get(cards) < B.get(cards)){
for(int x=0; x < cards; x++){
B.add(B.get(0));
B.add(A.get(0));
B.remove(0);
A.remove(0);
}
break;
}
else if(A.get(cards) == B.get(cards)){
cards += 4;
}
}
}
}
return score;
}
public static int findWinner(ArrayList<Integer> deck) {
War w = new War(deck);
return w.simulateGame();
}
@Override
public String toString() {
return
this.deck.toString();
}
public ArrayList<ArrayList<Integer>>card_delen(ArrayList<Integer> deck) {
/**
* Deze mothode deelt de deck door 2 players A en B, maakt list of lists daarin list[0] is A en List[1] is B
*/
ArrayList<ArrayList<Integer>> players = new ArrayList<ArrayList<Integer>>(); // list of lists
ArrayList<Integer> A = new ArrayList<>();
ArrayList<Integer> B = new ArrayList<>();
for (int ind = 0; ind < deck.size(); ind++) {
if (ind % 2 == 0){
A.add(deck.get(ind)); //Even nummer van de index voor A
} else {
B.add(deck.get(ind)); // Odd nummer van de index voor B
}
}
players.add(A);
players.add(B);
return players;
}
public static void main(String[] args) {
ArrayList<Integer> arl = new ArrayList<Integer>();
arl.add(1);
arl.add(22);
arl.add(-2);
System.out.println("Arraylist contains: " + arl.toString());
// print the result
}
} | IhabSaf/War-card-game-Simulation- | War.java | 1,113 | // Odd nummer van de index voor B | line_comment | nl | package simulation.src.main.java;
import java.util.ArrayList;
class War {
private ArrayList<Integer> deck;
public War(ArrayList<Integer> deck) {
this.deck = deck;
}
public int drawCard(ArrayList<Integer> stack) {
int myCard;
myCard= stack.get(0);
return myCard;
}
public int simulateGame() {
/// ...
int score = 0;
ArrayList<ArrayList<Integer>> A$B = card_delen(deck);
ArrayList<Integer> A = A$B.get(0); //Lijst van speler A
ArrayList<Integer> B = A$B.get(1); //Lijst van speler B.
boolean simulating = true;
while (simulating){
if(A.isEmpty()){return -1;}
if(B.isEmpty()){return 1;}
if(A.isEmpty() && B.isEmpty()){return 0;}
if(drawCard(A) > drawCard(B)){
A.add(B.get(0));
A.add(A.get(0));
B.remove(0);
A.remove(0);
}
else if(drawCard(A) < drawCard(B)){
B.add(B.get(0));
B.add(A.get(0));
A.remove(0);
B.remove(0);
}
else if(drawCard(A) == drawCard(B)){
//verklaar oorlog
int cards = 3;
while (true){
if(A.size() < cards){return -1;}
if(B.size() < cards){return 1;}
if(A.size() < cards && B.size() <cards){return 0;}
if(A.get(cards) > B.get(cards)){
for(int x=0; x < cards; x++){
A.add(B.get(0));
A.add(A.get(0));
B.remove(0);
A.remove(0);
}
break;
}
else if(A.get(cards) < B.get(cards)){
for(int x=0; x < cards; x++){
B.add(B.get(0));
B.add(A.get(0));
B.remove(0);
A.remove(0);
}
break;
}
else if(A.get(cards) == B.get(cards)){
cards += 4;
}
}
}
}
return score;
}
public static int findWinner(ArrayList<Integer> deck) {
War w = new War(deck);
return w.simulateGame();
}
@Override
public String toString() {
return
this.deck.toString();
}
public ArrayList<ArrayList<Integer>>card_delen(ArrayList<Integer> deck) {
/**
* Deze mothode deelt de deck door 2 players A en B, maakt list of lists daarin list[0] is A en List[1] is B
*/
ArrayList<ArrayList<Integer>> players = new ArrayList<ArrayList<Integer>>(); // list of lists
ArrayList<Integer> A = new ArrayList<>();
ArrayList<Integer> B = new ArrayList<>();
for (int ind = 0; ind < deck.size(); ind++) {
if (ind % 2 == 0){
A.add(deck.get(ind)); //Even nummer van de index voor A
} else {
B.add(deck.get(ind)); // Odd nummer<SUF>
}
}
players.add(A);
players.add(B);
return players;
}
public static void main(String[] args) {
ArrayList<Integer> arl = new ArrayList<Integer>();
arl.add(1);
arl.add(22);
arl.add(-2);
System.out.println("Arraylist contains: " + arl.toString());
// print the result
}
} | True | 800 | 9 | 923 | 10 | 1,006 | 8 | 923 | 10 | 1,070 | 10 | false | false | false | false | false | true |
909 | 83214_9 | package program;
import java.io.IOException;
import java.net.URL;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.image.ImageView;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.control.TextArea;
import javafx.scene.control.Label;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import javafx.scene.image.Image ;
import static program.Afname.*;
public class SchrijvenController {
public TextArea test1Field;
public Label testNumber;
public Button checkButton;
public Button playButton;
public Label middleText;
public ImageView endscreenImage;
public int current = 1; //houd bij welke mp3 file gebruikt moet worden
private static SchrijvenController instance;
// ik heb hieronder een private controller gemaakt. Hier door kan er maar 1 instance gemaakt worden
// je vraagt deze dan ook alsvolgt op: SchrijvenController.getInstance();
// je kunt nu niet meer SchrijvenController schrijven = new SchrijvenController();
// Kijk maar naar de if statement hieronder.
// als er al een instance is dan is 'instance == null' false, waardoor hij de zelfde 'return instance' geven.
// Als er geen instance is dus 'instance == nul' is true, dan kun je maar als het ware 1 object aanmaken.
private SchrijvenController(){
//System.out.println("hoi");
}
// ik heb dit weggehaald: static SchrijvenController obj = new SchrijvenController();
public static SchrijvenController getInstance(){
if (instance == null){
instance = new SchrijvenController();
}
return instance;
// dit ook: return obj;
}
public int teller = 2; //
public int count = 0;
//Speelt de mp3 file die is geselecteerd
public void startTest(){
StartToets("Schrijven");
Input input = Afname.opdrachten.get(count);
System.out.println(((SchrijvenInput) input).getMp3());
final URL resource = getClass().getResource("../mp3/" + ((SchrijvenInput) input).getMp3() +".mp3");
final Media media = new Media(resource.toString());
final MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
}
//Controleerd antwoord
public void checkTest() {
System.out.println("size = " + opdrachten.size());
Input opdracht = Afname.opdrachten.get(count);
String answer = ((SchrijvenInput) opdracht).getAntwoord();
String input = test1Field.getText();
if (count < 2) {
if (input.equals(answer)) {
alertBox(true);
test1Field.clear();
testNumber.setText("Test " + (count + 1));
count++;
} else {
alertBox(false);
}
} else {
done();
}
}
//Eindscherm laten zien voor als de gebruiker alles goed heeft
public void done(){
test1Field.setVisible(false);
playButton.setVisible(false);
checkButton.setVisible(false);
testNumber.setText("Good Job!");
middleText.setText("You have completed your test!");
endscreenImage.setVisible(true);
}
//Alertbox laten zien bij het checken van antwoord
public void alertBox(boolean status){
Alert alert = new Alert(Alert.AlertType.INFORMATION);
if (status == true){
alert.setTitle("Good Job!");
alert.setContentText("I have a great message for you!");
alert.setContentText("press ok to continue");
Image image = new Image(getClass().getResource("../images/goodjob.gif").toExternalForm());
ImageView imageView = new ImageView(image);
alert.setGraphic(imageView);
alert.showAndWait();
}else{
alert.setTitle("False answer");
alert.setContentText("I have a great message for you!");
alert.setContentText("press ok to continue");
Image image = new Image(getClass().getResource("../images/false.gif").toExternalForm());
ImageView imageView = new ImageView(image);
alert.setGraphic(imageView);
alert.showAndWait();
}
}
public void toHomescreen(ActionEvent event) throws IOException {
Parent tohome = FXMLLoader.load(getClass().getResource("homescreen.fxml"));
Scene homeScene = new Scene(tohome);
//pakt stage informatie
Stage window = (Stage)((Node)event.getSource()).getScene().getWindow();
window.setScene(homeScene);
window.show();
}
}
| KemalUzr/project-zeroXess | src/program/SchrijvenController.java | 1,323 | //Speelt de mp3 file die is geselecteerd | line_comment | nl | package program;
import java.io.IOException;
import java.net.URL;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.image.ImageView;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.control.TextArea;
import javafx.scene.control.Label;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import javafx.scene.image.Image ;
import static program.Afname.*;
public class SchrijvenController {
public TextArea test1Field;
public Label testNumber;
public Button checkButton;
public Button playButton;
public Label middleText;
public ImageView endscreenImage;
public int current = 1; //houd bij welke mp3 file gebruikt moet worden
private static SchrijvenController instance;
// ik heb hieronder een private controller gemaakt. Hier door kan er maar 1 instance gemaakt worden
// je vraagt deze dan ook alsvolgt op: SchrijvenController.getInstance();
// je kunt nu niet meer SchrijvenController schrijven = new SchrijvenController();
// Kijk maar naar de if statement hieronder.
// als er al een instance is dan is 'instance == null' false, waardoor hij de zelfde 'return instance' geven.
// Als er geen instance is dus 'instance == nul' is true, dan kun je maar als het ware 1 object aanmaken.
private SchrijvenController(){
//System.out.println("hoi");
}
// ik heb dit weggehaald: static SchrijvenController obj = new SchrijvenController();
public static SchrijvenController getInstance(){
if (instance == null){
instance = new SchrijvenController();
}
return instance;
// dit ook: return obj;
}
public int teller = 2; //
public int count = 0;
//Speelt de<SUF>
public void startTest(){
StartToets("Schrijven");
Input input = Afname.opdrachten.get(count);
System.out.println(((SchrijvenInput) input).getMp3());
final URL resource = getClass().getResource("../mp3/" + ((SchrijvenInput) input).getMp3() +".mp3");
final Media media = new Media(resource.toString());
final MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
}
//Controleerd antwoord
public void checkTest() {
System.out.println("size = " + opdrachten.size());
Input opdracht = Afname.opdrachten.get(count);
String answer = ((SchrijvenInput) opdracht).getAntwoord();
String input = test1Field.getText();
if (count < 2) {
if (input.equals(answer)) {
alertBox(true);
test1Field.clear();
testNumber.setText("Test " + (count + 1));
count++;
} else {
alertBox(false);
}
} else {
done();
}
}
//Eindscherm laten zien voor als de gebruiker alles goed heeft
public void done(){
test1Field.setVisible(false);
playButton.setVisible(false);
checkButton.setVisible(false);
testNumber.setText("Good Job!");
middleText.setText("You have completed your test!");
endscreenImage.setVisible(true);
}
//Alertbox laten zien bij het checken van antwoord
public void alertBox(boolean status){
Alert alert = new Alert(Alert.AlertType.INFORMATION);
if (status == true){
alert.setTitle("Good Job!");
alert.setContentText("I have a great message for you!");
alert.setContentText("press ok to continue");
Image image = new Image(getClass().getResource("../images/goodjob.gif").toExternalForm());
ImageView imageView = new ImageView(image);
alert.setGraphic(imageView);
alert.showAndWait();
}else{
alert.setTitle("False answer");
alert.setContentText("I have a great message for you!");
alert.setContentText("press ok to continue");
Image image = new Image(getClass().getResource("../images/false.gif").toExternalForm());
ImageView imageView = new ImageView(image);
alert.setGraphic(imageView);
alert.showAndWait();
}
}
public void toHomescreen(ActionEvent event) throws IOException {
Parent tohome = FXMLLoader.load(getClass().getResource("homescreen.fxml"));
Scene homeScene = new Scene(tohome);
//pakt stage informatie
Stage window = (Stage)((Node)event.getSource()).getScene().getWindow();
window.setScene(homeScene);
window.show();
}
}
| True | 1,000 | 13 | 1,157 | 13 | 1,169 | 13 | 1,157 | 13 | 1,300 | 13 | false | false | false | false | false | true |
407 | 66468_2 | package nl.han.asd.app.lesson_1_2_recursie;
public class Hanoi {
private static final int AANTAL_SCHIJVEN = 64;
private static final int START = 1;
private static final int VIA = 2;
private static final int DOEL = 3;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
verplaats(AANTAL_SCHIJVEN, START, DOEL, VIA);
}
/**
* Verplaatst een hanoi-toren van een plek naar de andere.
*
* @param aantalSchijven Hoogte van de toren.
* @param start Plek waar de toren zich bevindt.
* @param doel Plek waar de toren naartoe moet.
* @param tussenplek Extra plek om te gebruiken.
*/
public static void verplaats(int aantalSchijven, int start, int doel, int tussenplek) {
// stopconditie: 1 schijf over, dat is gemakkelijk
if (aantalSchijven == 1) {
System.out.printf("Verplaats schijf van plek %d naar plek %d\n", start, doel);
} else {
// los het recursief op
// 1) de stapel op 1 na verplaatsen van start naar tussenplek
verplaats(aantalSchijven - 1, start, tussenplek, doel);
// 2) de onderste schijf verplaatsen van start naar doel
verplaats(1, start, doel, tussenplek);
// 3) de stapel op 1 na verplaatsen van tussenplek naar doel
verplaats(aantalSchijven - 1, tussenplek, doel, start);
}
}
}
| DennisBreuker/APP | examples/src/main/java/nl/han/asd/app/lesson_1_2_recursie/Hanoi.java | 484 | // stopconditie: 1 schijf over, dat is gemakkelijk | line_comment | nl | package nl.han.asd.app.lesson_1_2_recursie;
public class Hanoi {
private static final int AANTAL_SCHIJVEN = 64;
private static final int START = 1;
private static final int VIA = 2;
private static final int DOEL = 3;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
verplaats(AANTAL_SCHIJVEN, START, DOEL, VIA);
}
/**
* Verplaatst een hanoi-toren van een plek naar de andere.
*
* @param aantalSchijven Hoogte van de toren.
* @param start Plek waar de toren zich bevindt.
* @param doel Plek waar de toren naartoe moet.
* @param tussenplek Extra plek om te gebruiken.
*/
public static void verplaats(int aantalSchijven, int start, int doel, int tussenplek) {
// stopconditie: 1<SUF>
if (aantalSchijven == 1) {
System.out.printf("Verplaats schijf van plek %d naar plek %d\n", start, doel);
} else {
// los het recursief op
// 1) de stapel op 1 na verplaatsen van start naar tussenplek
verplaats(aantalSchijven - 1, start, tussenplek, doel);
// 2) de onderste schijf verplaatsen van start naar doel
verplaats(1, start, doel, tussenplek);
// 3) de stapel op 1 na verplaatsen van tussenplek naar doel
verplaats(aantalSchijven - 1, tussenplek, doel, start);
}
}
}
| True | 436 | 19 | 481 | 19 | 439 | 15 | 481 | 19 | 498 | 18 | false | false | false | false | false | true |
134 | 20470_0 | package presentation;
import patterns.component.SlideshowComposite;
/**
* <p>Presentation houdt de slides in de presentatie bij.</p>
* <p>Er is slechts ��n instantie van deze klasse aanwezig.</p>
* @author Ian F. Darwin, [email protected], Gert Florijn, Sylvia Stuurman
* @version 1.1 2002/12/17 Gert Florijn
* @version 1.2 2003/11/19 Sylvia Stuurman
* @version 1.3 2004/08/17 Sylvia Stuurman
* @version 1.4 2007/07/16 Sylvia Stuurman
* @version 1.5 2010/03/03 Sylvia Stuurman
* @version 1.6 2014/05/16 Sylvia Stuurman
* @version 1.7 - ?? Applied design @Amriet Jainandunsing
* @version 1.? 2022/11/03 Fixed opening from files via file explorer @Armando Gerard
*/
public class Presentation {
private String showTitle; // de titel van de presentatie
private SlideshowComposite slideshowComposite;
private static Presentation presentation;
private boolean isLocked = true;
public Presentation() {
if(presentation != null)
presentation.clear(true);
presentation = this;
isLocked = false;
}
public static Presentation getPresentation() {
return presentation;
}
public void setSlideshowComposite(SlideshowComposite slideshowComposite) {
this.slideshowComposite = slideshowComposite;
}
public String getTitle() {
return showTitle;
}
public void setTitle(String nt) {
showTitle = nt;
}
public SlideshowComposite getSlideshowComposite() {
return this.slideshowComposite;
}
public void setSlideNumber(int number) {
this.slideshowComposite.setActive(true);
this.slideshowComposite.setSlideNumber(number);
}
// Verwijder de presentatie, om klaar te zijn voor de volgende
public void clear(boolean locked) {
if(slideshowComposite != null) {
isLocked = locked;
slideshowComposite.setActive(!isLocked);
slideshowComposite.removeAll();
}
}
public void exit(int n) {
System.exit(n);
}
public boolean canQuit() {
// This would have changed if saving was implemented,
// it would check if there are processes active that need to be finished first
return true;
}
}
| Armandreano/ou-jabberpoint | src/presentation/Presentation.java | 695 | /**
* <p>Presentation houdt de slides in de presentatie bij.</p>
* <p>Er is slechts ��n instantie van deze klasse aanwezig.</p>
* @author Ian F. Darwin, [email protected], Gert Florijn, Sylvia Stuurman
* @version 1.1 2002/12/17 Gert Florijn
* @version 1.2 2003/11/19 Sylvia Stuurman
* @version 1.3 2004/08/17 Sylvia Stuurman
* @version 1.4 2007/07/16 Sylvia Stuurman
* @version 1.5 2010/03/03 Sylvia Stuurman
* @version 1.6 2014/05/16 Sylvia Stuurman
* @version 1.7 - ?? Applied design @Amriet Jainandunsing
* @version 1.? 2022/11/03 Fixed opening from files via file explorer @Armando Gerard
*/ | block_comment | nl | package presentation;
import patterns.component.SlideshowComposite;
/**
* <p>Presentation houdt de<SUF>*/
public class Presentation {
private String showTitle; // de titel van de presentatie
private SlideshowComposite slideshowComposite;
private static Presentation presentation;
private boolean isLocked = true;
public Presentation() {
if(presentation != null)
presentation.clear(true);
presentation = this;
isLocked = false;
}
public static Presentation getPresentation() {
return presentation;
}
public void setSlideshowComposite(SlideshowComposite slideshowComposite) {
this.slideshowComposite = slideshowComposite;
}
public String getTitle() {
return showTitle;
}
public void setTitle(String nt) {
showTitle = nt;
}
public SlideshowComposite getSlideshowComposite() {
return this.slideshowComposite;
}
public void setSlideNumber(int number) {
this.slideshowComposite.setActive(true);
this.slideshowComposite.setSlideNumber(number);
}
// Verwijder de presentatie, om klaar te zijn voor de volgende
public void clear(boolean locked) {
if(slideshowComposite != null) {
isLocked = locked;
slideshowComposite.setActive(!isLocked);
slideshowComposite.removeAll();
}
}
public void exit(int n) {
System.exit(n);
}
public boolean canQuit() {
// This would have changed if saving was implemented,
// it would check if there are processes active that need to be finished first
return true;
}
}
| True | 576 | 255 | 679 | 288 | 634 | 242 | 679 | 288 | 782 | 276 | true | true | true | true | true | false |
2,289 | 8325_5 | package opdracht_B7;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
FileReader fr = new FileReader(
"/Users/Klaas/Documents/workspace/Project_week/src/opdracht_B7/cijfers.txt");
BufferedReader br = new BufferedReader(fr);
while (true) {
String s = br.readLine();
if (s == null)
break;
// scanner maken van de line, en ";" er af halen
Scanner cijfer = new Scanner(s).useDelimiter(";");
// array maken met alle doubles per line ter grote van de txt
// file
Double[] lijst = new Double[cijfer.nextLine().length()];
// door elke lijn moeten we heen lezen,
// als we in die lijst zijn, moeten we alle Doubles er uit
// halen,
// deze bijelkaar optellen, delen door het totaal aantal doubles
// in de lijn
// dat is het gemiddelde cijfer van die klas!
// vervolgens alle cijfers vergelijken met het gemiddelde en de
// cijfers
// eronder printen!
int i = 0;
while (cijfer.hasNextDouble()) {
lijst[i++] = cijfer.nextDouble();
System.out.println("test");
}
for (int index = 0; index > lijst.length; index++) {
System.out.println(lijst);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| bramhu/miniprojectp2 | Project Code/src/opdracht_B7/Main.java | 525 | // in de lijn | line_comment | nl | package opdracht_B7;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
FileReader fr = new FileReader(
"/Users/Klaas/Documents/workspace/Project_week/src/opdracht_B7/cijfers.txt");
BufferedReader br = new BufferedReader(fr);
while (true) {
String s = br.readLine();
if (s == null)
break;
// scanner maken van de line, en ";" er af halen
Scanner cijfer = new Scanner(s).useDelimiter(";");
// array maken met alle doubles per line ter grote van de txt
// file
Double[] lijst = new Double[cijfer.nextLine().length()];
// door elke lijn moeten we heen lezen,
// als we in die lijst zijn, moeten we alle Doubles er uit
// halen,
// deze bijelkaar optellen, delen door het totaal aantal doubles
// in de<SUF>
// dat is het gemiddelde cijfer van die klas!
// vervolgens alle cijfers vergelijken met het gemiddelde en de
// cijfers
// eronder printen!
int i = 0;
while (cijfer.hasNextDouble()) {
lijst[i++] = cijfer.nextDouble();
System.out.println("test");
}
for (int index = 0; index > lijst.length; index++) {
System.out.println(lijst);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| True | 404 | 5 | 475 | 5 | 432 | 4 | 475 | 5 | 602 | 5 | false | false | false | false | false | true |
871 | 36783_6 | package model;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import model.klas.Klas;
import model.persoon.Docent;
import model.persoon.Student;
public class PrIS {
private ArrayList<Docent> deDocenten;
private ArrayList<Student> deStudenten;
private ArrayList<Klas> deKlassen;
/**
* De constructor maakt een set met standaard-data aan. Deze data moet nog
* uitgebreidt worden met rooster gegevens die uit een bestand worden ingelezen,
* maar dat is geen onderdeel van deze demo-applicatie!
*
* De klasse PrIS (PresentieInformatieSysteem) heeft nu een meervoudige
* associatie met de klassen Docent, Student, Vakken en Klassen Uiteraard kan
* dit nog veel verder uitgebreid en aangepast worden!
*
* De klasse fungeert min of meer als ingangspunt voor het domeinmodel. Op dit
* moment zijn de volgende methoden aanroepbaar:
*
* String login(String gebruikersnaam, String wachtwoord) Docent
* getDocent(String gebruikersnaam) Student getStudent(String gebruikersnaam)
* ArrayList<Student> getStudentenVanKlas(String klasCode)
*
* Methode login geeft de rol van de gebruiker die probeert in te loggen, dat
* kan 'student', 'docent' of 'undefined' zijn! Die informatie kan gebruikt
* worden om in de Polymer-GUI te bepalen wat het volgende scherm is dat getoond
* moet worden.
*
*/
public PrIS() {
deDocenten = new ArrayList<Docent>();
deStudenten = new ArrayList<Student>();
deKlassen = new ArrayList<Klas>(); // Inladen klassen
vulKlassen(deKlassen); // Inladen studenten in klassen
vulStudenten(deStudenten, deKlassen);
// Inladen docenten
vulDocenten(deDocenten);
} // Einde Pris constructor
// deze method is static onderdeel van PrIS omdat hij als hulp methode
// in veel controllers gebruikt wordt
// een standaardDatumString heeft formaat YYYY-MM-DD
public static Calendar standaardDatumStringToCal(String pStadaardDatumString) {
Calendar lCal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
lCal.setTime(sdf.parse(pStadaardDatumString));
} catch (ParseException e) {
e.printStackTrace();
lCal = null;
}
return lCal;
}
// deze method is static onderdeel van PrIS omdat hij als hulp methode
// in veel controllers gebruikt wordt
// een standaardDatumString heeft formaat YYYY-MM-DD
public static String calToStandaardDatumString(Calendar pCalendar) {
int lJaar = pCalendar.get(Calendar.YEAR);
int lMaand = pCalendar.get(Calendar.MONTH) + 1;
int lDag = pCalendar.get(Calendar.DAY_OF_MONTH);
String lMaandStr = Integer.toString(lMaand);
if (lMaandStr.length() == 1) {
lMaandStr = "0" + lMaandStr;
}
String lDagStr = Integer.toString(lDag);
if (lDagStr.length() == 1) {
lDagStr = "0" + lDagStr;
}
String lString = Integer.toString(lJaar) + "-" + lMaandStr + "-" + lDagStr;
return lString;
}
public Docent getDocent(String gebruikersnaam) {
return deDocenten.stream().filter(d -> d.getGebruikersnaam().equals(gebruikersnaam)).findFirst().orElse(null);
}
public Klas getKlasVanStudent(Student pStudent) {
return deKlassen.stream().filter(k -> k.bevatStudent(pStudent)).findFirst().orElse(null);
}
public Student getStudent(String pGebruikersnaam) {
return deStudenten.stream().filter(s -> s.getGebruikersnaam().equals(pGebruikersnaam)).findFirst().orElse(null);
}
public Student getStudent(int pStudentNummer) {
return deStudenten.stream().filter(s -> s.getStudentNummer() == pStudentNummer).findFirst().orElse(null);
}
public String login(String gebruikersnaam, String wachtwoord) {
for (Docent d : deDocenten) {
if (d.getGebruikersnaam().equals(gebruikersnaam)) {
if (d.komtWachtwoordOvereen(wachtwoord)) {
return "docent";
}
}
}
for (Student s : deStudenten) {
if (s.getGebruikersnaam().equals(gebruikersnaam)) {
if (s.komtWachtwoordOvereen(wachtwoord)) {
return "student";
}
}
}
return "undefined";
}
private void vulDocenten(ArrayList<Docent> pDocenten) {
String csvFile = "././CSV/docenten.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] element = line.split(cvsSplitBy);
String gebruikersnaam = element[0].toLowerCase();
String voornaam = element[1];
String tussenvoegsel = element[2];
String achternaam = element[3];
pDocenten.add(new Docent(voornaam, tussenvoegsel, achternaam, "geheim", gebruikersnaam, 1));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// close the bufferedReader if opened.
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// verify content of arraylist, if empty add Jos
if (pDocenten.isEmpty())
pDocenten.add(new Docent("Jos", "van", "Reenen", "supergeheim", "[email protected]", 1));
}
}
private void vulKlassen(ArrayList<Klas> pKlassen) {
// TICT-SIE-VIA is de klascode die ook in de rooster file voorkomt
// V1A is de naam van de klas die ook als file naam voor de studenten van die
// klas wordt gebruikt
Klas k1 = new Klas("TICT-SIE-V1A", "V1A");
Klas k2 = new Klas("TICT-SIE-V1B", "V1B");
Klas k3 = new Klas("TICT-SIE-V1C", "V1C");
Klas k4 = new Klas("TICT-SIE-V1D", "V1D");
Klas k5 = new Klas("TICT-SIE-V1E", "V1E");
pKlassen.add(k1);
pKlassen.add(k2);
pKlassen.add(k3);
pKlassen.add(k4);
pKlassen.add(k5);
}
private void vulStudenten(ArrayList<Student> pStudenten, ArrayList<Klas> pKlassen) {
Student lStudent;
Student dummyStudent = new Student("Stu", "de", "Student", "geheim", "[email protected]", 0);
for (Klas k : pKlassen) {
// per klas
String csvFile = "././CSV/" + k.getNaam() + ".csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// line = line.replace(",,", ", ,");
// use comma as separator
String[] element = line.split(cvsSplitBy);
String gebruikersnaam = (element[3] + "." + element[2] + element[1] + "@student.hu.nl")
.toLowerCase();
// verwijder spaties tussen dubbele voornamen en tussen bv van der
gebruikersnaam = gebruikersnaam.replace(" ", "");
String lStudentNrString = element[0];
int lStudentNr = Integer.parseInt(lStudentNrString);
// Volgorde 3-2-1 = voornaam, tussenvoegsel en achternaam
lStudent = new Student(element[3], element[2], element[1], "geheim", gebruikersnaam, lStudentNr);
pStudenten.add(lStudent);
k.voegStudentToe(lStudent);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// mocht deze klas geen studenten bevatten omdat de csv niet heeft gewerkt:
if (k.getStudenten().isEmpty()) {
k.voegStudentToe(dummyStudent);
System.out.println("Had to add Stu de Student to class: " + k.getKlasCode());
}
}
}
// mocht de lijst met studenten nu nog leeg zijn
if (pStudenten.isEmpty())
pStudenten.add(dummyStudent);
}
}
| Josvanreenen/GroupProject2019 | src/model/PrIS.java | 2,825 | // deze method is static onderdeel van PrIS omdat hij als hulp methode | line_comment | nl | package model;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import model.klas.Klas;
import model.persoon.Docent;
import model.persoon.Student;
public class PrIS {
private ArrayList<Docent> deDocenten;
private ArrayList<Student> deStudenten;
private ArrayList<Klas> deKlassen;
/**
* De constructor maakt een set met standaard-data aan. Deze data moet nog
* uitgebreidt worden met rooster gegevens die uit een bestand worden ingelezen,
* maar dat is geen onderdeel van deze demo-applicatie!
*
* De klasse PrIS (PresentieInformatieSysteem) heeft nu een meervoudige
* associatie met de klassen Docent, Student, Vakken en Klassen Uiteraard kan
* dit nog veel verder uitgebreid en aangepast worden!
*
* De klasse fungeert min of meer als ingangspunt voor het domeinmodel. Op dit
* moment zijn de volgende methoden aanroepbaar:
*
* String login(String gebruikersnaam, String wachtwoord) Docent
* getDocent(String gebruikersnaam) Student getStudent(String gebruikersnaam)
* ArrayList<Student> getStudentenVanKlas(String klasCode)
*
* Methode login geeft de rol van de gebruiker die probeert in te loggen, dat
* kan 'student', 'docent' of 'undefined' zijn! Die informatie kan gebruikt
* worden om in de Polymer-GUI te bepalen wat het volgende scherm is dat getoond
* moet worden.
*
*/
public PrIS() {
deDocenten = new ArrayList<Docent>();
deStudenten = new ArrayList<Student>();
deKlassen = new ArrayList<Klas>(); // Inladen klassen
vulKlassen(deKlassen); // Inladen studenten in klassen
vulStudenten(deStudenten, deKlassen);
// Inladen docenten
vulDocenten(deDocenten);
} // Einde Pris constructor
// deze method is static onderdeel van PrIS omdat hij als hulp methode
// in veel controllers gebruikt wordt
// een standaardDatumString heeft formaat YYYY-MM-DD
public static Calendar standaardDatumStringToCal(String pStadaardDatumString) {
Calendar lCal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
lCal.setTime(sdf.parse(pStadaardDatumString));
} catch (ParseException e) {
e.printStackTrace();
lCal = null;
}
return lCal;
}
// deze method<SUF>
// in veel controllers gebruikt wordt
// een standaardDatumString heeft formaat YYYY-MM-DD
public static String calToStandaardDatumString(Calendar pCalendar) {
int lJaar = pCalendar.get(Calendar.YEAR);
int lMaand = pCalendar.get(Calendar.MONTH) + 1;
int lDag = pCalendar.get(Calendar.DAY_OF_MONTH);
String lMaandStr = Integer.toString(lMaand);
if (lMaandStr.length() == 1) {
lMaandStr = "0" + lMaandStr;
}
String lDagStr = Integer.toString(lDag);
if (lDagStr.length() == 1) {
lDagStr = "0" + lDagStr;
}
String lString = Integer.toString(lJaar) + "-" + lMaandStr + "-" + lDagStr;
return lString;
}
public Docent getDocent(String gebruikersnaam) {
return deDocenten.stream().filter(d -> d.getGebruikersnaam().equals(gebruikersnaam)).findFirst().orElse(null);
}
public Klas getKlasVanStudent(Student pStudent) {
return deKlassen.stream().filter(k -> k.bevatStudent(pStudent)).findFirst().orElse(null);
}
public Student getStudent(String pGebruikersnaam) {
return deStudenten.stream().filter(s -> s.getGebruikersnaam().equals(pGebruikersnaam)).findFirst().orElse(null);
}
public Student getStudent(int pStudentNummer) {
return deStudenten.stream().filter(s -> s.getStudentNummer() == pStudentNummer).findFirst().orElse(null);
}
public String login(String gebruikersnaam, String wachtwoord) {
for (Docent d : deDocenten) {
if (d.getGebruikersnaam().equals(gebruikersnaam)) {
if (d.komtWachtwoordOvereen(wachtwoord)) {
return "docent";
}
}
}
for (Student s : deStudenten) {
if (s.getGebruikersnaam().equals(gebruikersnaam)) {
if (s.komtWachtwoordOvereen(wachtwoord)) {
return "student";
}
}
}
return "undefined";
}
private void vulDocenten(ArrayList<Docent> pDocenten) {
String csvFile = "././CSV/docenten.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] element = line.split(cvsSplitBy);
String gebruikersnaam = element[0].toLowerCase();
String voornaam = element[1];
String tussenvoegsel = element[2];
String achternaam = element[3];
pDocenten.add(new Docent(voornaam, tussenvoegsel, achternaam, "geheim", gebruikersnaam, 1));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// close the bufferedReader if opened.
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// verify content of arraylist, if empty add Jos
if (pDocenten.isEmpty())
pDocenten.add(new Docent("Jos", "van", "Reenen", "supergeheim", "[email protected]", 1));
}
}
private void vulKlassen(ArrayList<Klas> pKlassen) {
// TICT-SIE-VIA is de klascode die ook in de rooster file voorkomt
// V1A is de naam van de klas die ook als file naam voor de studenten van die
// klas wordt gebruikt
Klas k1 = new Klas("TICT-SIE-V1A", "V1A");
Klas k2 = new Klas("TICT-SIE-V1B", "V1B");
Klas k3 = new Klas("TICT-SIE-V1C", "V1C");
Klas k4 = new Klas("TICT-SIE-V1D", "V1D");
Klas k5 = new Klas("TICT-SIE-V1E", "V1E");
pKlassen.add(k1);
pKlassen.add(k2);
pKlassen.add(k3);
pKlassen.add(k4);
pKlassen.add(k5);
}
private void vulStudenten(ArrayList<Student> pStudenten, ArrayList<Klas> pKlassen) {
Student lStudent;
Student dummyStudent = new Student("Stu", "de", "Student", "geheim", "[email protected]", 0);
for (Klas k : pKlassen) {
// per klas
String csvFile = "././CSV/" + k.getNaam() + ".csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// line = line.replace(",,", ", ,");
// use comma as separator
String[] element = line.split(cvsSplitBy);
String gebruikersnaam = (element[3] + "." + element[2] + element[1] + "@student.hu.nl")
.toLowerCase();
// verwijder spaties tussen dubbele voornamen en tussen bv van der
gebruikersnaam = gebruikersnaam.replace(" ", "");
String lStudentNrString = element[0];
int lStudentNr = Integer.parseInt(lStudentNrString);
// Volgorde 3-2-1 = voornaam, tussenvoegsel en achternaam
lStudent = new Student(element[3], element[2], element[1], "geheim", gebruikersnaam, lStudentNr);
pStudenten.add(lStudent);
k.voegStudentToe(lStudent);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// mocht deze klas geen studenten bevatten omdat de csv niet heeft gewerkt:
if (k.getStudenten().isEmpty()) {
k.voegStudentToe(dummyStudent);
System.out.println("Had to add Stu de Student to class: " + k.getKlasCode());
}
}
}
// mocht de lijst met studenten nu nog leeg zijn
if (pStudenten.isEmpty())
pStudenten.add(dummyStudent);
}
}
| True | 2,261 | 18 | 2,602 | 21 | 2,399 | 14 | 2,602 | 21 | 2,995 | 20 | false | false | false | false | false | true |
1,417 | 164959_4 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
*
* @author R. Springer
*/
public class MyWorld extends World {
private CollisionEngine ce;
/**
* Constructor for objects of class MyWorld.
*
*/
public MyWorld() {
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(800, 800, 1, false);
// this.setBackground("mar.gif");
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,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,14,-1,-1,13,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,94,-1,8,11,11,8,-1,-1,-1,-1,-1,-1,-1,-1,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,8,8,8,8,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,94,-1,8,10,10,8,-1,-1,-1,-1,-1,-1,-1,-1,7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,114,114,-1,12,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,6,6,6,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,94,-1,8,8,8,8,-1,-1,-1,-1,-1,-1,7,8,9,5,5,5,5,5,5,5,5,8,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,6,6,6,6,-1,-1,-1,-1,-1,-1,-1,-1,114,114,94,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,6,6,6,6,-1,114,114,117,-1,14,-1,-1,7,8,8,-1,-1,-1,-1,-1,-1,-1,-1,7,-1,-1,114,114,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,6,6,6,6,8,8,8,8,8,8,8,-1,-1,-1,-1,-1,-1,7,-1,5,5,5,7,8,8,8,8,9,8,8,8,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,6,6,6,6,11,11,11,11,11,11,11,11,11,11,11,11,7,8,9,11,11,11,11,11,11,11,11,11,11,11,11,7,-1,-1,-1,-1,-1,-1,-1,-1,8,8,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,6,6,6,6,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,7,-1,117,114,7,-1,114,7,10,10,6,-1,-1,117,114,12,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,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,8,8,8,8,8,8,10,10,10,6,8,8,8,8,8,8,8,8,8,11,11,11,11,11,11,11,11,-1,-1,-1},
{-1,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,10,10,10,-1,-1,-1},
{-1,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,10,10,10,-1,-1,-1},
};
// Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen
TileEngine te = new TileEngine(this, 60, 60, map);
// Declarenre en initialiseren van de camera klasse met de TileEngine klasse
// zodat de camera weet welke tiles allemaal moeten meebewegen met de camera
Camera camera = new Camera(te);
// Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse
// moet de klasse Mover extenden voor de camera om te werken
Hero hero = new Hero();
// Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan.
camera.follow(hero);
// Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies
addObject(camera, 0, 0);
addObject(hero, 300, 300);
addObject(new Enemy(), 2370, 810);
addObject(new deur(), 3070, 1165);
addObject(new deur2(), 3070, 1115);
addObject(new greenkey(), 1110, 1000);
addObject(new greenbox(), 2370, 1165);
addObject(new redkey(), 1110, 1000);
addObject(new redbox(), 2370, 1165);
addObject(new bluekey(), 1110, 1000);
addObject(new bluebox(), 2370, 1165);
// addObject(new munt(), 800, 800);
addObject(new gem(), 2370, 1165);
// Force act zodat de camera op de juist plek staat.
camera.act();
hero.act();
// Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen.
// De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan.
ce = new CollisionEngine(te, camera);
// Toevoegen van de mover instantie of een extentie hiervan
ce.addCollidingMover(hero);
}
@Override
public void act() {
ce.update();
}
}
| ROCMondriaanTIN/project-greenfoot-game-pedrodegroot | MyWorld.java | 3,744 | // Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen | line_comment | nl | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
*
* @author R. Springer
*/
public class MyWorld extends World {
private CollisionEngine ce;
/**
* Constructor for objects of class MyWorld.
*
*/
public MyWorld() {
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(800, 800, 1, false);
// this.setBackground("mar.gif");
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,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,34,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,14,-1,-1,13,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,94,-1,8,11,11,8,-1,-1,-1,-1,-1,-1,-1,-1,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,8,8,8,8,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,94,-1,8,10,10,8,-1,-1,-1,-1,-1,-1,-1,-1,7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,114,114,-1,12,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,6,6,6,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,94,-1,8,8,8,8,-1,-1,-1,-1,-1,-1,7,8,9,5,5,5,5,5,5,5,5,8,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,6,6,6,6,-1,-1,-1,-1,-1,-1,-1,-1,114,114,94,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,6,6,6,6,-1,114,114,117,-1,14,-1,-1,7,8,8,-1,-1,-1,-1,-1,-1,-1,-1,7,-1,-1,114,114,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,6,6,6,6,8,8,8,8,8,8,8,-1,-1,-1,-1,-1,-1,7,-1,5,5,5,7,8,8,8,8,9,8,8,8,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,6,6,6,6,11,11,11,11,11,11,11,11,11,11,11,11,7,8,9,11,11,11,11,11,11,11,11,11,11,11,11,7,-1,-1,-1,-1,-1,-1,-1,-1,8,8,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,6,6,6,6,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,7,-1,117,114,7,-1,114,7,10,10,6,-1,-1,117,114,12,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,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,8,8,8,8,8,8,10,10,10,6,8,8,8,8,8,8,8,8,8,11,11,11,11,11,11,11,11,-1,-1,-1},
{-1,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,10,10,10,-1,-1,-1},
{-1,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,10,10,10,-1,-1,-1},
};
// Declareren en<SUF>
TileEngine te = new TileEngine(this, 60, 60, map);
// Declarenre en initialiseren van de camera klasse met de TileEngine klasse
// zodat de camera weet welke tiles allemaal moeten meebewegen met de camera
Camera camera = new Camera(te);
// Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse
// moet de klasse Mover extenden voor de camera om te werken
Hero hero = new Hero();
// Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan.
camera.follow(hero);
// Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies
addObject(camera, 0, 0);
addObject(hero, 300, 300);
addObject(new Enemy(), 2370, 810);
addObject(new deur(), 3070, 1165);
addObject(new deur2(), 3070, 1115);
addObject(new greenkey(), 1110, 1000);
addObject(new greenbox(), 2370, 1165);
addObject(new redkey(), 1110, 1000);
addObject(new redbox(), 2370, 1165);
addObject(new bluekey(), 1110, 1000);
addObject(new bluebox(), 2370, 1165);
// addObject(new munt(), 800, 800);
addObject(new gem(), 2370, 1165);
// Force act zodat de camera op de juist plek staat.
camera.act();
hero.act();
// Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen.
// De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan.
ce = new CollisionEngine(te, camera);
// Toevoegen van de mover instantie of een extentie hiervan
ce.addCollidingMover(hero);
}
@Override
public void act() {
ce.update();
}
}
| True | 3,925 | 24 | 3,978 | 25 | 3,990 | 21 | 3,978 | 25 | 4,074 | 25 | false | false | false | false | false | true |
1,748 | 17149_4 | package me.thomasvt.magisterclient;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.CookieSyncManager;
import android.webkit.WebBackForwardList;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import me.thomasvt.magisterclient.db.School;
import me.thomasvt.magisterclient.db.SchoolDatabaseHelper;
public class Magister extends Activity {
private WebView mWebView;
private SharedPreferences mPreferences;
private SchoolDatabaseHelper mDatabase;
public static final String TAG = "Magistre";
private static final String PREF_HIDEMENU = "hidemenu";
public static final String PREF_HOST = "host";
public static final String PREF_FAVOURITE_INFO_SHOWN = "favourite_info_shown";
public static final String PREF_HIDEMENU_WARNING_SHOWN = "hidemenu_warning_shown";
public static final String PREF_LAST_SCHOOL_LIST_UPDATE = "last_school_list_update";
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate");
super.onCreate(savedInstanceState);
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
mDatabase = new SchoolDatabaseHelper(this);
if (mPreferences.getBoolean(PREF_HIDEMENU, false)) {
getActionBar().hide();
}
CookieSyncManager.createInstance(this).startSync();
String oldUrl = mPreferences.getString("url", null);
if(oldUrl != null) {
mPreferences.edit()
.putString(PREF_HOST, oldUrl.endsWith(".magister.net") ? oldUrl : oldUrl + ".magister.net")
.remove("url")
.apply();
}
String url = mPreferences.getString(PREF_HOST, null);
if(url == null) {
selectSchool();
finish();
return;
}
setContentView(R.layout.activity_magister);
mWebView = (WebView) findViewById(R.id.activity_magister_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setAllowFileAccess(true);
webSettings.setAppCacheEnabled(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setDatabaseEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportMultipleWindows(false);
webSettings.setAppCacheMaxSize(1024 * 1024 * 8);
webSettings.setAppCachePath(getCacheDir().getAbsolutePath());
//TODO: Better cache function
if (Build.VERSION.SDK_INT >= 16) {
webSettings.setAllowUniversalAccessFromFileURLs(true);
webSettings.setAllowFileAccessFromFileURLs(true);
}
mWebView.setWebViewClient(new MyAppWebViewClient(this));
if(savedInstanceState == null) {
loadWebsite();
}
giveVoteOption(); //ask for rating if requirement met
}
protected void onDestroy() {
Log.i(TAG, "onDestroy");
CookieSyncManager.getInstance().stopSync();
super.onDestroy();
}
protected void onStart() {
Log.i(TAG, "onStart");
super.onStart();
}
protected void onStop() {
Log.i(TAG, "onStop");
super.onStop();
//GoogleAnalytics.getInstance(this).reportActivityStop(this); //Stop the analytics tracking
}
private boolean isNetworkAvailable() {
Log.i(TAG, "isNetworkAvailable");
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private void loadWebsite() {
String url = "https://" + getHost() + "/";
Log.i(TAG, "loadWebsite");
mWebView.loadUrl("about:blank");
WebSettings webSettings = mWebView.getSettings();
if (!isNetworkAvailable()) { // loading offline
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
mWebView.loadUrl(url + "leerling/#/agenda");
Toast.makeText(Magister.this, R.string.offline_mode, Toast.LENGTH_LONG).show();
}
else {
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
mWebView.loadUrl(url);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mWebView.restoreState(savedInstanceState);
}
public String getHost() {
return mPreferences.getString(PREF_HOST, null);
}
private void selectSchool() {
Log.i(TAG, "selectSchool");
startActivity(new Intent(this, SchoolSelector.class));
}
private void giveVoteOption() {
Log.i(TAG, "giveVoteOption");
AppRater appRater = new AppRater(this);
appRater.setDaysBeforePrompt(3);
appRater.setLaunchesBeforePrompt(7);
appRater.setPhrases("Waardeer deze app", "We zouden het erg leuk vinden als je de app waardeerd op Google Play, Bedankt voor je support!", "Waardeer", "Later", "Nee bedankt");
appRater.setTargetUri("https://play.google.com/store/apps/details?id=me.thomasvt.magisterclient");
appRater.setPreferenceKeys("app_rater", "flag_dont_show", "launch_count", "first_launch_time");
appRater.show();
}
private Toast mExitToast;
@Override
public void onBackPressed() {
// Tobias: Degelijkere methode om te checken of een Toast nog zichtbaar is.
if (mExitToast != null && mExitToast.getView() != null && mExitToast.getView().isShown()) {
mExitToast.cancel();
finish();
return;
}
WebBackForwardList history = mWebView.copyBackForwardList();
int prevIndex = history.getCurrentIndex() - 1;
if (mWebView != null && !mWebView.getUrl().equals("https://" + getHost() + "/magister/#/vandaag") && mWebView.canGoBack() && !(prevIndex >= 0 && history.getItemAtIndex(prevIndex).getUrl().equals("about:blank"))) {
mWebView.goBack();
}
else {
mExitToast = Toast.makeText(this, R.string.repeat_click_to_close, Toast.LENGTH_SHORT);
mExitToast.show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.magister, menu);
return true;
}
public boolean onPrepareOptionsMenu(Menu menu) {
boolean actionBarHidden = mPreferences.getBoolean(PREF_HIDEMENU, false);
menu.findItem(R.id.action_hide_actionbar).setVisible(!actionBarHidden).setEnabled(!actionBarHidden);
menu.findItem(R.id.action_show_actionbar).setVisible(actionBarHidden).setEnabled(actionBarHidden);
boolean showFavourites = mDatabase.hasFavourites();
menu.findItem(R.id.favourite_schools).setVisible(showFavourites).setEnabled(showFavourites);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_reload:
mWebView.reload();
return true;
case R.id.action_clear_cache:
mWebView.clearCache(true);
mWebView.reload();
return true;
case R.id.action_change:
selectSchool();
return true;
case R.id.action_hide_actionbar:
if(mPreferences.getBoolean(PREF_HIDEMENU_WARNING_SHOWN, false)) {
mPreferences.edit().putBoolean(PREF_HIDEMENU, true).apply();
getActionBar().hide();
}
else {
new AlertDialog.Builder(this)
.setTitle(R.string.action_hide_actionbar)
.setMessage(R.string.warning_hide_actionbar)
.setNegativeButton(R.string.no, null)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
getActionBar().hide();
mPreferences.edit()
.putBoolean(PREF_HIDEMENU, true)
.putBoolean(PREF_HIDEMENU_WARNING_SHOWN, true)
.apply();
}
})
.show();
}
return true;
case R.id.action_show_actionbar:
getActionBar().show();
mPreferences.edit().putBoolean(PREF_HIDEMENU, false).apply();
return true;
case R.id.favourite_schools:
final List<School> favouriteList = mDatabase.getFavourites();
Utils.sortSchoolList(favouriteList);
CharSequence[] favourites = new CharSequence[favouriteList.size()];
for(int i = 0; i < favouriteList.size(); i++) {
favourites[i] = favouriteList.get(i).name;
}
new AlertDialog.Builder(Magister.this)
.setItems(favourites, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
mPreferences.edit().putString(PREF_HOST, favouriteList.get(i).host).apply();
loadWebsite();
}
})
.show();
return true;
}
return false;
}
} | Tobiaqs/MagisterClient | app/src/main/java/me/thomasvt/magisterclient/Magister.java | 2,993 | // Tobias: Degelijkere methode om te checken of een Toast nog zichtbaar is. | line_comment | nl | package me.thomasvt.magisterclient;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.CookieSyncManager;
import android.webkit.WebBackForwardList;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import me.thomasvt.magisterclient.db.School;
import me.thomasvt.magisterclient.db.SchoolDatabaseHelper;
public class Magister extends Activity {
private WebView mWebView;
private SharedPreferences mPreferences;
private SchoolDatabaseHelper mDatabase;
public static final String TAG = "Magistre";
private static final String PREF_HIDEMENU = "hidemenu";
public static final String PREF_HOST = "host";
public static final String PREF_FAVOURITE_INFO_SHOWN = "favourite_info_shown";
public static final String PREF_HIDEMENU_WARNING_SHOWN = "hidemenu_warning_shown";
public static final String PREF_LAST_SCHOOL_LIST_UPDATE = "last_school_list_update";
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate");
super.onCreate(savedInstanceState);
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
mDatabase = new SchoolDatabaseHelper(this);
if (mPreferences.getBoolean(PREF_HIDEMENU, false)) {
getActionBar().hide();
}
CookieSyncManager.createInstance(this).startSync();
String oldUrl = mPreferences.getString("url", null);
if(oldUrl != null) {
mPreferences.edit()
.putString(PREF_HOST, oldUrl.endsWith(".magister.net") ? oldUrl : oldUrl + ".magister.net")
.remove("url")
.apply();
}
String url = mPreferences.getString(PREF_HOST, null);
if(url == null) {
selectSchool();
finish();
return;
}
setContentView(R.layout.activity_magister);
mWebView = (WebView) findViewById(R.id.activity_magister_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setAllowFileAccess(true);
webSettings.setAppCacheEnabled(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setDatabaseEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportMultipleWindows(false);
webSettings.setAppCacheMaxSize(1024 * 1024 * 8);
webSettings.setAppCachePath(getCacheDir().getAbsolutePath());
//TODO: Better cache function
if (Build.VERSION.SDK_INT >= 16) {
webSettings.setAllowUniversalAccessFromFileURLs(true);
webSettings.setAllowFileAccessFromFileURLs(true);
}
mWebView.setWebViewClient(new MyAppWebViewClient(this));
if(savedInstanceState == null) {
loadWebsite();
}
giveVoteOption(); //ask for rating if requirement met
}
protected void onDestroy() {
Log.i(TAG, "onDestroy");
CookieSyncManager.getInstance().stopSync();
super.onDestroy();
}
protected void onStart() {
Log.i(TAG, "onStart");
super.onStart();
}
protected void onStop() {
Log.i(TAG, "onStop");
super.onStop();
//GoogleAnalytics.getInstance(this).reportActivityStop(this); //Stop the analytics tracking
}
private boolean isNetworkAvailable() {
Log.i(TAG, "isNetworkAvailable");
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private void loadWebsite() {
String url = "https://" + getHost() + "/";
Log.i(TAG, "loadWebsite");
mWebView.loadUrl("about:blank");
WebSettings webSettings = mWebView.getSettings();
if (!isNetworkAvailable()) { // loading offline
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
mWebView.loadUrl(url + "leerling/#/agenda");
Toast.makeText(Magister.this, R.string.offline_mode, Toast.LENGTH_LONG).show();
}
else {
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
mWebView.loadUrl(url);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mWebView.restoreState(savedInstanceState);
}
public String getHost() {
return mPreferences.getString(PREF_HOST, null);
}
private void selectSchool() {
Log.i(TAG, "selectSchool");
startActivity(new Intent(this, SchoolSelector.class));
}
private void giveVoteOption() {
Log.i(TAG, "giveVoteOption");
AppRater appRater = new AppRater(this);
appRater.setDaysBeforePrompt(3);
appRater.setLaunchesBeforePrompt(7);
appRater.setPhrases("Waardeer deze app", "We zouden het erg leuk vinden als je de app waardeerd op Google Play, Bedankt voor je support!", "Waardeer", "Later", "Nee bedankt");
appRater.setTargetUri("https://play.google.com/store/apps/details?id=me.thomasvt.magisterclient");
appRater.setPreferenceKeys("app_rater", "flag_dont_show", "launch_count", "first_launch_time");
appRater.show();
}
private Toast mExitToast;
@Override
public void onBackPressed() {
// Tobias: Degelijkere<SUF>
if (mExitToast != null && mExitToast.getView() != null && mExitToast.getView().isShown()) {
mExitToast.cancel();
finish();
return;
}
WebBackForwardList history = mWebView.copyBackForwardList();
int prevIndex = history.getCurrentIndex() - 1;
if (mWebView != null && !mWebView.getUrl().equals("https://" + getHost() + "/magister/#/vandaag") && mWebView.canGoBack() && !(prevIndex >= 0 && history.getItemAtIndex(prevIndex).getUrl().equals("about:blank"))) {
mWebView.goBack();
}
else {
mExitToast = Toast.makeText(this, R.string.repeat_click_to_close, Toast.LENGTH_SHORT);
mExitToast.show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.magister, menu);
return true;
}
public boolean onPrepareOptionsMenu(Menu menu) {
boolean actionBarHidden = mPreferences.getBoolean(PREF_HIDEMENU, false);
menu.findItem(R.id.action_hide_actionbar).setVisible(!actionBarHidden).setEnabled(!actionBarHidden);
menu.findItem(R.id.action_show_actionbar).setVisible(actionBarHidden).setEnabled(actionBarHidden);
boolean showFavourites = mDatabase.hasFavourites();
menu.findItem(R.id.favourite_schools).setVisible(showFavourites).setEnabled(showFavourites);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_reload:
mWebView.reload();
return true;
case R.id.action_clear_cache:
mWebView.clearCache(true);
mWebView.reload();
return true;
case R.id.action_change:
selectSchool();
return true;
case R.id.action_hide_actionbar:
if(mPreferences.getBoolean(PREF_HIDEMENU_WARNING_SHOWN, false)) {
mPreferences.edit().putBoolean(PREF_HIDEMENU, true).apply();
getActionBar().hide();
}
else {
new AlertDialog.Builder(this)
.setTitle(R.string.action_hide_actionbar)
.setMessage(R.string.warning_hide_actionbar)
.setNegativeButton(R.string.no, null)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
getActionBar().hide();
mPreferences.edit()
.putBoolean(PREF_HIDEMENU, true)
.putBoolean(PREF_HIDEMENU_WARNING_SHOWN, true)
.apply();
}
})
.show();
}
return true;
case R.id.action_show_actionbar:
getActionBar().show();
mPreferences.edit().putBoolean(PREF_HIDEMENU, false).apply();
return true;
case R.id.favourite_schools:
final List<School> favouriteList = mDatabase.getFavourites();
Utils.sortSchoolList(favouriteList);
CharSequence[] favourites = new CharSequence[favouriteList.size()];
for(int i = 0; i < favouriteList.size(); i++) {
favourites[i] = favouriteList.get(i).name;
}
new AlertDialog.Builder(Magister.this)
.setItems(favourites, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
mPreferences.edit().putString(PREF_HOST, favouriteList.get(i).host).apply();
loadWebsite();
}
})
.show();
return true;
}
return false;
}
} | True | 2,044 | 21 | 2,434 | 26 | 2,539 | 19 | 2,434 | 26 | 2,893 | 24 | false | false | false | false | false | true |
2,385 | 140902_0 | /***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package de.cismet.cids.custom.utils;
import lombok.Getter;
import java.util.Properties;
import de.cismet.cids.utils.serverresources.ServerResourcesLoader;
/**
* DOCUMENT ME!
*
* @author sandra
* @version $Revision$, $Date$
*/
@Getter
public class BaumProperties {
//~ Static fields/initializers ---------------------------------------------
private static final transient org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(
BaumProperties.class);
protected static final WundaBlauServerResources SERVER_RESOURCE = WundaBlauServerResources.BAUM_CONF_PROPERTIES;
//~ Instance fields --------------------------------------------------------
private final Properties properties;
private final String urlFestsetzung;
private final String urlSchaden;
private final String urlDefault;
private final Integer gebietMapDpi;
private final Integer gebietMapWidth;
private final Integer gebietMapHeight;
private final Double gebietMapBuffer;
private final Integer schadenMapDpi;
private final Integer schadenMapWidth;
private final Integer schadenMapHeight;
private final Double schadenMapBuffer;
private final Integer ersatzMapDpi;
private final Integer ersatzMapWidth;
private final Integer ersatzMapHeight;
private final Double ersatzMapBuffer;
private final Integer festMapDpi;
private final Integer festMapWidth;
private final Integer festMapHeight;
private final Double festMapBuffer;
private final String mapSrs;
private final String gebietColor;
private final String ersatzColor;
private final String baumColor;
private final String festColor;
private final String schadenColor;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new BaumProperties object.
*
* @param properties DOCUMENT ME!
*/
protected BaumProperties(final Properties properties) {
this.properties = properties;
urlFestsetzung = String.valueOf(properties.getProperty("MAP_CALL_STRING_FESTSETZUNG"));
urlSchaden = String.valueOf(properties.getProperty("MAP_CALL_STRING_SCHADEN"));
urlDefault = String.valueOf(properties.getProperty("MAP_CALL_STRING_DEFAULT"));
gebietMapDpi = Integer.valueOf(properties.getProperty("GEBIET_MAP_DPI"));
gebietMapHeight = Integer.valueOf(properties.getProperty("GEBIET_MAP_HEIGHT"));
gebietMapWidth = Integer.valueOf(properties.getProperty("GEBIET_MAP_WIDTH"));
gebietMapBuffer = Double.valueOf(properties.getProperty("GEBIET_MAP_BUFFER"));
schadenMapDpi = Integer.valueOf(properties.getProperty("SCHADEN_MAP_DPI"));
schadenMapHeight = Integer.valueOf(properties.getProperty("SCHADEN_MAP_HEIGHT"));
schadenMapWidth = Integer.valueOf(properties.getProperty("SCHADEN_MAP_WIDTH"));
schadenMapBuffer = Double.valueOf(properties.getProperty("SCHADEN_MAP_BUFFER"));
ersatzMapDpi = Integer.valueOf(properties.getProperty("ERSATZ_MAP_DPI"));
ersatzMapHeight = Integer.valueOf(properties.getProperty("ERSATZ_MAP_HEIGHT"));
ersatzMapWidth = Integer.valueOf(properties.getProperty("ERSATZ_MAP_WIDTH"));
ersatzMapBuffer = Double.valueOf(properties.getProperty("ERSATZ_MAP_BUFFER"));
festMapDpi = Integer.valueOf(properties.getProperty("FEST_MAP_DPI"));
festMapHeight = Integer.valueOf(properties.getProperty("FEST_MAP_HEIGHT"));
festMapWidth = Integer.valueOf(properties.getProperty("FEST_MAP_WIDTH"));
festMapBuffer = Double.valueOf(properties.getProperty("FEST_MAP_BUFFER"));
mapSrs = String.valueOf(properties.getProperty("MAP_SRS"));
gebietColor = String.valueOf(properties.getProperty("GEBIET_COLOR"));
ersatzColor = String.valueOf(properties.getProperty("ERSATZ_COLOR"));
baumColor = String.valueOf(properties.getProperty("BAUM_COLOR"));
festColor = String.valueOf(properties.getProperty("FEST_COLOR"));
schadenColor = String.valueOf(properties.getProperty("SCHADEN_COLOR"));
}
//~ Methods ----------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public static BaumProperties getInstance() {
return LazyInitialiser.INSTANCE;
}
/**
* DOCUMENT ME!
*
* @param property DOCUMENT ME!
* @param defaultValue DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public final String valueOfString(final String property, final String defaultValue) {
String value = defaultValue;
if (properties.getProperty(property) != null) {
value = properties.getProperty(property);
}
return value;
}
/**
* DOCUMENT ME!
*
* @param property DOCUMENT ME!
* @param defaultValue DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public final Integer valueOfInteger(final String property, final Integer defaultValue) {
Integer value = defaultValue;
try {
value = Integer.valueOf(properties.getProperty(property));
} catch (final NumberFormatException ex) {
LOG.warn(String.format(
"value of %s is set to %s and can't be cast to Integer.",
property,
properties.getProperty(property)),
ex);
}
return value;
}
/**
* DOCUMENT ME!
*
* @param property DOCUMENT ME!
* @param defaultValue DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public final Boolean valueOfBoolean(final String property, final Boolean defaultValue) {
Boolean value = defaultValue;
try {
value = Boolean.valueOf(properties.getProperty(property));
} catch (final Exception ex) {
LOG.warn(String.format(
"value of %s is set to %s and can't be cast to Boolean.",
property,
properties.getProperty(property)),
ex);
}
return value;
}
//~ Inner Classes ----------------------------------------------------------
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
private static final class LazyInitialiser {
//~ Static fields/initializers -----------------------------------------
private static final BaumProperties INSTANCE;
static {
try {
INSTANCE = getNewInstance();
} catch (final Exception ex) {
throw new RuntimeException("Exception while initializing BaumProperties", ex);
}
}
//~ Constructors -------------------------------------------------------
/**
* Creates a new LazyInitialiser object.
*/
private LazyInitialiser() {
}
//~ Methods ------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws RuntimeException DOCUMENT ME!
*/
public static BaumProperties getNewInstance() {
try {
return new BaumProperties(ServerResourcesLoader.getInstance().loadProperties(
SERVER_RESOURCE.getValue()));
} catch (final Exception ex) {
throw new RuntimeException("Exception while initializing BaumProperties", ex);
}
}
}
}
| cismet/cids-custom-wuppertal-server | src/main/java/de/cismet/cids/custom/utils/BaumProperties.java | 2,111 | /***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/ | block_comment | nl | /***************************************************
*
* cismet GmbH, Saarbruecken,<SUF>*/
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package de.cismet.cids.custom.utils;
import lombok.Getter;
import java.util.Properties;
import de.cismet.cids.utils.serverresources.ServerResourcesLoader;
/**
* DOCUMENT ME!
*
* @author sandra
* @version $Revision$, $Date$
*/
@Getter
public class BaumProperties {
//~ Static fields/initializers ---------------------------------------------
private static final transient org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(
BaumProperties.class);
protected static final WundaBlauServerResources SERVER_RESOURCE = WundaBlauServerResources.BAUM_CONF_PROPERTIES;
//~ Instance fields --------------------------------------------------------
private final Properties properties;
private final String urlFestsetzung;
private final String urlSchaden;
private final String urlDefault;
private final Integer gebietMapDpi;
private final Integer gebietMapWidth;
private final Integer gebietMapHeight;
private final Double gebietMapBuffer;
private final Integer schadenMapDpi;
private final Integer schadenMapWidth;
private final Integer schadenMapHeight;
private final Double schadenMapBuffer;
private final Integer ersatzMapDpi;
private final Integer ersatzMapWidth;
private final Integer ersatzMapHeight;
private final Double ersatzMapBuffer;
private final Integer festMapDpi;
private final Integer festMapWidth;
private final Integer festMapHeight;
private final Double festMapBuffer;
private final String mapSrs;
private final String gebietColor;
private final String ersatzColor;
private final String baumColor;
private final String festColor;
private final String schadenColor;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new BaumProperties object.
*
* @param properties DOCUMENT ME!
*/
protected BaumProperties(final Properties properties) {
this.properties = properties;
urlFestsetzung = String.valueOf(properties.getProperty("MAP_CALL_STRING_FESTSETZUNG"));
urlSchaden = String.valueOf(properties.getProperty("MAP_CALL_STRING_SCHADEN"));
urlDefault = String.valueOf(properties.getProperty("MAP_CALL_STRING_DEFAULT"));
gebietMapDpi = Integer.valueOf(properties.getProperty("GEBIET_MAP_DPI"));
gebietMapHeight = Integer.valueOf(properties.getProperty("GEBIET_MAP_HEIGHT"));
gebietMapWidth = Integer.valueOf(properties.getProperty("GEBIET_MAP_WIDTH"));
gebietMapBuffer = Double.valueOf(properties.getProperty("GEBIET_MAP_BUFFER"));
schadenMapDpi = Integer.valueOf(properties.getProperty("SCHADEN_MAP_DPI"));
schadenMapHeight = Integer.valueOf(properties.getProperty("SCHADEN_MAP_HEIGHT"));
schadenMapWidth = Integer.valueOf(properties.getProperty("SCHADEN_MAP_WIDTH"));
schadenMapBuffer = Double.valueOf(properties.getProperty("SCHADEN_MAP_BUFFER"));
ersatzMapDpi = Integer.valueOf(properties.getProperty("ERSATZ_MAP_DPI"));
ersatzMapHeight = Integer.valueOf(properties.getProperty("ERSATZ_MAP_HEIGHT"));
ersatzMapWidth = Integer.valueOf(properties.getProperty("ERSATZ_MAP_WIDTH"));
ersatzMapBuffer = Double.valueOf(properties.getProperty("ERSATZ_MAP_BUFFER"));
festMapDpi = Integer.valueOf(properties.getProperty("FEST_MAP_DPI"));
festMapHeight = Integer.valueOf(properties.getProperty("FEST_MAP_HEIGHT"));
festMapWidth = Integer.valueOf(properties.getProperty("FEST_MAP_WIDTH"));
festMapBuffer = Double.valueOf(properties.getProperty("FEST_MAP_BUFFER"));
mapSrs = String.valueOf(properties.getProperty("MAP_SRS"));
gebietColor = String.valueOf(properties.getProperty("GEBIET_COLOR"));
ersatzColor = String.valueOf(properties.getProperty("ERSATZ_COLOR"));
baumColor = String.valueOf(properties.getProperty("BAUM_COLOR"));
festColor = String.valueOf(properties.getProperty("FEST_COLOR"));
schadenColor = String.valueOf(properties.getProperty("SCHADEN_COLOR"));
}
//~ Methods ----------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public static BaumProperties getInstance() {
return LazyInitialiser.INSTANCE;
}
/**
* DOCUMENT ME!
*
* @param property DOCUMENT ME!
* @param defaultValue DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public final String valueOfString(final String property, final String defaultValue) {
String value = defaultValue;
if (properties.getProperty(property) != null) {
value = properties.getProperty(property);
}
return value;
}
/**
* DOCUMENT ME!
*
* @param property DOCUMENT ME!
* @param defaultValue DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public final Integer valueOfInteger(final String property, final Integer defaultValue) {
Integer value = defaultValue;
try {
value = Integer.valueOf(properties.getProperty(property));
} catch (final NumberFormatException ex) {
LOG.warn(String.format(
"value of %s is set to %s and can't be cast to Integer.",
property,
properties.getProperty(property)),
ex);
}
return value;
}
/**
* DOCUMENT ME!
*
* @param property DOCUMENT ME!
* @param defaultValue DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public final Boolean valueOfBoolean(final String property, final Boolean defaultValue) {
Boolean value = defaultValue;
try {
value = Boolean.valueOf(properties.getProperty(property));
} catch (final Exception ex) {
LOG.warn(String.format(
"value of %s is set to %s and can't be cast to Boolean.",
property,
properties.getProperty(property)),
ex);
}
return value;
}
//~ Inner Classes ----------------------------------------------------------
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
private static final class LazyInitialiser {
//~ Static fields/initializers -----------------------------------------
private static final BaumProperties INSTANCE;
static {
try {
INSTANCE = getNewInstance();
} catch (final Exception ex) {
throw new RuntimeException("Exception while initializing BaumProperties", ex);
}
}
//~ Constructors -------------------------------------------------------
/**
* Creates a new LazyInitialiser object.
*/
private LazyInitialiser() {
}
//~ Methods ------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws RuntimeException DOCUMENT ME!
*/
public static BaumProperties getNewInstance() {
try {
return new BaumProperties(ServerResourcesLoader.getInstance().loadProperties(
SERVER_RESOURCE.getValue()));
} catch (final Exception ex) {
throw new RuntimeException("Exception while initializing BaumProperties", ex);
}
}
}
}
| False | 1,488 | 29 | 1,714 | 36 | 1,842 | 36 | 1,714 | 36 | 2,103 | 40 | false | false | false | false | false | true |
2,761 | 44375_5 | package source;_x000D_
_x000D_
import static org.junit.Assert.*;_x000D_
_x000D_
import org.junit.Before;_x000D_
import org.junit.Test;_x000D_
_x000D_
import source.Login;_x000D_
_x000D_
public class LoginTest {_x000D_
// login is totaal anders in klassendiagram_x000D_
// en deze testen zijn niet meer van toepasing_x000D_
// -Aime_x000D_
_x000D_
// private String usernameTest;_x000D_
// // opmerking! als deze var_x000D_
// // hetzelde naam heeft als die van Login(rollId)_x000D_
// // en je wijzigd zijn waarde dan wijzigd die van_x000D_
// // login ook om die static is_x000D_
// // nog een opmerking!_x000D_
// // als een primitieve int geen waarde kreeg bij_x000D_
// // dan kreeg die een automatisch 0_x000D_
// private int rollIdTest;_x000D_
//_x000D_
// @Before_x000D_
// public void initialize() {_x000D_
// usernameTest = "test";_x000D_
// rollIdTest = 2;_x000D_
// }_x000D_
//_x000D_
// @Test_x000D_
// public void setRollId_FailTest() {_x000D_
// // fail_x000D_
// // assertNotEquals(0, Login.getRollId());_x000D_
// // System.out.println(Login.getRollId());_x000D_
// // success_x000D_
// assertEquals(0, Login.getRollId());_x000D_
// }_x000D_
//_x000D_
// @Test_x000D_
// public void setUsername_FailTest() {_x000D_
// // fail_x000D_
// // assertNotEquals(null, Login.getUsername());_x000D_
// // success_x000D_
// assertEquals(null, Login.getUsername());_x000D_
// }_x000D_
//_x000D_
// @Test_x000D_
// public void setUsername_SuccessTest() {_x000D_
// // fail_x000D_
// // assertEquals(null, Login.getUsername());_x000D_
// // success_x000D_
// Login.setUsername(usernameTest);_x000D_
// assertEquals(usernameTest, Login.getUsername());_x000D_
// }_x000D_
//_x000D_
// @Test_x000D_
// public void setRollId_SuccessTest() {_x000D_
// // fail_x000D_
// // assertEquals(0, login.getRollId());_x000D_
// // success_x000D_
// Login.setRollId(rollIdTest);_x000D_
// assertEquals(rollIdTest, Login.getRollId());_x000D_
// }_x000D_
_x000D_
}_x000D_
| gauquier/NMBS-java | testing/source/LoginTest.java | 596 | // // en je wijzigd zijn waarde dan wijzigd die van_x000D_ | line_comment | nl | package source;_x000D_
_x000D_
import static org.junit.Assert.*;_x000D_
_x000D_
import org.junit.Before;_x000D_
import org.junit.Test;_x000D_
_x000D_
import source.Login;_x000D_
_x000D_
public class LoginTest {_x000D_
// login is totaal anders in klassendiagram_x000D_
// en deze testen zijn niet meer van toepasing_x000D_
// -Aime_x000D_
_x000D_
// private String usernameTest;_x000D_
// // opmerking! als deze var_x000D_
// // hetzelde naam heeft als die van Login(rollId)_x000D_
// // en je<SUF>
// // login ook om die static is_x000D_
// // nog een opmerking!_x000D_
// // als een primitieve int geen waarde kreeg bij_x000D_
// // dan kreeg die een automatisch 0_x000D_
// private int rollIdTest;_x000D_
//_x000D_
// @Before_x000D_
// public void initialize() {_x000D_
// usernameTest = "test";_x000D_
// rollIdTest = 2;_x000D_
// }_x000D_
//_x000D_
// @Test_x000D_
// public void setRollId_FailTest() {_x000D_
// // fail_x000D_
// // assertNotEquals(0, Login.getRollId());_x000D_
// // System.out.println(Login.getRollId());_x000D_
// // success_x000D_
// assertEquals(0, Login.getRollId());_x000D_
// }_x000D_
//_x000D_
// @Test_x000D_
// public void setUsername_FailTest() {_x000D_
// // fail_x000D_
// // assertNotEquals(null, Login.getUsername());_x000D_
// // success_x000D_
// assertEquals(null, Login.getUsername());_x000D_
// }_x000D_
//_x000D_
// @Test_x000D_
// public void setUsername_SuccessTest() {_x000D_
// // fail_x000D_
// // assertEquals(null, Login.getUsername());_x000D_
// // success_x000D_
// Login.setUsername(usernameTest);_x000D_
// assertEquals(usernameTest, Login.getUsername());_x000D_
// }_x000D_
//_x000D_
// @Test_x000D_
// public void setRollId_SuccessTest() {_x000D_
// // fail_x000D_
// // assertEquals(0, login.getRollId());_x000D_
// // success_x000D_
// Login.setRollId(rollIdTest);_x000D_
// assertEquals(rollIdTest, Login.getRollId());_x000D_
// }_x000D_
_x000D_
}_x000D_
| True | 850 | 22 | 976 | 25 | 958 | 22 | 976 | 25 | 995 | 23 | false | false | false | false | false | true |
1,854 | 1627_0 | package com.voipgrid.vialer.api.models;
import android.text.TextUtils;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class UserDestination {
@SerializedName("fixeddestinations")
private List<FixedDestination> fixedDestinations;
@SerializedName("phoneaccounts")
private List<PhoneAccount> phoneAccounts;
@SerializedName("selecteduserdestination")
private SelectedUserDestination selectedUserDestination;
@SerializedName("id")
private String id;
@SerializedName("internal_number")
private String internalNumber;
public List<FixedDestination> getFixedDestinations() {
return fixedDestinations;
}
public void setFixedDestinations(List<FixedDestination> fixedDestinations) {
this.fixedDestinations = fixedDestinations;
}
public List<PhoneAccount> getPhoneAccounts() {
return phoneAccounts;
}
public void setPhoneAccounts(List<PhoneAccount> phoneAccounts) {
this.phoneAccounts = phoneAccounts;
}
public SelectedUserDestination getSelectedUserDestination() {
return selectedUserDestination;
}
public void setSelectedUserDestination(SelectedUserDestination selectedUserDestination) {
this.selectedUserDestination = selectedUserDestination;
}
public Destination getActiveDestination() {
// Je moet door de phone accounts en fixed accounts heen loopen om de lijst van mogelijke
// nummers waar je bereikbaar op bent.
List<Destination> destinations = getDestinations();
// In de selecteduserdestination zitten twee keys welke het id hebben van of een phone
// account of een fixed destination en van die keys heeft er altijd eentje een waarde
if(selectedUserDestination != null) {
String selectedDestinationId = null;
if(!TextUtils.isEmpty(selectedUserDestination.getFixedDestinationId())) {
selectedDestinationId = selectedUserDestination.getFixedDestinationId();
} else if(!TextUtils.isEmpty(selectedUserDestination.getPhoneAccountId())) {
selectedDestinationId = selectedUserDestination.getPhoneAccountId();
}
if(!TextUtils.isEmpty(selectedDestinationId)) {
// tijdens de loop door de phone accounts en fixed destinations moet je dan een de
// check hebben of de waarde van de key in de selecteduserdestination gelijk zijn
for(int i=0, size=destinations.size(); i<size; i++) {
Destination destination = destinations.get(i);
if(selectedDestinationId.equals(destination.getId())) {
return destination;
}
}
}
}
return null;
}
public List<Destination> getDestinations() {
List<Destination> destinations = new ArrayList();
if(fixedDestinations != null) {
destinations.addAll(fixedDestinations);
}
if(phoneAccounts != null) {
destinations.addAll(phoneAccounts);
}
return destinations;
}
public SelectedUserDestination getSelectUserDestination() {
return selectedUserDestination;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getInternalNumber() {
return internalNumber;
}
}
| VoIPGRID/vialer-android | app/src/main/java/com/voipgrid/vialer/api/models/UserDestination.java | 872 | // Je moet door de phone accounts en fixed accounts heen loopen om de lijst van mogelijke | line_comment | nl | package com.voipgrid.vialer.api.models;
import android.text.TextUtils;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class UserDestination {
@SerializedName("fixeddestinations")
private List<FixedDestination> fixedDestinations;
@SerializedName("phoneaccounts")
private List<PhoneAccount> phoneAccounts;
@SerializedName("selecteduserdestination")
private SelectedUserDestination selectedUserDestination;
@SerializedName("id")
private String id;
@SerializedName("internal_number")
private String internalNumber;
public List<FixedDestination> getFixedDestinations() {
return fixedDestinations;
}
public void setFixedDestinations(List<FixedDestination> fixedDestinations) {
this.fixedDestinations = fixedDestinations;
}
public List<PhoneAccount> getPhoneAccounts() {
return phoneAccounts;
}
public void setPhoneAccounts(List<PhoneAccount> phoneAccounts) {
this.phoneAccounts = phoneAccounts;
}
public SelectedUserDestination getSelectedUserDestination() {
return selectedUserDestination;
}
public void setSelectedUserDestination(SelectedUserDestination selectedUserDestination) {
this.selectedUserDestination = selectedUserDestination;
}
public Destination getActiveDestination() {
// Je moet<SUF>
// nummers waar je bereikbaar op bent.
List<Destination> destinations = getDestinations();
// In de selecteduserdestination zitten twee keys welke het id hebben van of een phone
// account of een fixed destination en van die keys heeft er altijd eentje een waarde
if(selectedUserDestination != null) {
String selectedDestinationId = null;
if(!TextUtils.isEmpty(selectedUserDestination.getFixedDestinationId())) {
selectedDestinationId = selectedUserDestination.getFixedDestinationId();
} else if(!TextUtils.isEmpty(selectedUserDestination.getPhoneAccountId())) {
selectedDestinationId = selectedUserDestination.getPhoneAccountId();
}
if(!TextUtils.isEmpty(selectedDestinationId)) {
// tijdens de loop door de phone accounts en fixed destinations moet je dan een de
// check hebben of de waarde van de key in de selecteduserdestination gelijk zijn
for(int i=0, size=destinations.size(); i<size; i++) {
Destination destination = destinations.get(i);
if(selectedDestinationId.equals(destination.getId())) {
return destination;
}
}
}
}
return null;
}
public List<Destination> getDestinations() {
List<Destination> destinations = new ArrayList();
if(fixedDestinations != null) {
destinations.addAll(fixedDestinations);
}
if(phoneAccounts != null) {
destinations.addAll(phoneAccounts);
}
return destinations;
}
public SelectedUserDestination getSelectUserDestination() {
return selectedUserDestination;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getInternalNumber() {
return internalNumber;
}
}
| True | 654 | 21 | 727 | 23 | 754 | 19 | 727 | 23 | 898 | 22 | false | false | false | false | false | true |
2,401 | 200234_32 | /**
* Copyright (c) 2010-2015, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.novelanheatpump;
import org.openhab.core.items.Item;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.library.items.StringItem;
/**
* Represents all valid commands which could be processed by this binding
*
* @author Jan-Philipp Bolle
* @since 1.0.0
*/
public enum HeatpumpCommandType {
//in german Außentemperatur
TYPE_TEMPERATURE_OUTSIDE {
{
command = "temperature_outside";
itemClass = NumberItem.class;
}
},
//in german Außentemperatur
TYPE_TEMPERATURE_OUTSIDE_AVG {
{
command = "temperature_outside_avg";
itemClass = NumberItem.class;
}
},
//in german Rücklauf
TYPE_TEMPERATURE_RETURN {
{
command = "temperature_return";
itemClass = NumberItem.class;
}
},
//in german Rücklauf Soll
TYPE_TEMPERATURE_REFERENCE_RETURN {
{
command = "temperature_reference_return";
itemClass = NumberItem.class;
}
},
//in german Vorlauf
TYPE_TEMPERATURE_SUPPLAY {
{
command = "temperature_supplay";
itemClass = NumberItem.class;
}
},
// in german Brauchwasser Soll
TYPE_TEMPERATURE_SERVICEWATER_REFERENCE {
{
command = "temperature_servicewater_reference";
itemClass = NumberItem.class;
}
},
// in german Brauchwasser Ist
TYPE_TEMPERATURE_SERVICEWATER {
{
command = "temperature_servicewater";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_STATE {
{
command = "state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_EXTENDED_STATE {
{
command = "extended_state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_SOLAR_COLLECTOR {
{
command = "temperature_solar_collector";
itemClass = NumberItem.class;
}
},
// in german Temperatur Heissgas
TYPE_TEMPERATURE_HOT_GAS {
{
command = "temperature_hot_gas";
itemClass = NumberItem.class;
}
},
// in german Sondentemperatur WP Eingang
TYPE_TEMPERATURE_PROBE_IN {
{
command = "temperature_probe_in";
itemClass = NumberItem.class;
}
},
// in german Sondentemperatur WP Ausgang
TYPE_TEMPERATURE_PROBE_OUT {
{
command = "temperature_probe_out";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 IST
TYPE_TEMPERATURE_MK1 {
{
command = "temperature_mk1";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 SOLL
TYPE_TEMPERATURE_MK1_REFERENCE {
{
command = "temperature_mk1_reference";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 IST
TYPE_TEMPERATURE_MK2 {
{
command = "temperature_mk2";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 SOLL
TYPE_TEMPERATURE_MK2_REFERENCE {
{
command = "temperature_mk2_reference";
itemClass = NumberItem.class;
}
},
// in german Temperatur externe Energiequelle
TYPE_TEMPERATURE_EXTERNAL_SOURCE {
{
command = "temperature_external_source";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden Verdichter1
TYPE_HOURS_COMPRESSOR1 {
{
command = "hours_compressor1";
itemClass = StringItem.class;
}
},
// in german Impulse (Starts) Verdichter 1
TYPE_STARTS_COMPRESSOR1 {
{
command = "starts_compressor1";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden Verdichter2
TYPE_HOURS_COMPRESSOR2 {
{
command = "hours_compressor2";
itemClass = StringItem.class;
}
},
// in german Impulse (Starts) Verdichter 2
TYPE_STARTS_COMPRESSOR2 {
{
command = "starts_compressor2";
itemClass = NumberItem.class;
}
},
// Temperatur_TRL_ext
TYPE_TEMPERATURE_OUT_EXTERNAL {
{
command = "temperature_out_external";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE1 {
{
command = "hours_zwe1";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE2 {
{
command = "hours_zwe2";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE3 {
{
command = "hours_zwe3";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Wärmepumpe
TYPE_HOURS_HETPUMP {
{
command = "hours_heatpump";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Heizung
TYPE_HOURS_HEATING {
{
command = "hours_heating";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Brauchwasser
TYPE_HOURS_WARMWATER {
{
command = "hours_warmwater";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Brauchwasser
TYPE_HOURS_COOLING {
{
command = "hours_cooling";
itemClass = StringItem.class;
}
},
// in german Waermemenge Heizung
TYPE_THERMALENERGY_HEATING {
{
command = "thermalenergy_heating";
itemClass = NumberItem.class;
}
},
// in german Waermemenge Brauchwasser
TYPE_THERMALENERGY_WARMWATER {
{
command = "thermalenergy_warmwater";
itemClass = NumberItem.class;
}
},
// in german Waermemenge Schwimmbad
TYPE_THERMALENERGY_POOL {
{
command = "thermalenergy_pool";
itemClass = NumberItem.class;
}
},
// in german Waermemenge gesamt seit Reset
TYPE_THERMALENERGY_TOTAL {
{
command = "thermalenergy_total";
itemClass = NumberItem.class;
}
},
// in german Massentrom
TYPE_MASSFLOW {
{
command = "massflow";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_SOLAR_STORAGE {
{
command = "temperature_solar_storage";
itemClass = NumberItem.class;
}
},
//in german Heizung Betriebsart
TYPE_HEATING_OPERATION_MODE {
{
command = "heating_operation_mode";
itemClass = NumberItem.class;
}
},
//in german Heizung Temperatur (Parallelverschiebung)
TYPE_HEATING_TEMPERATURE {
{
command = "heating_temperatur";
itemClass = NumberItem.class;
}
},
//in german Warmwasser Betriebsart
TYPE_WARMWATER_OPERATION_MODE {
{
command = "warmwater_operation_mode";
itemClass = NumberItem.class;
}
},
//in german Warmwasser Temperatur
TYPE_WARMWATER_TEMPERATURE {
{
command = "warmwater_temperatur";
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 + "'");
}
} | clinique/openhab | bundles/binding/org.openhab.binding.novelanheatpump/src/main/java/org/openhab/binding/novelanheatpump/HeatpumpCommandType.java | 2,895 | // in german Massentrom | line_comment | nl | /**
* Copyright (c) 2010-2015, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.novelanheatpump;
import org.openhab.core.items.Item;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.library.items.StringItem;
/**
* Represents all valid commands which could be processed by this binding
*
* @author Jan-Philipp Bolle
* @since 1.0.0
*/
public enum HeatpumpCommandType {
//in german Außentemperatur
TYPE_TEMPERATURE_OUTSIDE {
{
command = "temperature_outside";
itemClass = NumberItem.class;
}
},
//in german Außentemperatur
TYPE_TEMPERATURE_OUTSIDE_AVG {
{
command = "temperature_outside_avg";
itemClass = NumberItem.class;
}
},
//in german Rücklauf
TYPE_TEMPERATURE_RETURN {
{
command = "temperature_return";
itemClass = NumberItem.class;
}
},
//in german Rücklauf Soll
TYPE_TEMPERATURE_REFERENCE_RETURN {
{
command = "temperature_reference_return";
itemClass = NumberItem.class;
}
},
//in german Vorlauf
TYPE_TEMPERATURE_SUPPLAY {
{
command = "temperature_supplay";
itemClass = NumberItem.class;
}
},
// in german Brauchwasser Soll
TYPE_TEMPERATURE_SERVICEWATER_REFERENCE {
{
command = "temperature_servicewater_reference";
itemClass = NumberItem.class;
}
},
// in german Brauchwasser Ist
TYPE_TEMPERATURE_SERVICEWATER {
{
command = "temperature_servicewater";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_STATE {
{
command = "state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_EXTENDED_STATE {
{
command = "extended_state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_SOLAR_COLLECTOR {
{
command = "temperature_solar_collector";
itemClass = NumberItem.class;
}
},
// in german Temperatur Heissgas
TYPE_TEMPERATURE_HOT_GAS {
{
command = "temperature_hot_gas";
itemClass = NumberItem.class;
}
},
// in german Sondentemperatur WP Eingang
TYPE_TEMPERATURE_PROBE_IN {
{
command = "temperature_probe_in";
itemClass = NumberItem.class;
}
},
// in german Sondentemperatur WP Ausgang
TYPE_TEMPERATURE_PROBE_OUT {
{
command = "temperature_probe_out";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 IST
TYPE_TEMPERATURE_MK1 {
{
command = "temperature_mk1";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 SOLL
TYPE_TEMPERATURE_MK1_REFERENCE {
{
command = "temperature_mk1_reference";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 IST
TYPE_TEMPERATURE_MK2 {
{
command = "temperature_mk2";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 SOLL
TYPE_TEMPERATURE_MK2_REFERENCE {
{
command = "temperature_mk2_reference";
itemClass = NumberItem.class;
}
},
// in german Temperatur externe Energiequelle
TYPE_TEMPERATURE_EXTERNAL_SOURCE {
{
command = "temperature_external_source";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden Verdichter1
TYPE_HOURS_COMPRESSOR1 {
{
command = "hours_compressor1";
itemClass = StringItem.class;
}
},
// in german Impulse (Starts) Verdichter 1
TYPE_STARTS_COMPRESSOR1 {
{
command = "starts_compressor1";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden Verdichter2
TYPE_HOURS_COMPRESSOR2 {
{
command = "hours_compressor2";
itemClass = StringItem.class;
}
},
// in german Impulse (Starts) Verdichter 2
TYPE_STARTS_COMPRESSOR2 {
{
command = "starts_compressor2";
itemClass = NumberItem.class;
}
},
// Temperatur_TRL_ext
TYPE_TEMPERATURE_OUT_EXTERNAL {
{
command = "temperature_out_external";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE1 {
{
command = "hours_zwe1";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE2 {
{
command = "hours_zwe2";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE3 {
{
command = "hours_zwe3";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Wärmepumpe
TYPE_HOURS_HETPUMP {
{
command = "hours_heatpump";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Heizung
TYPE_HOURS_HEATING {
{
command = "hours_heating";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Brauchwasser
TYPE_HOURS_WARMWATER {
{
command = "hours_warmwater";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Brauchwasser
TYPE_HOURS_COOLING {
{
command = "hours_cooling";
itemClass = StringItem.class;
}
},
// in german Waermemenge Heizung
TYPE_THERMALENERGY_HEATING {
{
command = "thermalenergy_heating";
itemClass = NumberItem.class;
}
},
// in german Waermemenge Brauchwasser
TYPE_THERMALENERGY_WARMWATER {
{
command = "thermalenergy_warmwater";
itemClass = NumberItem.class;
}
},
// in german Waermemenge Schwimmbad
TYPE_THERMALENERGY_POOL {
{
command = "thermalenergy_pool";
itemClass = NumberItem.class;
}
},
// in german Waermemenge gesamt seit Reset
TYPE_THERMALENERGY_TOTAL {
{
command = "thermalenergy_total";
itemClass = NumberItem.class;
}
},
// in german<SUF>
TYPE_MASSFLOW {
{
command = "massflow";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_SOLAR_STORAGE {
{
command = "temperature_solar_storage";
itemClass = NumberItem.class;
}
},
//in german Heizung Betriebsart
TYPE_HEATING_OPERATION_MODE {
{
command = "heating_operation_mode";
itemClass = NumberItem.class;
}
},
//in german Heizung Temperatur (Parallelverschiebung)
TYPE_HEATING_TEMPERATURE {
{
command = "heating_temperatur";
itemClass = NumberItem.class;
}
},
//in german Warmwasser Betriebsart
TYPE_WARMWATER_OPERATION_MODE {
{
command = "warmwater_operation_mode";
itemClass = NumberItem.class;
}
},
//in german Warmwasser Temperatur
TYPE_WARMWATER_TEMPERATURE {
{
command = "warmwater_temperatur";
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,257 | 6 | 2,707 | 7 | 2,485 | 6 | 2,707 | 7 | 3,245 | 7 | false | false | false | false | false | true |
3,753 | 31792_4 | public class DavidImmutableTree extends ImmutableTree {
private final int value;
private final ImmutableTree left;
private final ImmutableTree right;
public DavidImmutableTree(Integer value, ImmutableTree left, ImmutableTree right) {
this.value = value;
this.left = left;
this.right = right;
}
public ImmutableTree newInstance(int value) {
return new DavidImmutableTree(value, null, null);
}
public int getValue() {
return this.value;
}
public ImmutableTree getLeft() {
return this.left;
}
public ImmutableTree getRight() {
return this.right;
}
public String toString() {
String retStr = "";
if (this.left != null) {
retStr += this.left.toString() + ", ";
}
retStr += this.value;
if (this.right != null) {
retStr += ", " + this.right.toString();
}
return retStr;
}
public ImmutableTree getMin() {
return (ImmutableTree) (this.left != null ? this.left.getMin() : this);
}
public ImmutableTree sortedInsert(int insertVal) {
if (insertVal < this.value) { // wenn kleiner links
if (this.left == null) { // kein kind links
return new DavidImmutableTree(this.value, new DavidImmutableTree(insertVal, null, null), this.right); // neuen
// knoten
// als
// blatt
// direkt
// anfuegen
} else { // sonst rekursiv im linken teilbaum
return new DavidImmutableTree(this.value, this.left.sortedInsert(insertVal), this.right);
}
} else { // nicht kleiner rechts analog zu links
if (this.right == null) {
return new DavidImmutableTree(this.value, this.left, new DavidImmutableTree(insertVal, null, null));
} else {
return new DavidImmutableTree(this.value, this.left, this.right.sortedInsert(insertVal));
}
}
}
public ImmutableTree sortedDelete(int deleteVal) {
if (this.value == deleteVal) { // this soll geloescht werden
if (this.left == null && this.right == null) { // nur this
// leeren baum zurueckgeben
return null;
} else { // this hat kinder
if (this.right != null) { // rechter teilbaum vorhanden.
// kleinstes element von rechts in die wurzel kopieren und
// aus rechtem teilbaum loeschen
return new DavidImmutableTree(this.right.getMin().getValue(), this.left,
this.right.sortedDelete(this.right.getMin().getValue()));
} else { // kein rechter teilbaum
return this.left; // linkes kind ist neue wurzel des
// teilbaumes mit this als wurzel
}
// der sonderfall (right != null && left==null) wird nicht
// betrachtet
// so spaart man sich ein paar vergleiche, einigen dublicate
// code
// mit einem kleinen risiko etwas mehraufwand zu betreiben
}
} else { // wurzel wird nicht geloescht
if (deleteVal < this.value) { // element zum loeschen ist links
return new DavidImmutableTree(this.value, this.left != null ? this.left.sortedDelete(deleteVal) : null,
this.right); // element links loeschen
} else { // analog mit rechts
return new DavidImmutableTree(this.value, this.left,
this.right != null ? this.right.sortedDelete(deleteVal) : null);
}
}
// hier kein return noetig, weil jedes if ein else hat und in jedem if
// und else block returned wird.
}
// feststellung: Mit immutables ist das alles so schoen endrekursiv :)
}
| mumogu/TreeTester | DavidImmutableTree.java | 1,067 | // this soll geloescht werden | line_comment | nl | public class DavidImmutableTree extends ImmutableTree {
private final int value;
private final ImmutableTree left;
private final ImmutableTree right;
public DavidImmutableTree(Integer value, ImmutableTree left, ImmutableTree right) {
this.value = value;
this.left = left;
this.right = right;
}
public ImmutableTree newInstance(int value) {
return new DavidImmutableTree(value, null, null);
}
public int getValue() {
return this.value;
}
public ImmutableTree getLeft() {
return this.left;
}
public ImmutableTree getRight() {
return this.right;
}
public String toString() {
String retStr = "";
if (this.left != null) {
retStr += this.left.toString() + ", ";
}
retStr += this.value;
if (this.right != null) {
retStr += ", " + this.right.toString();
}
return retStr;
}
public ImmutableTree getMin() {
return (ImmutableTree) (this.left != null ? this.left.getMin() : this);
}
public ImmutableTree sortedInsert(int insertVal) {
if (insertVal < this.value) { // wenn kleiner links
if (this.left == null) { // kein kind links
return new DavidImmutableTree(this.value, new DavidImmutableTree(insertVal, null, null), this.right); // neuen
// knoten
// als
// blatt
// direkt
// anfuegen
} else { // sonst rekursiv im linken teilbaum
return new DavidImmutableTree(this.value, this.left.sortedInsert(insertVal), this.right);
}
} else { // nicht kleiner rechts analog zu links
if (this.right == null) {
return new DavidImmutableTree(this.value, this.left, new DavidImmutableTree(insertVal, null, null));
} else {
return new DavidImmutableTree(this.value, this.left, this.right.sortedInsert(insertVal));
}
}
}
public ImmutableTree sortedDelete(int deleteVal) {
if (this.value == deleteVal) { // this soll<SUF>
if (this.left == null && this.right == null) { // nur this
// leeren baum zurueckgeben
return null;
} else { // this hat kinder
if (this.right != null) { // rechter teilbaum vorhanden.
// kleinstes element von rechts in die wurzel kopieren und
// aus rechtem teilbaum loeschen
return new DavidImmutableTree(this.right.getMin().getValue(), this.left,
this.right.sortedDelete(this.right.getMin().getValue()));
} else { // kein rechter teilbaum
return this.left; // linkes kind ist neue wurzel des
// teilbaumes mit this als wurzel
}
// der sonderfall (right != null && left==null) wird nicht
// betrachtet
// so spaart man sich ein paar vergleiche, einigen dublicate
// code
// mit einem kleinen risiko etwas mehraufwand zu betreiben
}
} else { // wurzel wird nicht geloescht
if (deleteVal < this.value) { // element zum loeschen ist links
return new DavidImmutableTree(this.value, this.left != null ? this.left.sortedDelete(deleteVal) : null,
this.right); // element links loeschen
} else { // analog mit rechts
return new DavidImmutableTree(this.value, this.left,
this.right != null ? this.right.sortedDelete(deleteVal) : null);
}
}
// hier kein return noetig, weil jedes if ein else hat und in jedem if
// und else block returned wird.
}
// feststellung: Mit immutables ist das alles so schoen endrekursiv :)
}
| False | 864 | 7 | 1,019 | 9 | 955 | 7 | 1,019 | 9 | 1,186 | 8 | false | false | false | false | false | true |
1,930 | 26181_0 | package com.example.eindopdrachtandroid;
import static android.app.PendingIntent.getActivity;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.example.eindopdrachtandroid.model.Post;
import com.example.eindopdrachtandroid.viewmodel.PostViewModel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar mToolbar = findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragmentContainerView);
NavController mNavController = navHostFragment.getNavController();
AppBarConfiguration mAppBarConfig = new AppBarConfiguration.Builder(mNavController.getGraph()).build();
NavigationUI.setupActionBarWithNavController(this, mNavController, mAppBarConfig);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
PostViewModel mViewmodel = new ViewModelProvider(this).get(PostViewModel.class);
Thread backgroundThread = new Thread(new Runnable() {
@Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();
Request myRequest = new Request.Builder()
.url("https://opendata.bruxelles.be/api/explore/v2.1/catalog/datasets/bruxelles_urinoirs_publics/records")
.get()
.build();
Response myResponse = client.newCall(myRequest).execute();
//raw payload
String responseText = myResponse.body().string();
//JSON convert
JSONObject myJSONObject = new JSONObject(responseText);
JSONArray myJSONArray = myJSONObject.getJSONArray("results");
int postsJSONlength = myJSONArray.length();
ArrayList<Post> parsedObjects = new ArrayList<>(postsJSONlength);
for (int i = 0; i < postsJSONlength; i++) {
JSONObject temp = myJSONArray.getJSONObject(i);
Post currentPost = new Post(
temp.getString("typeeng"),
temp.getString("adrvoisnl"),
temp.getString("z_pcdd_nl"),
Double.parseDouble(temp.getString("wgs84_long")),
Double.parseDouble(temp.getString("wgs84_lat"))
);
parsedObjects.add(currentPost);
}
mViewmodel.InitialPosts(parsedObjects);
}catch (IOException e){
Log.e("fout", e.getMessage());
} catch (JSONException e){
Log.e("fout", e.getMessage());
}
}
});
// Als alles ingeladen is, edit de prefs om ervoor te zorgen dat men alles niet twee keer afprint
if(!prefs.contains("loaded")){
backgroundThread.start();
prefs.edit().putBoolean("loaded", true);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
} | Zenodesp/EindopdrachtAndroid_zd | app/src/main/java/com/example/eindopdrachtandroid/MainActivity.java | 1,110 | // Als alles ingeladen is, edit de prefs om ervoor te zorgen dat men alles niet twee keer afprint | line_comment | nl | package com.example.eindopdrachtandroid;
import static android.app.PendingIntent.getActivity;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.example.eindopdrachtandroid.model.Post;
import com.example.eindopdrachtandroid.viewmodel.PostViewModel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar mToolbar = findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragmentContainerView);
NavController mNavController = navHostFragment.getNavController();
AppBarConfiguration mAppBarConfig = new AppBarConfiguration.Builder(mNavController.getGraph()).build();
NavigationUI.setupActionBarWithNavController(this, mNavController, mAppBarConfig);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
PostViewModel mViewmodel = new ViewModelProvider(this).get(PostViewModel.class);
Thread backgroundThread = new Thread(new Runnable() {
@Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();
Request myRequest = new Request.Builder()
.url("https://opendata.bruxelles.be/api/explore/v2.1/catalog/datasets/bruxelles_urinoirs_publics/records")
.get()
.build();
Response myResponse = client.newCall(myRequest).execute();
//raw payload
String responseText = myResponse.body().string();
//JSON convert
JSONObject myJSONObject = new JSONObject(responseText);
JSONArray myJSONArray = myJSONObject.getJSONArray("results");
int postsJSONlength = myJSONArray.length();
ArrayList<Post> parsedObjects = new ArrayList<>(postsJSONlength);
for (int i = 0; i < postsJSONlength; i++) {
JSONObject temp = myJSONArray.getJSONObject(i);
Post currentPost = new Post(
temp.getString("typeeng"),
temp.getString("adrvoisnl"),
temp.getString("z_pcdd_nl"),
Double.parseDouble(temp.getString("wgs84_long")),
Double.parseDouble(temp.getString("wgs84_lat"))
);
parsedObjects.add(currentPost);
}
mViewmodel.InitialPosts(parsedObjects);
}catch (IOException e){
Log.e("fout", e.getMessage());
} catch (JSONException e){
Log.e("fout", e.getMessage());
}
}
});
// Als alles<SUF>
if(!prefs.contains("loaded")){
backgroundThread.start();
prefs.edit().putBoolean("loaded", true);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
} | True | 703 | 25 | 896 | 30 | 917 | 23 | 896 | 30 | 1,079 | 27 | false | false | false | false | false | true |
4,568 | 200948_9 | /*
* c't-Sim - Robotersimulator für den c't-Bot
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307, USA.
*
*/
package ctSim;
import java.io.IOException;
import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import ctSim.controller.BotReceiver;
import ctSim.controller.Config;
import ctSim.util.SaferThread;
/**
* Repräsentiert eine TCP-Verbindung
*
* @author Benjamin Benz
* @author Christoph Grimmer ([email protected])
*/
public class TcpConnection extends Connection {
/** Socket der Connection */
private Socket socket = null;
/**
* TCP-Verbindung
*
* @param sock Socket
* @throws IOException
*/
public TcpConnection(Socket sock) throws IOException {
this.socket = sock;
setInputStream(socket.getInputStream());
setOutputStream(socket.getOutputStream());
}
/**
* Wandelt den übergebenen String und die Portnummer in eine TCP/IP-Adresse und stellt dann die
* Verbindung her
*
* @param hostname Adresse als String
* @param port Portnummer
* @throws IOException
*/
public TcpConnection(String hostname, int port) throws IOException {
this(new Socket(hostname, port));
}
/**
* Beendet die laufende Verbindung
*
* @throws IOException
*/
@Override
public synchronized void close() throws IOException {
socket.close();
super.close();
}
/**
* @see ctSim.Connection#getName()
*/
@Override
public String getName() {
return
"TCP " + socket.getLocalAddress() + ":" + socket.getLocalPort() +
"->" + socket.getInetAddress() + ":" + socket.getPort();
}
/**
* @see ctSim.Connection#getShortName()
*/
@Override
public String getShortName() { return "TCP"; }
/**
* Beginnt zu lauschen
*
* @param receiver Bot-Receiver
*/
public static void startListening(final BotReceiver receiver) {
int p = 10001;
try {
p = Integer.parseInt(Config.getValue("botport"));
} catch(NumberFormatException nfe) {
lg.warning(nfe, "Problem beim Parsen der Konfiguration: Parameter 'botport' ist keine Ganzzahl");
}
lg.info("Warte auf Verbindung vom c't-Bot auf TCP-Port " + p);
try {
@SuppressWarnings("resource")
final ServerSocket srvSocket = new ServerSocket(p);
new SaferThread("ctSim-Listener-" + p + "/tcp") {
@Override
public void work() {
try {
Socket s = srvSocket.accept(); // blockiert
lg.fine("Verbindung auf Port " + srvSocket.getLocalPort() + "/tcp eingegangen");
new TcpConnection(s).doHandshake(receiver);
} catch (IOException e) {
lg.warn(e, "Thread " + getName() + " hat ein E/A-Problem beim Lauschen");
}
}
}.start();
} catch (IOException e) {
lg.warning(e, "E/A-Problem beim Binden an TCP-Port " + p + "; läuft der c't-Sim schon?");
System.exit(1);
}
}
/**
* Verbindet zu Host:Port
*
* @param hostname Host-Name des Bots
* @param port Port
* @param receiver Bot-Receiver
*/
public static void connectTo(final String hostname, final int port,
final BotReceiver receiver) {
final String address = hostname + ":" + port; // nur für Meldungen
lg.info("Verbinde mit " + address + " ...");
new SaferThread("ctSim-Connect-" + address) {
@Override
public void work() {
try {
new TcpConnection(hostname, port).doHandshake(receiver);
} catch (UnknownHostException e) {
lg.warn("Host '" + e.getMessage() + "' nicht gefunden");
} catch (ConnectException e) {
// ConnectExcp deckt so Sachen ab wie "connection refused" und "connection timed out"
lg.warn("Konnte Verbindung mit " + address + " nicht herstellen (" + e.getLocalizedMessage() + ")");
} catch (IOException e) {
lg.severe(e, "E/A-Problem beim Verbinden mit " + address);
}
// Arbeit ist getan, ob es funktioniert hat oder nicht...
die();
}
}.start();
}
}
| tsandmann/ct-sim | ctSim/TcpConnection.java | 1,502 | /**
* Verbindet zu Host:Port
*
* @param hostname Host-Name des Bots
* @param port Port
* @param receiver Bot-Receiver
*/ | block_comment | nl | /*
* c't-Sim - Robotersimulator für den c't-Bot
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307, USA.
*
*/
package ctSim;
import java.io.IOException;
import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import ctSim.controller.BotReceiver;
import ctSim.controller.Config;
import ctSim.util.SaferThread;
/**
* Repräsentiert eine TCP-Verbindung
*
* @author Benjamin Benz
* @author Christoph Grimmer ([email protected])
*/
public class TcpConnection extends Connection {
/** Socket der Connection */
private Socket socket = null;
/**
* TCP-Verbindung
*
* @param sock Socket
* @throws IOException
*/
public TcpConnection(Socket sock) throws IOException {
this.socket = sock;
setInputStream(socket.getInputStream());
setOutputStream(socket.getOutputStream());
}
/**
* Wandelt den übergebenen String und die Portnummer in eine TCP/IP-Adresse und stellt dann die
* Verbindung her
*
* @param hostname Adresse als String
* @param port Portnummer
* @throws IOException
*/
public TcpConnection(String hostname, int port) throws IOException {
this(new Socket(hostname, port));
}
/**
* Beendet die laufende Verbindung
*
* @throws IOException
*/
@Override
public synchronized void close() throws IOException {
socket.close();
super.close();
}
/**
* @see ctSim.Connection#getName()
*/
@Override
public String getName() {
return
"TCP " + socket.getLocalAddress() + ":" + socket.getLocalPort() +
"->" + socket.getInetAddress() + ":" + socket.getPort();
}
/**
* @see ctSim.Connection#getShortName()
*/
@Override
public String getShortName() { return "TCP"; }
/**
* Beginnt zu lauschen
*
* @param receiver Bot-Receiver
*/
public static void startListening(final BotReceiver receiver) {
int p = 10001;
try {
p = Integer.parseInt(Config.getValue("botport"));
} catch(NumberFormatException nfe) {
lg.warning(nfe, "Problem beim Parsen der Konfiguration: Parameter 'botport' ist keine Ganzzahl");
}
lg.info("Warte auf Verbindung vom c't-Bot auf TCP-Port " + p);
try {
@SuppressWarnings("resource")
final ServerSocket srvSocket = new ServerSocket(p);
new SaferThread("ctSim-Listener-" + p + "/tcp") {
@Override
public void work() {
try {
Socket s = srvSocket.accept(); // blockiert
lg.fine("Verbindung auf Port " + srvSocket.getLocalPort() + "/tcp eingegangen");
new TcpConnection(s).doHandshake(receiver);
} catch (IOException e) {
lg.warn(e, "Thread " + getName() + " hat ein E/A-Problem beim Lauschen");
}
}
}.start();
} catch (IOException e) {
lg.warning(e, "E/A-Problem beim Binden an TCP-Port " + p + "; läuft der c't-Sim schon?");
System.exit(1);
}
}
/**
* Verbindet zu Host:Port<SUF>*/
public static void connectTo(final String hostname, final int port,
final BotReceiver receiver) {
final String address = hostname + ":" + port; // nur für Meldungen
lg.info("Verbinde mit " + address + " ...");
new SaferThread("ctSim-Connect-" + address) {
@Override
public void work() {
try {
new TcpConnection(hostname, port).doHandshake(receiver);
} catch (UnknownHostException e) {
lg.warn("Host '" + e.getMessage() + "' nicht gefunden");
} catch (ConnectException e) {
// ConnectExcp deckt so Sachen ab wie "connection refused" und "connection timed out"
lg.warn("Konnte Verbindung mit " + address + " nicht herstellen (" + e.getLocalizedMessage() + ")");
} catch (IOException e) {
lg.severe(e, "E/A-Problem beim Verbinden mit " + address);
}
// Arbeit ist getan, ob es funktioniert hat oder nicht...
die();
}
}.start();
}
}
| False | 1,182 | 46 | 1,344 | 43 | 1,332 | 46 | 1,344 | 43 | 1,599 | 51 | false | false | false | false | false | true |
1,051 | 206445_1 | //Je project bevat 1 Translator class met daarin een HashMap variabele, een constructor met 2
// arrays als parameter en een translate functie;
import java.util.HashMap;
import java.util.Map;
public class Translator {
private Map<Integer, String> numericAlpha = new HashMap<>();
public Translator(int[] numeric, String[] alphabetic) {
for (int i = 0; i < numeric.length; i++) {
numericAlpha.put(numeric[i], alphabetic[i]);
}
}
// geen getter nodig, want we gaan die via constructor opvragen
// geen setter nodig want we gaan de hashmap niet aanpassen, alleen er iets uit op halen
// methods
public String translate(Integer number) {
return "The translation of your number " + number + " in text is: " + numericAlpha.get(number);
}
}
| Majda-Mech/Java-Collecties-Lussen | src/Translator.java | 237 | // arrays als parameter en een translate functie; | line_comment | nl | //Je project bevat 1 Translator class met daarin een HashMap variabele, een constructor met 2
// arrays als<SUF>
import java.util.HashMap;
import java.util.Map;
public class Translator {
private Map<Integer, String> numericAlpha = new HashMap<>();
public Translator(int[] numeric, String[] alphabetic) {
for (int i = 0; i < numeric.length; i++) {
numericAlpha.put(numeric[i], alphabetic[i]);
}
}
// geen getter nodig, want we gaan die via constructor opvragen
// geen setter nodig want we gaan de hashmap niet aanpassen, alleen er iets uit op halen
// methods
public String translate(Integer number) {
return "The translation of your number " + number + " in text is: " + numericAlpha.get(number);
}
}
| True | 187 | 10 | 216 | 10 | 208 | 9 | 216 | 10 | 241 | 11 | false | false | false | false | false | true |
1,938 | 37220_0 | import java.util.ArrayList;
/**
* Sommige positieve getallen n hebben de eigenschap dat de som [ n + reverse(n) ]
* volledig bestaat uit oneven nummers. Bijvoorbeeld, 36 + 63 = 99 en 409 + 904 = 1313. Deze getallen noemen we omkeerbaar;
* dus 36, 63, 409, en 904 zijn omkeerbaar. Voorlopende nullen in n or reverse(n) zijn niet toegestaan.
*
* Er zijn 120 omkeerbare getallen onder 1000.
*
* Hoeveel omkeerbare getallen zijn er onder 100 miljoen (10^8)?
*
*
* @author ZL
*
*/
public class OmkeerbareGetallen {
/**
* Main method
*/
public void start(){
int begin = 0;
int end = 100000000;
ArrayList<Integer> lijst = new ArrayList<>();
for (int i = begin; i <= end; ++i){
if(i%10!=0 && isAllOdd(i+reverseInt(i))){
lijst.add(i);
}
}
System.out.println(lijst.size());
}
/**
* Checks if all individual numbers are odd numbers
* @param number Number to check for
* @return
*/
public boolean isAllOdd(int number){
String[] stringNum = Integer.toString(number).split("");
for(String str:stringNum){
if(Integer.parseInt(str)%2==0){
return false;
}
}
return true;
}
/**
* Reverse an integer number. 1234 becomes 4321
* @param number The number to be reversed
* @return
*/
public int reverseInt(int number){
return (int) Integer.parseInt(new StringBuilder(Integer.toString(number)).reverse().toString());
}
/**
* Static Main method
* @param args
*/
public static void main(String[] args){
new OmkeerbareGetallen().start();
}
}
| aapman55/Tweakers-contest | src/OmkeerbareGetallen.java | 579 | /**
* Sommige positieve getallen n hebben de eigenschap dat de som [ n + reverse(n) ]
* volledig bestaat uit oneven nummers. Bijvoorbeeld, 36 + 63 = 99 en 409 + 904 = 1313. Deze getallen noemen we omkeerbaar;
* dus 36, 63, 409, en 904 zijn omkeerbaar. Voorlopende nullen in n or reverse(n) zijn niet toegestaan.
*
* Er zijn 120 omkeerbare getallen onder 1000.
*
* Hoeveel omkeerbare getallen zijn er onder 100 miljoen (10^8)?
*
*
* @author ZL
*
*/ | block_comment | nl | import java.util.ArrayList;
/**
* Sommige positieve getallen<SUF>*/
public class OmkeerbareGetallen {
/**
* Main method
*/
public void start(){
int begin = 0;
int end = 100000000;
ArrayList<Integer> lijst = new ArrayList<>();
for (int i = begin; i <= end; ++i){
if(i%10!=0 && isAllOdd(i+reverseInt(i))){
lijst.add(i);
}
}
System.out.println(lijst.size());
}
/**
* Checks if all individual numbers are odd numbers
* @param number Number to check for
* @return
*/
public boolean isAllOdd(int number){
String[] stringNum = Integer.toString(number).split("");
for(String str:stringNum){
if(Integer.parseInt(str)%2==0){
return false;
}
}
return true;
}
/**
* Reverse an integer number. 1234 becomes 4321
* @param number The number to be reversed
* @return
*/
public int reverseInt(int number){
return (int) Integer.parseInt(new StringBuilder(Integer.toString(number)).reverse().toString());
}
/**
* Static Main method
* @param args
*/
public static void main(String[] args){
new OmkeerbareGetallen().start();
}
}
| True | 503 | 189 | 562 | 206 | 570 | 187 | 562 | 206 | 641 | 203 | false | false | false | false | false | true |
28 | 1633_1 | import java.text.SimpleDateFormat;_x000D_
import java.util.Date;_x000D_
import java.text.DateFormat;_x000D_
import java.text.ParseException;_x000D_
_x000D_
public class Medicijn {_x000D_
_x000D_
String merknaam;_x000D_
String stofnaam;_x000D_
int aantal;_x000D_
int gewensteAantal;_x000D_
int minimumAantal;_x000D_
String fabrikant;_x000D_
int prijs;_x000D_
int kastID; _x000D_
String houdbaarheid;//String die de datum voorstelt in het formaat "dd-MM-yyyy' zoals sdf._x000D_
boolean alGewaarschuwd;_x000D_
boolean besteld;_x000D_
_x000D_
_x000D_
public Medicijn(String merknaam, String stofnaam, int aantal, int gewensteAantal, int minimumAantal, String fabrikant, int prijs, int kastID, String houdbaarheid)_x000D_
{_x000D_
this.merknaam = merknaam;_x000D_
this.stofnaam = stofnaam;_x000D_
this.aantal = aantal;_x000D_
this.gewensteAantal = gewensteAantal;_x000D_
this.minimumAantal = minimumAantal;_x000D_
this.fabrikant = fabrikant;_x000D_
this.prijs = prijs;_x000D_
this.kastID = kastID;_x000D_
this.houdbaarheid = houdbaarheid;_x000D_
alGewaarschuwd=false;_x000D_
}_x000D_
_x000D_
public int controleerOpAantal()_x000D_
{_x000D_
//return 0 als er genoeg zijn, en anders hoeveel er te weinig zijn._x000D_
if (aantal <= minimumAantal)_x000D_
{_x000D_
return gewensteAantal-aantal;_x000D_
}_x000D_
_x000D_
else_x000D_
{_x000D_
return 0;_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
public int controleerOpBeide() throws ParseException{_x000D_
int hoogste = 0;_x000D_
if(controleerOpHoudbaarheid()>controleerOpAantal()) _x000D_
hoogste = controleerOpHoudbaarheid();_x000D_
else_x000D_
hoogste=controleerOpAantal();_x000D_
return hoogste;_x000D_
}_x000D_
_x000D_
public int controleerOpHoudbaarheid() throws ParseException_x000D_
{ _x000D_
DateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");_x000D_
Date huidig = new Date();_x000D_
Date houdbaarheidsDatum = sdf.parse(houdbaarheid); //zet String om naar Date om deze de kunnen vergelijken met huidig._x000D_
_x000D_
if (huidig.after(houdbaarheidsDatum) && alGewaarschuwd==false)_x000D_
{_x000D_
wijzigAantal(0); //indien niet meer houdbaar, moet het eruit en dient het programma_x000D_
//de apotheker hiervan op de hoogte te houden._x000D_
Log.print();_x000D_
System.out.println("Controle houdbaarheidsdatum "+ houdbaarheid +": ");_x000D_
Log.print();_x000D_
System.out.println("Gelieve "+geefMerknaam()+" uit kast "+geefKastID()+" te halen.");_x000D_
return gewensteAantal; //Voorraadbeheer zal het gewensteAantal doorgeven in "besmedlist" om te bestellen._x000D_
}_x000D_
else _x000D_
{_x000D_
return 0; //in alle andere gevallen wel houdbaar_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
public String geefMerknaam(){_x000D_
return merknaam;_x000D_
}_x000D_
_x000D_
public int geefKastID()_x000D_
{_x000D_
return kastID;_x000D_
}_x000D_
_x000D_
public void wijzigMerknaam(String merknaam)_x000D_
{_x000D_
this.merknaam = merknaam; _x000D_
}_x000D_
_x000D_
public void wijzigStofnaam(String stofnaam)_x000D_
{_x000D_
this.stofnaam = stofnaam; _x000D_
}_x000D_
_x000D_
public void wijzigPlaatsBepaling(int kastID)_x000D_
{_x000D_
this.kastID = kastID;_x000D_
}_x000D_
_x000D_
public void wijzigAantal(int aantal)_x000D_
{_x000D_
this.aantal = aantal;_x000D_
}_x000D_
_x000D_
public void wijzigGewensteAantal(int aantal)_x000D_
{_x000D_
gewensteAantal = aantal;_x000D_
}_x000D_
_x000D_
public void wijzigMinimumAantal(int aantal)_x000D_
{_x000D_
minimumAantal = aantal;_x000D_
}_x000D_
_x000D_
public void wijzigFabrikant(String fabrikant)_x000D_
{_x000D_
this.fabrikant = fabrikant;_x000D_
}_x000D_
_x000D_
public void wijzigPrijs(int prijs)_x000D_
{_x000D_
this.prijs = prijs;_x000D_
}_x000D_
_x000D_
public void vermeerderMedicijnAantal(int vermeerder)_x000D_
{_x000D_
aantal = aantal + vermeerder;_x000D_
}_x000D_
_x000D_
}_x000D_
| 4SDDeMeyerKaya/Voorraadbeheer4SD | src/Medicijn.java | 1,292 | //return 0 als er genoeg zijn, en anders hoeveel er te weinig zijn._x000D_ | line_comment | nl | import java.text.SimpleDateFormat;_x000D_
import java.util.Date;_x000D_
import java.text.DateFormat;_x000D_
import java.text.ParseException;_x000D_
_x000D_
public class Medicijn {_x000D_
_x000D_
String merknaam;_x000D_
String stofnaam;_x000D_
int aantal;_x000D_
int gewensteAantal;_x000D_
int minimumAantal;_x000D_
String fabrikant;_x000D_
int prijs;_x000D_
int kastID; _x000D_
String houdbaarheid;//String die de datum voorstelt in het formaat "dd-MM-yyyy' zoals sdf._x000D_
boolean alGewaarschuwd;_x000D_
boolean besteld;_x000D_
_x000D_
_x000D_
public Medicijn(String merknaam, String stofnaam, int aantal, int gewensteAantal, int minimumAantal, String fabrikant, int prijs, int kastID, String houdbaarheid)_x000D_
{_x000D_
this.merknaam = merknaam;_x000D_
this.stofnaam = stofnaam;_x000D_
this.aantal = aantal;_x000D_
this.gewensteAantal = gewensteAantal;_x000D_
this.minimumAantal = minimumAantal;_x000D_
this.fabrikant = fabrikant;_x000D_
this.prijs = prijs;_x000D_
this.kastID = kastID;_x000D_
this.houdbaarheid = houdbaarheid;_x000D_
alGewaarschuwd=false;_x000D_
}_x000D_
_x000D_
public int controleerOpAantal()_x000D_
{_x000D_
//return 0<SUF>
if (aantal <= minimumAantal)_x000D_
{_x000D_
return gewensteAantal-aantal;_x000D_
}_x000D_
_x000D_
else_x000D_
{_x000D_
return 0;_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
public int controleerOpBeide() throws ParseException{_x000D_
int hoogste = 0;_x000D_
if(controleerOpHoudbaarheid()>controleerOpAantal()) _x000D_
hoogste = controleerOpHoudbaarheid();_x000D_
else_x000D_
hoogste=controleerOpAantal();_x000D_
return hoogste;_x000D_
}_x000D_
_x000D_
public int controleerOpHoudbaarheid() throws ParseException_x000D_
{ _x000D_
DateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");_x000D_
Date huidig = new Date();_x000D_
Date houdbaarheidsDatum = sdf.parse(houdbaarheid); //zet String om naar Date om deze de kunnen vergelijken met huidig._x000D_
_x000D_
if (huidig.after(houdbaarheidsDatum) && alGewaarschuwd==false)_x000D_
{_x000D_
wijzigAantal(0); //indien niet meer houdbaar, moet het eruit en dient het programma_x000D_
//de apotheker hiervan op de hoogte te houden._x000D_
Log.print();_x000D_
System.out.println("Controle houdbaarheidsdatum "+ houdbaarheid +": ");_x000D_
Log.print();_x000D_
System.out.println("Gelieve "+geefMerknaam()+" uit kast "+geefKastID()+" te halen.");_x000D_
return gewensteAantal; //Voorraadbeheer zal het gewensteAantal doorgeven in "besmedlist" om te bestellen._x000D_
}_x000D_
else _x000D_
{_x000D_
return 0; //in alle andere gevallen wel houdbaar_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
public String geefMerknaam(){_x000D_
return merknaam;_x000D_
}_x000D_
_x000D_
public int geefKastID()_x000D_
{_x000D_
return kastID;_x000D_
}_x000D_
_x000D_
public void wijzigMerknaam(String merknaam)_x000D_
{_x000D_
this.merknaam = merknaam; _x000D_
}_x000D_
_x000D_
public void wijzigStofnaam(String stofnaam)_x000D_
{_x000D_
this.stofnaam = stofnaam; _x000D_
}_x000D_
_x000D_
public void wijzigPlaatsBepaling(int kastID)_x000D_
{_x000D_
this.kastID = kastID;_x000D_
}_x000D_
_x000D_
public void wijzigAantal(int aantal)_x000D_
{_x000D_
this.aantal = aantal;_x000D_
}_x000D_
_x000D_
public void wijzigGewensteAantal(int aantal)_x000D_
{_x000D_
gewensteAantal = aantal;_x000D_
}_x000D_
_x000D_
public void wijzigMinimumAantal(int aantal)_x000D_
{_x000D_
minimumAantal = aantal;_x000D_
}_x000D_
_x000D_
public void wijzigFabrikant(String fabrikant)_x000D_
{_x000D_
this.fabrikant = fabrikant;_x000D_
}_x000D_
_x000D_
public void wijzigPrijs(int prijs)_x000D_
{_x000D_
this.prijs = prijs;_x000D_
}_x000D_
_x000D_
public void vermeerderMedicijnAantal(int vermeerder)_x000D_
{_x000D_
aantal = aantal + vermeerder;_x000D_
}_x000D_
_x000D_
}_x000D_
| True | 1,875 | 29 | 2,124 | 31 | 1,926 | 23 | 2,124 | 31 | 2,210 | 31 | false | false | false | false | false | true |
2,537 | 18693_2 | //Demo MySQL
//Met Connectionpooling
package server;
import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;
import java.sql.*;
public class MySQLDatabase_char {
private static MySQLDatabase_char instance=new MySQLDatabase_char();
private MysqlConnectionPoolDataSource pool;
private String sequenceTable;
private boolean sequenceSupported;
private MySQLDatabase_char() {
pool = new MysqlConnectionPoolDataSource();
//zelf aanvullen!
//maak connectie met de database
pool.setDatabaseName("characters");
pool.setServerName("hairy.dyndns.biz");
pool.setUser("selectonly");
pool.setPassword("1234");
pool.setPort(3306);
//sequenceTable="pkgenerator";
sequenceSupported = false;
}
public static MySQLDatabase_char getInstance(){
return instance;
}
//openen connectie
public Connection getConnection() throws SQLException{
return pool.getConnection();
}
/**
* Creëert een nieuw id voor een tabel en kolom, indien
* een Sequence gebruikt wordt, wordt de tabel en kolom genegeerd.
*/
public int createNewID(Connection conn, String tabel,String kolom){
try{
if ( sequenceSupported){
String sql = "select nextval('"+sequenceTable+"')";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
if ( rs.next()){
return rs.getInt(1);
}
return -1;
}else{
if ( conn != null && !conn.isClosed()){
String sql = "select max("+kolom+") as maxid from "+tabel;
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
if ( rs.next() ){
int maxid = rs.getInt("maxid");
return maxid+1;
}
return -1;
}
}
}catch(SQLException ex){
ex.printStackTrace();
}
return -1;
}
/**
* Deze methode kan gebruikt worden om te testen wat er precies in een
* ResultSet te vinden is.
* Let op : De ResultSet kan je daarna niet meer gebruiken!
*/
public void printResultSet(ResultSet rs){
try{
ResultSetMetaData rsmd = rs.getMetaData();
for (int i=1;i <= rsmd.getColumnCount();i++){
System.out.print(rsmd.getColumnLabel(i));
System.out.print(",");
}
System.out.println();
while(rs.next()){
for ( int i = 1 ; i <= rsmd.getColumnCount(); i++){
System.out.print(rs.getString(i));
System.out.print(",");
}
System.out.println();
}
}catch(Exception ex){
ex.printStackTrace();
}
}
public static void main(String[] args)throws Exception{
System.out.println("Execute this main method to test the connection !");
MySQLDatabase_char db = MySQLDatabase_char.getInstance();
Connection c = db.getConnection();
System.out.println("Connectie openen geslaagd");
c.close();
System.out.println("Connectie sluiten geslaagd");
}
} | devalacarte/newPhoenix | JavaApplication1/src/server/MySQLDatabase_char.java | 952 | /**
* Creëert een nieuw id voor een tabel en kolom, indien
* een Sequence gebruikt wordt, wordt de tabel en kolom genegeerd.
*/ | block_comment | nl | //Demo MySQL
//Met Connectionpooling
package server;
import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;
import java.sql.*;
public class MySQLDatabase_char {
private static MySQLDatabase_char instance=new MySQLDatabase_char();
private MysqlConnectionPoolDataSource pool;
private String sequenceTable;
private boolean sequenceSupported;
private MySQLDatabase_char() {
pool = new MysqlConnectionPoolDataSource();
//zelf aanvullen!
//maak connectie met de database
pool.setDatabaseName("characters");
pool.setServerName("hairy.dyndns.biz");
pool.setUser("selectonly");
pool.setPassword("1234");
pool.setPort(3306);
//sequenceTable="pkgenerator";
sequenceSupported = false;
}
public static MySQLDatabase_char getInstance(){
return instance;
}
//openen connectie
public Connection getConnection() throws SQLException{
return pool.getConnection();
}
/**
* Creëert een nieuw<SUF>*/
public int createNewID(Connection conn, String tabel,String kolom){
try{
if ( sequenceSupported){
String sql = "select nextval('"+sequenceTable+"')";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
if ( rs.next()){
return rs.getInt(1);
}
return -1;
}else{
if ( conn != null && !conn.isClosed()){
String sql = "select max("+kolom+") as maxid from "+tabel;
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
if ( rs.next() ){
int maxid = rs.getInt("maxid");
return maxid+1;
}
return -1;
}
}
}catch(SQLException ex){
ex.printStackTrace();
}
return -1;
}
/**
* Deze methode kan gebruikt worden om te testen wat er precies in een
* ResultSet te vinden is.
* Let op : De ResultSet kan je daarna niet meer gebruiken!
*/
public void printResultSet(ResultSet rs){
try{
ResultSetMetaData rsmd = rs.getMetaData();
for (int i=1;i <= rsmd.getColumnCount();i++){
System.out.print(rsmd.getColumnLabel(i));
System.out.print(",");
}
System.out.println();
while(rs.next()){
for ( int i = 1 ; i <= rsmd.getColumnCount(); i++){
System.out.print(rs.getString(i));
System.out.print(",");
}
System.out.println();
}
}catch(Exception ex){
ex.printStackTrace();
}
}
public static void main(String[] args)throws Exception{
System.out.println("Execute this main method to test the connection !");
MySQLDatabase_char db = MySQLDatabase_char.getInstance();
Connection c = db.getConnection();
System.out.println("Connectie openen geslaagd");
c.close();
System.out.println("Connectie sluiten geslaagd");
}
} | True | 669 | 40 | 749 | 38 | 813 | 37 | 749 | 38 | 908 | 45 | false | false | false | false | false | true |
3,016 | 119694_9 | package org.httpkit.server;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.httpkit.HttpMethod;
import org.httpkit.HttpUtils;
import org.httpkit.HttpVersion;
import org.httpkit.LineReader;
import org.httpkit.LineTooLargeException;
import org.httpkit.ProtocolException;
import org.httpkit.RequestTooLargeException;
import static org.httpkit.HttpUtils.*;
import static org.httpkit.HttpVersion.HTTP_1_0;
import static org.httpkit.HttpVersion.HTTP_1_1;
public class HttpDecoder {
public enum State {
ALL_READ, CONNECTION_OPEN, READ_INITIAL, READ_HEADER, READ_FIXED_LENGTH_CONTENT, READ_CHUNK_SIZE, READ_CHUNKED_CONTENT, READ_CHUNK_FOOTER, READ_CHUNK_DELIMITER,
}
/**
* Pattern for matching numbers 0 to 255. We use this in the IPV4 address pattern to prevent invalid sequences
* from be parsed by InetAddress.getByName and thus being treated as a name instead of an address.
*/
private static final String IPV4SEG = "(?:0|1\\d{0,2}|2(?:[0-4]\\d*|5[0-5]?|[6-9])?|[3-9]\\d?)";
private static final String IPV4ADDR = IPV4SEG + "(?:\\." + IPV4SEG + "){3}";
/**
* Pattern for a port number. We are not as strict in our pattern matching as we are with ipv4 address
* and instead rely upon Integer.parseInt and a range check. Port 0 is invalid, so we disallow that here.
*/
private static final String PORT = "[1-9]\\d{0,4}";
/**
* The PROXY protocol header is quite strict in what it allows, specifying for example that only
* a single space character (\x20) is allowed between components.
*/
private static final Pattern PROXY_PATTERN = Pattern.compile(
"PROXY\\x20TCP4\\x20(" + IPV4ADDR + ")\\x20(" + IPV4ADDR +")\\x20(" + PORT + ")\\x20(" + PORT + ")"
);
private State state;
private ProxyProtocolOption proxyProtocolOption;
private int readRemaining = 0; // bytes need read
private int readCount = 0; // already read bytes count
private String xForwardedFor;
private String xForwardedProto;
private int xForwardedPort;
HttpRequest request; // package visible
private Map<String, Object> headers = new TreeMap<String, Object>();
byte[] content;
private final int maxBody;
private final LineReader lineReader;
public HttpDecoder(int maxBody, int maxLine, ProxyProtocolOption proxyProtocolOption) {
this.maxBody = maxBody;
this.lineReader = new LineReader(maxLine);
this.proxyProtocolOption = (proxyProtocolOption == null)
? ProxyProtocolOption.DISABLED : proxyProtocolOption;
this.state = (proxyProtocolOption == ProxyProtocolOption.DISABLED)
? State.READ_INITIAL : State.CONNECTION_OPEN;
}
private boolean parseProxyLine(String line) throws ProtocolException {
// PROXY TCP4 255.255.255.255 255.255.255.255 65535 65535\r\n
if (!line.startsWith("PROXY ")) {
return false;
}
final Matcher m = PROXY_PATTERN.matcher(line);
if (!m.matches()) {
throw new ProtocolException("Unsupported or malformed proxy header: "+line);
}
try {
final InetAddress clientAddr = InetAddress.getByName(m.group(1));
final InetAddress proxyAddr = InetAddress.getByName(m.group(2));
final int clientPort = Integer.parseInt(m.group(3), 10);
final int proxyPort = Integer.parseInt(m.group(4), 10);
if (((clientPort | proxyPort) & ~0xffff) != 0) {
throw new ProtocolException("Invalid port number: "+line);
}
xForwardedFor = clientAddr.getHostAddress();
if (proxyPort == 80) {
xForwardedProto = "http";
} else if (proxyPort == 443) {
xForwardedProto = "https";
}
xForwardedPort = proxyPort;
return true;
} catch (NumberFormatException ex) {
throw new ProtocolException("Malformed port in: "+line);
} catch (UnknownHostException ex) {
throw new ProtocolException("Malformed address in: "+line);
}
}
private void createRequest(String sb) throws ProtocolException {
int aStart;
int aEnd;
int bStart;
int bEnd;
int cStart;
int cEnd;
aStart = findNonWhitespace(sb, 0);
aEnd = findWhitespace(sb, aStart);
bStart = findNonWhitespace(sb, aEnd);
bEnd = findWhitespace(sb, bStart);
cStart = findNonWhitespace(sb, bEnd);
cEnd = findEndOfString(sb, cStart);
if (cStart < cEnd) {
try {
HttpMethod method = HttpMethod.valueOf(sb.substring(aStart, aEnd).toUpperCase());
HttpVersion version = HTTP_1_1;
if ("HTTP/1.0".equals(sb.substring(cStart, cEnd))) {
version = HTTP_1_0;
}
request = new HttpRequest(method, sb.substring(bStart, bEnd), version);
} catch (Exception e) {
throw new ProtocolException("method not understand");
}
} else {
throw new ProtocolException("not http?");
}
}
public boolean requiresContinue() {
if (request == null || request.version != HTTP_1_1 || request.sentContinue) {
return false;
} else {
String expect = (String) headers.get(EXPECT);
return(expect != null && CONTINUE.equalsIgnoreCase(expect));
}
}
public void setSentContinue() {
request.sentContinue = true;
}
public HttpRequest decode(ByteBuffer buffer) throws LineTooLargeException,
ProtocolException, RequestTooLargeException {
String line;
while (buffer.hasRemaining()) {
switch (state) {
case ALL_READ:
return request;
case CONNECTION_OPEN:
line = lineReader.readLine(buffer);
if (line != null) {
// parseProxyLines returns true if the line parsed
// false if it was not a PROXY line
// or throws ProtocolException, if the PROXY line is malformed or unsupported.
if (parseProxyLine(line)) {
// valid proxy header
state = State.READ_INITIAL;
} else if (proxyProtocolOption == ProxyProtocolOption.OPTIONAL) {
// did not parse as a proxy header, try to create a request from it
// as the READ_INITIAL state would.
createRequest(line);
state = State.READ_HEADER;
} else {
throw new ProtocolException("Expected PROXY header, got: "+line);
}
}
break;
case READ_INITIAL:
line = lineReader.readLine(buffer);
if (line != null) {
createRequest(line);
state = State.READ_HEADER;
}
break;
case READ_HEADER:
readHeaders(buffer);
break;
case READ_CHUNK_SIZE:
line = lineReader.readLine(buffer);
if (line != null) {
readRemaining = getChunkSize(line);
if (readRemaining == 0) {
state = State.READ_CHUNK_FOOTER;
} else {
throwIfBodyIsTooLarge();
if (content == null) {
content = new byte[readRemaining];
} else if (content.length < readCount + readRemaining) {
// *1.3 to protect slow client
int newLength = (int) ((readRemaining + readCount) * 1.3);
content = Arrays.copyOf(content, newLength);
}
state = State.READ_CHUNKED_CONTENT;
}
}
break;
case READ_FIXED_LENGTH_CONTENT:
readFixedLength(buffer);
if (readRemaining == 0) {
finish();
}
break;
case READ_CHUNKED_CONTENT:
readFixedLength(buffer);
if (readRemaining == 0) {
state = State.READ_CHUNK_DELIMITER;
}
break;
case READ_CHUNK_FOOTER:
readEmptyLine(buffer);
finish();
break;
case READ_CHUNK_DELIMITER:
readEmptyLine(buffer);
state = State.READ_CHUNK_SIZE;
break;
}
}
return state == State.ALL_READ ? request : null;
}
private void finish() {
state = State.ALL_READ;
request.setBody(content, readCount);
}
void readEmptyLine(ByteBuffer buffer) {
byte b = buffer.get();
if (b == CR && buffer.hasRemaining()) {
buffer.get(); // should be LF
}
}
void readFixedLength(ByteBuffer buffer) {
int toRead = Math.min(buffer.remaining(), readRemaining);
buffer.get(content, readCount, toRead);
readRemaining -= toRead;
readCount += toRead;
}
private void readHeaders(ByteBuffer buffer) throws LineTooLargeException,
RequestTooLargeException, ProtocolException {
if (proxyProtocolOption == ProxyProtocolOption.OPTIONAL
|| proxyProtocolOption == ProxyProtocolOption.ENABLED) {
headers.put("x-forwarded-for", xForwardedFor);
headers.put("x-forwarded-proto", xForwardedProto);
headers.put("x-forwarded-port", xForwardedPort);
}
String line = lineReader.readLine(buffer);
while (line != null && !line.isEmpty()) {
HttpUtils.splitAndAddHeader(line, headers);
line = lineReader.readLine(buffer);
}
if (line == null) {
return;
}
request.setHeaders(headers);
String te = HttpUtils.getStringValue(headers, TRANSFER_ENCODING);
if (CHUNKED.equals(te)) {
state = State.READ_CHUNK_SIZE;
} else {
String cl = HttpUtils.getStringValue(headers, CONTENT_LENGTH);
if (cl != null) {
try {
readRemaining = Integer.parseInt(cl);
if (readRemaining > 0) {
throwIfBodyIsTooLarge();
content = new byte[readRemaining];
state = State.READ_FIXED_LENGTH_CONTENT;
} else {
state = State.ALL_READ;
}
} catch (NumberFormatException e) {
throw new ProtocolException(e.getMessage());
}
} else {
state = State.ALL_READ;
}
}
}
public void reset() {
state = State.READ_INITIAL;
headers = new TreeMap<String, Object>();
readCount = 0;
content = null;
lineReader.reset();
request = null;
}
private void throwIfBodyIsTooLarge() throws RequestTooLargeException {
if (readCount + readRemaining > maxBody) {
throw new RequestTooLargeException("request body " + (readCount + readRemaining)
+ "; max request body " + maxBody);
}
}
}
| http-kit/http-kit | src/java/org/httpkit/server/HttpDecoder.java | 3,287 | // valid proxy header | line_comment | nl | package org.httpkit.server;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.httpkit.HttpMethod;
import org.httpkit.HttpUtils;
import org.httpkit.HttpVersion;
import org.httpkit.LineReader;
import org.httpkit.LineTooLargeException;
import org.httpkit.ProtocolException;
import org.httpkit.RequestTooLargeException;
import static org.httpkit.HttpUtils.*;
import static org.httpkit.HttpVersion.HTTP_1_0;
import static org.httpkit.HttpVersion.HTTP_1_1;
public class HttpDecoder {
public enum State {
ALL_READ, CONNECTION_OPEN, READ_INITIAL, READ_HEADER, READ_FIXED_LENGTH_CONTENT, READ_CHUNK_SIZE, READ_CHUNKED_CONTENT, READ_CHUNK_FOOTER, READ_CHUNK_DELIMITER,
}
/**
* Pattern for matching numbers 0 to 255. We use this in the IPV4 address pattern to prevent invalid sequences
* from be parsed by InetAddress.getByName and thus being treated as a name instead of an address.
*/
private static final String IPV4SEG = "(?:0|1\\d{0,2}|2(?:[0-4]\\d*|5[0-5]?|[6-9])?|[3-9]\\d?)";
private static final String IPV4ADDR = IPV4SEG + "(?:\\." + IPV4SEG + "){3}";
/**
* Pattern for a port number. We are not as strict in our pattern matching as we are with ipv4 address
* and instead rely upon Integer.parseInt and a range check. Port 0 is invalid, so we disallow that here.
*/
private static final String PORT = "[1-9]\\d{0,4}";
/**
* The PROXY protocol header is quite strict in what it allows, specifying for example that only
* a single space character (\x20) is allowed between components.
*/
private static final Pattern PROXY_PATTERN = Pattern.compile(
"PROXY\\x20TCP4\\x20(" + IPV4ADDR + ")\\x20(" + IPV4ADDR +")\\x20(" + PORT + ")\\x20(" + PORT + ")"
);
private State state;
private ProxyProtocolOption proxyProtocolOption;
private int readRemaining = 0; // bytes need read
private int readCount = 0; // already read bytes count
private String xForwardedFor;
private String xForwardedProto;
private int xForwardedPort;
HttpRequest request; // package visible
private Map<String, Object> headers = new TreeMap<String, Object>();
byte[] content;
private final int maxBody;
private final LineReader lineReader;
public HttpDecoder(int maxBody, int maxLine, ProxyProtocolOption proxyProtocolOption) {
this.maxBody = maxBody;
this.lineReader = new LineReader(maxLine);
this.proxyProtocolOption = (proxyProtocolOption == null)
? ProxyProtocolOption.DISABLED : proxyProtocolOption;
this.state = (proxyProtocolOption == ProxyProtocolOption.DISABLED)
? State.READ_INITIAL : State.CONNECTION_OPEN;
}
private boolean parseProxyLine(String line) throws ProtocolException {
// PROXY TCP4 255.255.255.255 255.255.255.255 65535 65535\r\n
if (!line.startsWith("PROXY ")) {
return false;
}
final Matcher m = PROXY_PATTERN.matcher(line);
if (!m.matches()) {
throw new ProtocolException("Unsupported or malformed proxy header: "+line);
}
try {
final InetAddress clientAddr = InetAddress.getByName(m.group(1));
final InetAddress proxyAddr = InetAddress.getByName(m.group(2));
final int clientPort = Integer.parseInt(m.group(3), 10);
final int proxyPort = Integer.parseInt(m.group(4), 10);
if (((clientPort | proxyPort) & ~0xffff) != 0) {
throw new ProtocolException("Invalid port number: "+line);
}
xForwardedFor = clientAddr.getHostAddress();
if (proxyPort == 80) {
xForwardedProto = "http";
} else if (proxyPort == 443) {
xForwardedProto = "https";
}
xForwardedPort = proxyPort;
return true;
} catch (NumberFormatException ex) {
throw new ProtocolException("Malformed port in: "+line);
} catch (UnknownHostException ex) {
throw new ProtocolException("Malformed address in: "+line);
}
}
private void createRequest(String sb) throws ProtocolException {
int aStart;
int aEnd;
int bStart;
int bEnd;
int cStart;
int cEnd;
aStart = findNonWhitespace(sb, 0);
aEnd = findWhitespace(sb, aStart);
bStart = findNonWhitespace(sb, aEnd);
bEnd = findWhitespace(sb, bStart);
cStart = findNonWhitespace(sb, bEnd);
cEnd = findEndOfString(sb, cStart);
if (cStart < cEnd) {
try {
HttpMethod method = HttpMethod.valueOf(sb.substring(aStart, aEnd).toUpperCase());
HttpVersion version = HTTP_1_1;
if ("HTTP/1.0".equals(sb.substring(cStart, cEnd))) {
version = HTTP_1_0;
}
request = new HttpRequest(method, sb.substring(bStart, bEnd), version);
} catch (Exception e) {
throw new ProtocolException("method not understand");
}
} else {
throw new ProtocolException("not http?");
}
}
public boolean requiresContinue() {
if (request == null || request.version != HTTP_1_1 || request.sentContinue) {
return false;
} else {
String expect = (String) headers.get(EXPECT);
return(expect != null && CONTINUE.equalsIgnoreCase(expect));
}
}
public void setSentContinue() {
request.sentContinue = true;
}
public HttpRequest decode(ByteBuffer buffer) throws LineTooLargeException,
ProtocolException, RequestTooLargeException {
String line;
while (buffer.hasRemaining()) {
switch (state) {
case ALL_READ:
return request;
case CONNECTION_OPEN:
line = lineReader.readLine(buffer);
if (line != null) {
// parseProxyLines returns true if the line parsed
// false if it was not a PROXY line
// or throws ProtocolException, if the PROXY line is malformed or unsupported.
if (parseProxyLine(line)) {
// valid proxy<SUF>
state = State.READ_INITIAL;
} else if (proxyProtocolOption == ProxyProtocolOption.OPTIONAL) {
// did not parse as a proxy header, try to create a request from it
// as the READ_INITIAL state would.
createRequest(line);
state = State.READ_HEADER;
} else {
throw new ProtocolException("Expected PROXY header, got: "+line);
}
}
break;
case READ_INITIAL:
line = lineReader.readLine(buffer);
if (line != null) {
createRequest(line);
state = State.READ_HEADER;
}
break;
case READ_HEADER:
readHeaders(buffer);
break;
case READ_CHUNK_SIZE:
line = lineReader.readLine(buffer);
if (line != null) {
readRemaining = getChunkSize(line);
if (readRemaining == 0) {
state = State.READ_CHUNK_FOOTER;
} else {
throwIfBodyIsTooLarge();
if (content == null) {
content = new byte[readRemaining];
} else if (content.length < readCount + readRemaining) {
// *1.3 to protect slow client
int newLength = (int) ((readRemaining + readCount) * 1.3);
content = Arrays.copyOf(content, newLength);
}
state = State.READ_CHUNKED_CONTENT;
}
}
break;
case READ_FIXED_LENGTH_CONTENT:
readFixedLength(buffer);
if (readRemaining == 0) {
finish();
}
break;
case READ_CHUNKED_CONTENT:
readFixedLength(buffer);
if (readRemaining == 0) {
state = State.READ_CHUNK_DELIMITER;
}
break;
case READ_CHUNK_FOOTER:
readEmptyLine(buffer);
finish();
break;
case READ_CHUNK_DELIMITER:
readEmptyLine(buffer);
state = State.READ_CHUNK_SIZE;
break;
}
}
return state == State.ALL_READ ? request : null;
}
private void finish() {
state = State.ALL_READ;
request.setBody(content, readCount);
}
void readEmptyLine(ByteBuffer buffer) {
byte b = buffer.get();
if (b == CR && buffer.hasRemaining()) {
buffer.get(); // should be LF
}
}
void readFixedLength(ByteBuffer buffer) {
int toRead = Math.min(buffer.remaining(), readRemaining);
buffer.get(content, readCount, toRead);
readRemaining -= toRead;
readCount += toRead;
}
private void readHeaders(ByteBuffer buffer) throws LineTooLargeException,
RequestTooLargeException, ProtocolException {
if (proxyProtocolOption == ProxyProtocolOption.OPTIONAL
|| proxyProtocolOption == ProxyProtocolOption.ENABLED) {
headers.put("x-forwarded-for", xForwardedFor);
headers.put("x-forwarded-proto", xForwardedProto);
headers.put("x-forwarded-port", xForwardedPort);
}
String line = lineReader.readLine(buffer);
while (line != null && !line.isEmpty()) {
HttpUtils.splitAndAddHeader(line, headers);
line = lineReader.readLine(buffer);
}
if (line == null) {
return;
}
request.setHeaders(headers);
String te = HttpUtils.getStringValue(headers, TRANSFER_ENCODING);
if (CHUNKED.equals(te)) {
state = State.READ_CHUNK_SIZE;
} else {
String cl = HttpUtils.getStringValue(headers, CONTENT_LENGTH);
if (cl != null) {
try {
readRemaining = Integer.parseInt(cl);
if (readRemaining > 0) {
throwIfBodyIsTooLarge();
content = new byte[readRemaining];
state = State.READ_FIXED_LENGTH_CONTENT;
} else {
state = State.ALL_READ;
}
} catch (NumberFormatException e) {
throw new ProtocolException(e.getMessage());
}
} else {
state = State.ALL_READ;
}
}
}
public void reset() {
state = State.READ_INITIAL;
headers = new TreeMap<String, Object>();
readCount = 0;
content = null;
lineReader.reset();
request = null;
}
private void throwIfBodyIsTooLarge() throws RequestTooLargeException {
if (readCount + readRemaining > maxBody) {
throw new RequestTooLargeException("request body " + (readCount + readRemaining)
+ "; max request body " + maxBody);
}
}
}
| False | 2,442 | 4 | 2,675 | 4 | 2,939 | 4 | 2,675 | 4 | 3,331 | 4 | false | false | false | false | false | true |
1,727 | 23434_10 | package Hoofdstuk10;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by Thomas-X on 9/28/2016. And effectively coded by the only Thomas-X
*/
public class Praktijkopdracht extends Applet {
TextField tekstvak1;
String tekst;
@Override
public void init() {
super.init();
tekstvak1 = new TextField("", 90);
tekstvak1.addActionListener(new onvoldoendechecker());
add(tekstvak1);
tekst = "";
}
public void paint(Graphics g) {
// Color setkleur;
// setkleur = Color.RED;
g.drawString("" + tekst, 50, 50);
// setBackground((setkleur));
}
public class onvoldoendechecker implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
tekstvak1.paint(getGraphics());
if (Double.parseDouble(tekstvak1.getText()) < 4) { //Of || 3x maar ik ben lui dus je kan nu -1 etc gebruiken en dan nog steeds slecht krijgen
tekst = "Je hebt een 'slecht', SLECHT HOOR!";
// tekstvak1.setText("Je hebt een 'slecht', SLECHT HOOR!");
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
tekstvak1.setText("");
repaint();
} else {
if (Double.parseDouble(tekstvak1.getText()) == 4) {
// getGraphics().drawString("Je hebt een onvoldoende, bah!", 60, 60);
// tekstvak1.setText("Je hebt een onvoldoende, bah!");
tekst = "Je hebt een onvoldoende, bah!";
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
tekstvak1.setText("");
repaint();
} else {
if (Double.parseDouble(tekstvak1.getText()) == 5) {
// getGraphics().drawString("Je hebt een matig, komop, dit is bagger", 60, 60);
// tekstvak1.setText("Je hebt een matig, komop, dit is bagger");
tekst = "Je hebt een matig, komop, dit is bagger";
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
tekstvak1.setText("");
repaint();
} else {
if (Double.parseDouble(tekstvak1.getText()) == 6 || (Double.parseDouble(tekstvak1.getText())) == 7) {
// getGraphics().drawString("Je hebt een voldoende, KAN BETER HEH?", 60, 60);
// tekstvak1.setText("Je hebt een voldoende, KAN BETER HEH?");
tekst = "Je hebt een voldoende, KAN BETER HEH?";
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
tekstvak1.setText("");
repaint();
} else {
if (Double.parseDouble(tekstvak1.getText()) == 8 || (Double.parseDouble(tekstvak1.getText())) == 9 || (Double.parseDouble(tekstvak1.getText())) == 10) {
// getGraphics().drawString("Je hebt een goed, MOOI MAN", 60, 60);
// tekstvak1.setText("Je hebt een goed, MOOI MAN");
tekst = "Je hebt een goed, MOOI MAN";
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
tekstvak1.setText("");
repaint();
} else {
// tekstvak1.setText("Verkeerd cijfer ingevoerd!");
tekst = "Verkeerd cijfer ingevoerd!";
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
tekstvak1.setText("");
repaint();
}
}
}
}
}
}
}
}
| Thomas-X/old-repos | javaopdrachten/src/Hoofdstuk10/Praktijkopdracht.java | 1,384 | // getGraphics().drawString("Je hebt een goed, MOOI MAN", 60, 60); | line_comment | nl | package Hoofdstuk10;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by Thomas-X on 9/28/2016. And effectively coded by the only Thomas-X
*/
public class Praktijkopdracht extends Applet {
TextField tekstvak1;
String tekst;
@Override
public void init() {
super.init();
tekstvak1 = new TextField("", 90);
tekstvak1.addActionListener(new onvoldoendechecker());
add(tekstvak1);
tekst = "";
}
public void paint(Graphics g) {
// Color setkleur;
// setkleur = Color.RED;
g.drawString("" + tekst, 50, 50);
// setBackground((setkleur));
}
public class onvoldoendechecker implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
tekstvak1.paint(getGraphics());
if (Double.parseDouble(tekstvak1.getText()) < 4) { //Of || 3x maar ik ben lui dus je kan nu -1 etc gebruiken en dan nog steeds slecht krijgen
tekst = "Je hebt een 'slecht', SLECHT HOOR!";
// tekstvak1.setText("Je hebt een 'slecht', SLECHT HOOR!");
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
tekstvak1.setText("");
repaint();
} else {
if (Double.parseDouble(tekstvak1.getText()) == 4) {
// getGraphics().drawString("Je hebt een onvoldoende, bah!", 60, 60);
// tekstvak1.setText("Je hebt een onvoldoende, bah!");
tekst = "Je hebt een onvoldoende, bah!";
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
tekstvak1.setText("");
repaint();
} else {
if (Double.parseDouble(tekstvak1.getText()) == 5) {
// getGraphics().drawString("Je hebt een matig, komop, dit is bagger", 60, 60);
// tekstvak1.setText("Je hebt een matig, komop, dit is bagger");
tekst = "Je hebt een matig, komop, dit is bagger";
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
tekstvak1.setText("");
repaint();
} else {
if (Double.parseDouble(tekstvak1.getText()) == 6 || (Double.parseDouble(tekstvak1.getText())) == 7) {
// getGraphics().drawString("Je hebt een voldoende, KAN BETER HEH?", 60, 60);
// tekstvak1.setText("Je hebt een voldoende, KAN BETER HEH?");
tekst = "Je hebt een voldoende, KAN BETER HEH?";
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
tekstvak1.setText("");
repaint();
} else {
if (Double.parseDouble(tekstvak1.getText()) == 8 || (Double.parseDouble(tekstvak1.getText())) == 9 || (Double.parseDouble(tekstvak1.getText())) == 10) {
// getGraphics().drawString("Je hebt<SUF>
// tekstvak1.setText("Je hebt een goed, MOOI MAN");
tekst = "Je hebt een goed, MOOI MAN";
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
tekstvak1.setText("");
repaint();
} else {
// tekstvak1.setText("Verkeerd cijfer ingevoerd!");
tekst = "Verkeerd cijfer ingevoerd!";
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
tekstvak1.setText("");
repaint();
}
}
}
}
}
}
}
}
| False | 953 | 25 | 1,093 | 28 | 1,076 | 25 | 1,093 | 28 | 1,325 | 30 | false | false | false | false | false | true |
1,494 | 194306_1 | package nl.novi.techiteasyfull.config;
import nl.novi.techiteasyfull.filter.JwtRequestFilter;
import nl.novi.techiteasyfull.service.CustomUserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class SpringSercurityConfig {
public final CustomUserDetailsService customerUserDetails;
private final JwtRequestFilter jwtRequestFilter;
public SpringSercurityConfig(CustomUserDetailsService customerUserDetails, JwtRequestFilter jwtRequestFilter) {
this.customerUserDetails = customerUserDetails;
this.jwtRequestFilter = jwtRequestFilter;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http, PasswordEncoder passwordEncoder) throws Exception {
var auth = new DaoAuthenticationProvider();
auth.setPasswordEncoder(passwordEncoder);
auth.setUserDetailsService(customerUserDetails);
return new ProviderManager(auth);
}
@Bean
protected SecurityFilterChain filter (HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.httpBasic(basic -> basic.disable())
.cors(Customizer.withDefaults())
.authorizeHttpRequests(auth ->
auth
// Wanneer je deze uncomments, staat je hele security open. Je hebt dan alleen nog een jwt nodig.
.requestMatchers("/**").permitAll()
// .requestMatchers(HttpMethod.POST, "/users").hasRole("ADMIN")
// .requestMatchers(HttpMethod.GET,"/users").hasRole("ADMIN")
// .requestMatchers(HttpMethod.POST,"/users/**").hasRole("ADMIN")
// .requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN")
// .requestMatchers(HttpMethod.POST, "/cimodules").hasRole("ADMIN")
// .requestMatchers(HttpMethod.DELETE, "/cimodules/**").hasRole("ADMIN")
// .requestMatchers(HttpMethod.POST, "/remotecontrollers").hasRole("ADMIN")
// .requestMatchers(HttpMethod.DELETE, "/remotecontrollers/**").hasRole("ADMIN")
// .requestMatchers(HttpMethod.POST, "/televisions").hasRole("ADMIN")
// .requestMatchers(HttpMethod.DELETE, "/televisions/**").hasRole("ADMIN")
// .requestMatchers(HttpMethod.POST, "/wallbrackets").hasRole("ADMIN")
// .requestMatchers(HttpMethod.DELETE, "/wallbrackets/**").hasRole("ADMIN")
// // Je mag meerdere paths tegelijk definieren
// .requestMatchers("/cimodules", "/remotecontrollers", "/televisions", "/wallbrackets").hasAnyRole("ADMIN", "USER")
.requestMatchers("/authenticated").authenticated()
.requestMatchers("/authenticate").permitAll()
.anyRequest().denyAll()
)
.sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}
| RowanPl/TechItEasyFull | src/main/java/nl/novi/techiteasyfull/config/SpringSercurityConfig.java | 1,124 | // // Je mag meerdere paths tegelijk definieren | line_comment | nl | package nl.novi.techiteasyfull.config;
import nl.novi.techiteasyfull.filter.JwtRequestFilter;
import nl.novi.techiteasyfull.service.CustomUserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class SpringSercurityConfig {
public final CustomUserDetailsService customerUserDetails;
private final JwtRequestFilter jwtRequestFilter;
public SpringSercurityConfig(CustomUserDetailsService customerUserDetails, JwtRequestFilter jwtRequestFilter) {
this.customerUserDetails = customerUserDetails;
this.jwtRequestFilter = jwtRequestFilter;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http, PasswordEncoder passwordEncoder) throws Exception {
var auth = new DaoAuthenticationProvider();
auth.setPasswordEncoder(passwordEncoder);
auth.setUserDetailsService(customerUserDetails);
return new ProviderManager(auth);
}
@Bean
protected SecurityFilterChain filter (HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.httpBasic(basic -> basic.disable())
.cors(Customizer.withDefaults())
.authorizeHttpRequests(auth ->
auth
// Wanneer je deze uncomments, staat je hele security open. Je hebt dan alleen nog een jwt nodig.
.requestMatchers("/**").permitAll()
// .requestMatchers(HttpMethod.POST, "/users").hasRole("ADMIN")
// .requestMatchers(HttpMethod.GET,"/users").hasRole("ADMIN")
// .requestMatchers(HttpMethod.POST,"/users/**").hasRole("ADMIN")
// .requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN")
// .requestMatchers(HttpMethod.POST, "/cimodules").hasRole("ADMIN")
// .requestMatchers(HttpMethod.DELETE, "/cimodules/**").hasRole("ADMIN")
// .requestMatchers(HttpMethod.POST, "/remotecontrollers").hasRole("ADMIN")
// .requestMatchers(HttpMethod.DELETE, "/remotecontrollers/**").hasRole("ADMIN")
// .requestMatchers(HttpMethod.POST, "/televisions").hasRole("ADMIN")
// .requestMatchers(HttpMethod.DELETE, "/televisions/**").hasRole("ADMIN")
// .requestMatchers(HttpMethod.POST, "/wallbrackets").hasRole("ADMIN")
// .requestMatchers(HttpMethod.DELETE, "/wallbrackets/**").hasRole("ADMIN")
// // Je mag<SUF>
// .requestMatchers("/cimodules", "/remotecontrollers", "/televisions", "/wallbrackets").hasAnyRole("ADMIN", "USER")
.requestMatchers("/authenticated").authenticated()
.requestMatchers("/authenticate").permitAll()
.anyRequest().denyAll()
)
.sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}
| True | 752 | 13 | 890 | 13 | 904 | 12 | 890 | 13 | 1,081 | 16 | false | false | false | false | false | true |
3,407 | 189893_5 | /*
* Units.java
* Copyright (C) 2010 Kimmo Tuukkanen
*
* This file is part of Java Marine API.
* <http://ktuukkan.github.io/marine-api/>
*
* Java Marine API is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Java Marine API 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 Java Marine API. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.marineapi.nmea.util;
/**
* Defines the supported units of measure.
*
* @author Kimmo Tuukkanen
*
*/
public enum Units {
/** Pressure in bars */
BARS('B'),
/** Temperature in degrees Celsius (centigrade) */
CELSIUS('C'),
/** Depth in fathoms */
FATHOMS('F'),
/** Length in feet */
FEET('f'),
/** Distance/pressure in inches */
INCHES('I'),
/** Kilometers - used for distance, and speed (as kilometers per hour) */
KILOMETERS('K'),
/** Length in meter */
METER('M'),
/** Nautical miles - used for distance, and for speed (nautical miles per hour, which are knots) */
NAUTICAL_MILES('N'),
/** Statute miles - used for distance, and for speed (as miles per hour/mph) */
STATUTE_MILES('S');
private char ch;
private Units(char c) {
ch = c;
}
/**
* Returns the corresponding char constant.
*
* @return Char indicator of enum
*/
public char toChar() {
return ch;
}
/**
* Get the enum corresponding to specified char.
*
* @param ch Char indicator for unit
* @return Units enum
*/
public static Units valueOf(char ch) {
for (Units u : values()) {
if (u.toChar() == ch) {
return u;
}
}
return valueOf(String.valueOf(ch));
}
}
| ktuukkan/marine-api | src/main/java/net/sf/marineapi/nmea/util/Units.java | 685 | /** Length in feet */ | block_comment | nl | /*
* Units.java
* Copyright (C) 2010 Kimmo Tuukkanen
*
* This file is part of Java Marine API.
* <http://ktuukkan.github.io/marine-api/>
*
* Java Marine API is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Java Marine API 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 Java Marine API. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.marineapi.nmea.util;
/**
* Defines the supported units of measure.
*
* @author Kimmo Tuukkanen
*
*/
public enum Units {
/** Pressure in bars */
BARS('B'),
/** Temperature in degrees Celsius (centigrade) */
CELSIUS('C'),
/** Depth in fathoms */
FATHOMS('F'),
/** Length in feet<SUF>*/
FEET('f'),
/** Distance/pressure in inches */
INCHES('I'),
/** Kilometers - used for distance, and speed (as kilometers per hour) */
KILOMETERS('K'),
/** Length in meter */
METER('M'),
/** Nautical miles - used for distance, and for speed (nautical miles per hour, which are knots) */
NAUTICAL_MILES('N'),
/** Statute miles - used for distance, and for speed (as miles per hour/mph) */
STATUTE_MILES('S');
private char ch;
private Units(char c) {
ch = c;
}
/**
* Returns the corresponding char constant.
*
* @return Char indicator of enum
*/
public char toChar() {
return ch;
}
/**
* Get the enum corresponding to specified char.
*
* @param ch Char indicator for unit
* @return Units enum
*/
public static Units valueOf(char ch) {
for (Units u : values()) {
if (u.toChar() == ch) {
return u;
}
}
return valueOf(String.valueOf(ch));
}
}
| False | 548 | 5 | 639 | 5 | 627 | 5 | 639 | 5 | 719 | 6 | false | false | false | false | false | true |
2,390 | 38292_1 | /*
* Calendula - An assistant for personal medication management.
* Copyright (C) 2014-2018 CiTIUS - University of Santiago de Compostela
*
* Calendula 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 software. If not, see <http://www.gnu.org/licenses/>.
*/
package es.usc.citius.servando.calendula.database;
import android.content.Context;
import com.j256.ormlite.misc.TransactionManager;
import java.util.concurrent.Callable;
import es.usc.citius.servando.calendula.drugdb.model.database.DrugDBModule;
import es.usc.citius.servando.calendula.util.LogUtil;
public class DB {
private static final String TAG = "DB";
// Database name
public static String DB_NAME = "calendula.db";
// initialized flag
public static boolean initialized = false;
// DatabaseManeger reference
private static DatabaseManager<DatabaseHelper> manager;
// SQLite DB Helper
private static DatabaseHelper db;
// Medicines DAO
private static MedicineDao Medicines;
// Routines DAO
private static RoutineDao Routines;
// Schedules DAO
private static ScheduleDao Schedules;
// ScheduleItems DAO
private static ScheduleItemDao ScheduleItems;
// DailyScheduleItem DAO
private static DailyScheduleItemDao DailyScheduleItems;
// Pickups DAO
private static PickupInfoDao Pickups;
// Patients DAO
private static PatientDao Patients;
// Drug DB module
private static DrugDBModule DrugDB;
// Alerts DAO
private static PatientAlertDao PatientAlerts;
// Allergens DAO
private static PatientAllergenDao PatientAllergens;
// Allergy group DAO
private static AllergyGroupDao AllergyGroups;
/**
* Initialize database and DAOs
*/
public synchronized static void init(Context context) {
if (!initialized) {
initialized = true;
manager = new DatabaseManager<>();
db = manager.getHelper(context, DatabaseHelper.class);
db.getReadableDatabase().enableWriteAheadLogging();
Medicines = new MedicineDao(db);
Routines = new RoutineDao(db);
Schedules = new ScheduleDao(db);
ScheduleItems = new ScheduleItemDao(db);
DailyScheduleItems = new DailyScheduleItemDao(db);
Pickups = new PickupInfoDao(db);
Patients = new PatientDao(db);
DrugDB = DrugDBModule.getInstance();
PatientAlerts = new PatientAlertDao(db);
PatientAllergens = new PatientAllergenDao(db);
AllergyGroups = new AllergyGroupDao(db);
LogUtil.v(TAG, "DB initialized " + DB.DB_NAME);
}
}
/**
* Dispose DB and DAOs
*/
public synchronized static void dispose() {
initialized = false;
db.close();
manager.releaseHelper(db);
LogUtil.v(TAG, "DB disposed");
}
public static DatabaseHelper helper() {
return db;
}
public static Object transaction(Callable<?> callable) {
try {
return TransactionManager.callInTransaction(db.getConnectionSource(), callable);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static MedicineDao medicines() {
return Medicines;
}
public static RoutineDao routines() {
return Routines;
}
public static ScheduleDao schedules() {
return Schedules;
}
public static ScheduleItemDao scheduleItems() {
return ScheduleItems;
}
public static DailyScheduleItemDao dailyScheduleItems() {
return DailyScheduleItems;
}
public static PickupInfoDao pickups() {
return Pickups;
}
public static PatientDao patients() {
return Patients;
}
public static DrugDBModule drugDB() {
return DrugDB;
}
public static PatientAlertDao alerts() {
return PatientAlerts;
}
public static PatientAllergenDao patientAllergens() {
return PatientAllergens;
}
public static AllergyGroupDao allergyGroups() {
return AllergyGroups;
}
public static void dropAndCreateDatabase() {
db.dropAndCreateAllTables();
}
}
| citiususc/calendula | Calendula/src/main/java/es/usc/citius/servando/calendula/database/DB.java | 1,322 | // SQLite DB Helper | line_comment | nl | /*
* Calendula - An assistant for personal medication management.
* Copyright (C) 2014-2018 CiTIUS - University of Santiago de Compostela
*
* Calendula 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 software. If not, see <http://www.gnu.org/licenses/>.
*/
package es.usc.citius.servando.calendula.database;
import android.content.Context;
import com.j256.ormlite.misc.TransactionManager;
import java.util.concurrent.Callable;
import es.usc.citius.servando.calendula.drugdb.model.database.DrugDBModule;
import es.usc.citius.servando.calendula.util.LogUtil;
public class DB {
private static final String TAG = "DB";
// Database name
public static String DB_NAME = "calendula.db";
// initialized flag
public static boolean initialized = false;
// DatabaseManeger reference
private static DatabaseManager<DatabaseHelper> manager;
// SQLite DB<SUF>
private static DatabaseHelper db;
// Medicines DAO
private static MedicineDao Medicines;
// Routines DAO
private static RoutineDao Routines;
// Schedules DAO
private static ScheduleDao Schedules;
// ScheduleItems DAO
private static ScheduleItemDao ScheduleItems;
// DailyScheduleItem DAO
private static DailyScheduleItemDao DailyScheduleItems;
// Pickups DAO
private static PickupInfoDao Pickups;
// Patients DAO
private static PatientDao Patients;
// Drug DB module
private static DrugDBModule DrugDB;
// Alerts DAO
private static PatientAlertDao PatientAlerts;
// Allergens DAO
private static PatientAllergenDao PatientAllergens;
// Allergy group DAO
private static AllergyGroupDao AllergyGroups;
/**
* Initialize database and DAOs
*/
public synchronized static void init(Context context) {
if (!initialized) {
initialized = true;
manager = new DatabaseManager<>();
db = manager.getHelper(context, DatabaseHelper.class);
db.getReadableDatabase().enableWriteAheadLogging();
Medicines = new MedicineDao(db);
Routines = new RoutineDao(db);
Schedules = new ScheduleDao(db);
ScheduleItems = new ScheduleItemDao(db);
DailyScheduleItems = new DailyScheduleItemDao(db);
Pickups = new PickupInfoDao(db);
Patients = new PatientDao(db);
DrugDB = DrugDBModule.getInstance();
PatientAlerts = new PatientAlertDao(db);
PatientAllergens = new PatientAllergenDao(db);
AllergyGroups = new AllergyGroupDao(db);
LogUtil.v(TAG, "DB initialized " + DB.DB_NAME);
}
}
/**
* Dispose DB and DAOs
*/
public synchronized static void dispose() {
initialized = false;
db.close();
manager.releaseHelper(db);
LogUtil.v(TAG, "DB disposed");
}
public static DatabaseHelper helper() {
return db;
}
public static Object transaction(Callable<?> callable) {
try {
return TransactionManager.callInTransaction(db.getConnectionSource(), callable);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static MedicineDao medicines() {
return Medicines;
}
public static RoutineDao routines() {
return Routines;
}
public static ScheduleDao schedules() {
return Schedules;
}
public static ScheduleItemDao scheduleItems() {
return ScheduleItems;
}
public static DailyScheduleItemDao dailyScheduleItems() {
return DailyScheduleItems;
}
public static PickupInfoDao pickups() {
return Pickups;
}
public static PatientDao patients() {
return Patients;
}
public static DrugDBModule drugDB() {
return DrugDB;
}
public static PatientAlertDao alerts() {
return PatientAlerts;
}
public static PatientAllergenDao patientAllergens() {
return PatientAllergens;
}
public static AllergyGroupDao allergyGroups() {
return AllergyGroups;
}
public static void dropAndCreateDatabase() {
db.dropAndCreateAllTables();
}
}
| False | 1,027 | 4 | 1,121 | 4 | 1,161 | 4 | 1,121 | 4 | 1,389 | 5 | false | false | false | false | false | true |
3,816 | 31941_5 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Magazijn;
import java.util.ArrayList;
import magazijnapplicatie.IFactuur;
import magazijnapplicatie.IFactuurRegel;
/**
*
* @author Rob Maas
*/
public class Factuur implements IFactuur{
/**
* De datum van het factuur.
*/
private String datum;
/**
* Het ID van de klant.
*/
private int klantId;
/**
* Het ID van de factuur.
*/
private int factuurId;
/**
* De lijst met IFactuurRegel-objecten (bevat Onderdeel + aantal).
*/
private ArrayList<IFactuurRegel> onderdelen;
/**
* Nieuw Factuur-object met ingevoerde waardes.
* @param datum De datum van de factuur.
* @param klantId Het ID van de klant.
* @param factuurId Het ID van de factuur.
* @param onderdelen Lijst met IFactuurRegel objecten die bij de factuur horen.
*/
public Factuur(String datum, int klantId, int factuurId, ArrayList<IFactuurRegel> onderdelen){
this.datum = datum;
this.klantId = klantId;
this.factuurId = factuurId;
if(onderdelen != null)
{
this.onderdelen = onderdelen;
}
else
{
this.onderdelen = new ArrayList<IFactuurRegel>();
}
}
/**
* Geeft de datum van de factuur.
* @return De datum van de factuur.
*/
public String getDatum(){
return this.datum;
}
/**
* Geeft de ID van de klant.
* @return De ID van de klant.
*/
public int getKlantId(){
return this.klantId;
}
/**
* Geeft de ID van de factuur.
* @return De ID van de factuur.
*/
public int getFactuurId(){
return this.factuurId;
}
/**
* Geeft een lijst met IFactuurRegel-objecten.
* @return Lijst met IFactuurRegel-objecten.
*/
public ArrayList<IFactuurRegel> getOnderdelen(){
return this.onderdelen;
}
}
| niekert/AIDaS-PTS-SEI | src/main/java/Magazijn/Factuur.java | 661 | /**
* De lijst met IFactuurRegel-objecten (bevat Onderdeel + aantal).
*/ | block_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Magazijn;
import java.util.ArrayList;
import magazijnapplicatie.IFactuur;
import magazijnapplicatie.IFactuurRegel;
/**
*
* @author Rob Maas
*/
public class Factuur implements IFactuur{
/**
* De datum van het factuur.
*/
private String datum;
/**
* Het ID van de klant.
*/
private int klantId;
/**
* Het ID van de factuur.
*/
private int factuurId;
/**
* De lijst met<SUF>*/
private ArrayList<IFactuurRegel> onderdelen;
/**
* Nieuw Factuur-object met ingevoerde waardes.
* @param datum De datum van de factuur.
* @param klantId Het ID van de klant.
* @param factuurId Het ID van de factuur.
* @param onderdelen Lijst met IFactuurRegel objecten die bij de factuur horen.
*/
public Factuur(String datum, int klantId, int factuurId, ArrayList<IFactuurRegel> onderdelen){
this.datum = datum;
this.klantId = klantId;
this.factuurId = factuurId;
if(onderdelen != null)
{
this.onderdelen = onderdelen;
}
else
{
this.onderdelen = new ArrayList<IFactuurRegel>();
}
}
/**
* Geeft de datum van de factuur.
* @return De datum van de factuur.
*/
public String getDatum(){
return this.datum;
}
/**
* Geeft de ID van de klant.
* @return De ID van de klant.
*/
public int getKlantId(){
return this.klantId;
}
/**
* Geeft de ID van de factuur.
* @return De ID van de factuur.
*/
public int getFactuurId(){
return this.factuurId;
}
/**
* Geeft een lijst met IFactuurRegel-objecten.
* @return Lijst met IFactuurRegel-objecten.
*/
public ArrayList<IFactuurRegel> getOnderdelen(){
return this.onderdelen;
}
}
| True | 560 | 26 | 618 | 29 | 595 | 25 | 618 | 29 | 660 | 29 | false | false | false | false | false | true |
1,165 | 208252_4 | /* Copyright (C) 2010 - 2011 Fabian Neundorf, Philip Caroli,
* Maximilian Madlung, Usman Ghani Ahmed, Jeremias Mechler
*
* 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 org.ojim.rmi.server;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class StartNetOjim {
/**
* Klasse verwaltet eine Instanz des Remote Objektes , welches unter einem
* festgelegten Namen über das Netzwerk erreichbar ist
* Netzwerk Objekt wird bei dem lokalen Namendienst registriert, portReg und
* portStub müssen von der lokalen Firewall und der Hardware Firewall
* (Router) freigegeben werden. Bitte Achten Sie auch darauf, dass
* Ports die schon von ihrem Betriebssystem benutzt werden, nicht für ihren Server
* benutzt werden können. Eine Liste mit den Standardports die von ihrem Betriebssystem
* verwendet werden, finden Sie auf http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers.
*
*
* @param portReg Port für die lokale Registry
*
* @param portStub Port für das exportieren des Objekts
*
* @param ip ip Adresse unter welcher der Namendienst erreichbar ist
*/
public void startServer(int portReg,String ip,ImplNetOjim ojimServer){
System.out.println("\n"+"Server wird eingerichtet...");
try {
Registry registry = LocateRegistry.createRegistry(portReg);
//registry.list();
String registryURL = "rmi://"+ip+":" + portReg + "/myServer";
Naming.rebind(registryURL, ojimServer);
System.err.println("Server ist bereit");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
/**
* Beendet die gestartete Registry
*/
public void endRegistry(ImplNetOjim ojimServer){
try {
Registry registry = LocateRegistry.getRegistry();
registry.unbind("myServer");
UnicastRemoteObject.unexportObject(ojimServer, true);
UnicastRemoteObject.unexportObject(registry, true);
registry = null;
} catch (RemoteException e) {
System.out.println("Es wurde keine Registry gestartet!");
} catch (NotBoundException e) {
System.out.println("Es ist kein Objekt in der Registry registriert,"+"\n"+
"somit kann auch kein Remote Objekt von der Registry abgemeldet werden!");
}
}
}
| N0T3P4D/PSE | src/org/ojim/rmi/server/StartNetOjim.java | 1,006 | /**
* Beendet die gestartete Registry
*/ | block_comment | nl | /* Copyright (C) 2010 - 2011 Fabian Neundorf, Philip Caroli,
* Maximilian Madlung, Usman Ghani Ahmed, Jeremias Mechler
*
* 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 org.ojim.rmi.server;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class StartNetOjim {
/**
* Klasse verwaltet eine Instanz des Remote Objektes , welches unter einem
* festgelegten Namen über das Netzwerk erreichbar ist
* Netzwerk Objekt wird bei dem lokalen Namendienst registriert, portReg und
* portStub müssen von der lokalen Firewall und der Hardware Firewall
* (Router) freigegeben werden. Bitte Achten Sie auch darauf, dass
* Ports die schon von ihrem Betriebssystem benutzt werden, nicht für ihren Server
* benutzt werden können. Eine Liste mit den Standardports die von ihrem Betriebssystem
* verwendet werden, finden Sie auf http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers.
*
*
* @param portReg Port für die lokale Registry
*
* @param portStub Port für das exportieren des Objekts
*
* @param ip ip Adresse unter welcher der Namendienst erreichbar ist
*/
public void startServer(int portReg,String ip,ImplNetOjim ojimServer){
System.out.println("\n"+"Server wird eingerichtet...");
try {
Registry registry = LocateRegistry.createRegistry(portReg);
//registry.list();
String registryURL = "rmi://"+ip+":" + portReg + "/myServer";
Naming.rebind(registryURL, ojimServer);
System.err.println("Server ist bereit");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
/**
* Beendet die gestartete<SUF>*/
public void endRegistry(ImplNetOjim ojimServer){
try {
Registry registry = LocateRegistry.getRegistry();
registry.unbind("myServer");
UnicastRemoteObject.unexportObject(ojimServer, true);
UnicastRemoteObject.unexportObject(registry, true);
registry = null;
} catch (RemoteException e) {
System.out.println("Es wurde keine Registry gestartet!");
} catch (NotBoundException e) {
System.out.println("Es ist kein Objekt in der Registry registriert,"+"\n"+
"somit kann auch kein Remote Objekt von der Registry abgemeldet werden!");
}
}
}
| False | 791 | 13 | 885 | 12 | 881 | 14 | 885 | 12 | 1,057 | 15 | false | false | false | false | false | true |
123 | 22204_0 | import java.util.ArrayList;
import java.util.List;
public class Person {
private final String name; // Final niet in de NOVI-uitwerkingen. Alleen een setter.
private String middleName; // Deze kan waarschijnlijk niet op final omdat deze niet in de eerste constructor staat als parameter
private final String lastName;
private int age;
private char sex;
private Person mother;
private Person father;
private List<Person> siblings; // Niet doen: = new ArrayList<>();! Maar in de method.
private List<Person> children;
private List<Pet> pets;
// List<Pet> pets = new ArrayList<>(); Geeft een dubbele pet: waarom? getPets(): [Pet@4eec7777, Pet@4eec7777, Pet@3b07d329]
public Person(String name, String lastName, int age, char sex) {
this.name = name;
this.lastName = lastName;
this.age = age;
this.sex = sex;
}
public Person(String name, String middleName, String lastName, int age, char sex) {
this.name = name;
this.middleName = middleName;
this.lastName = lastName;
this.age = age;
this.sex = sex;
}
// Getters & Setters
// Geen print/sout in getters/setters, maar een return!
public String getName() {
return name;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
public char getSex() {
return sex;
}
public int getAge() {
return age;
}
public Person getMother() {
return mother;
}
public Person getFather() {
return father;
}
public List<Person> getSiblings() {
return siblings;
}
public List<Person> getChildren() {
return children;
}
public List<Pet> getPets() { // Geeft: [Pet@3b07d329, Pet@41629346], tenzij je toString @Override in Pet.java
return pets;
}
public void setAge(int age) {
this.age = age;
}
public void setSex(char sex) {
this.sex = sex;
}
public void setMother(Person mother) {
this.mother = mother;
}
public void setFather(Person father) {
this.father = father;
}
public void setSiblings(List<Person> siblings) {
this.siblings = siblings;
}
// ja
public void setChildren(List<Person> children) {
this.children = children;
}
// ja
public void setPets(List<Pet> pets) {
this.pets = pets;
}
// Methods
// Met alleen een father en mother parameter, zie je niet wie het kind is.
// addChild() bestaat niet, omdat het niet aangeeft wie de vader is.
public void addParents(Person father, Person mother, Person child) {
child.setMother(mother);
child.setFather(father);
// ?
mother.addChildToChildren(mother, child);
father.addChildToChildren(father, child);
}
// Hoe deze method opvatten?!
public void addChildToChildren(Person parent, Person child) {
List<Person> kids = new ArrayList<>();
if (parent.getChildren() != null) {
kids.addAll(parent.getChildren());
}
kids.add(child);
parent.setChildren(kids);
}
// Steeds een null of niet gelijk aan null check
// https://youtu.be/lm72_HCd17s?si=KF6wkEMwfPGUCEqc (Coding with John, Null Pointer Exceptions In Java - What EXACTLY They Are and How to Fix Them)
public void addPet(Person person, Pet pet) { // Herschrijven met een Optional?
List<Pet> pets = new ArrayList<>(); // Waarom hier en niet als attribuut? Als field/attribuut geeft het dubbele pet terug. 2x Pablo.
if (person.getPets() != null) { // null = De persoon heeft geen huisdieren. Null geeft Exception error: Cannot invoke iterator
pets.addAll(person.getPets()); // Alleen als een persoon een huisdier of huisdieren heeft, voeg deze dan toe aan de lijst
}
pets.add(pet); // Voeg een huisdier toe aan de lijst pets
person.setPets(pets); // Ken de lijst toe aan een persoon als de eigenaar
}
public void addSibling(Person person, Person sibling) {
List<Person> family = new ArrayList<>();
if (person.getSiblings() != null) {
for (Person people : person.getSiblings()) {
family.add(people);
}
}
family.add(sibling);
person.setSiblings(family);
}
public List<Person> getGrandChildren(Person person) {
List<Person> grandChildren = new ArrayList<>();
if (person.getChildren() != null) {
for (Person children : person.getChildren()) {
if (children.getChildren() != null) {
for (Person grandKid : children.getChildren()) {
grandChildren.add(grandKid);
}
}
}
}
return grandChildren;
}
}
// public void printPets() {
// System.out.println(this.name + " has the following pets:");
// for (Pet pet : pets) {
// System.out.println("- " + pet.getName());
// }
// } | Aphelion-im/backend-java-family-tree-opdracht | src/main/java/Person.java | 1,513 | // Final niet in de NOVI-uitwerkingen. Alleen een setter. | line_comment | nl | import java.util.ArrayList;
import java.util.List;
public class Person {
private final String name; // Final niet<SUF>
private String middleName; // Deze kan waarschijnlijk niet op final omdat deze niet in de eerste constructor staat als parameter
private final String lastName;
private int age;
private char sex;
private Person mother;
private Person father;
private List<Person> siblings; // Niet doen: = new ArrayList<>();! Maar in de method.
private List<Person> children;
private List<Pet> pets;
// List<Pet> pets = new ArrayList<>(); Geeft een dubbele pet: waarom? getPets(): [Pet@4eec7777, Pet@4eec7777, Pet@3b07d329]
public Person(String name, String lastName, int age, char sex) {
this.name = name;
this.lastName = lastName;
this.age = age;
this.sex = sex;
}
public Person(String name, String middleName, String lastName, int age, char sex) {
this.name = name;
this.middleName = middleName;
this.lastName = lastName;
this.age = age;
this.sex = sex;
}
// Getters & Setters
// Geen print/sout in getters/setters, maar een return!
public String getName() {
return name;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
public char getSex() {
return sex;
}
public int getAge() {
return age;
}
public Person getMother() {
return mother;
}
public Person getFather() {
return father;
}
public List<Person> getSiblings() {
return siblings;
}
public List<Person> getChildren() {
return children;
}
public List<Pet> getPets() { // Geeft: [Pet@3b07d329, Pet@41629346], tenzij je toString @Override in Pet.java
return pets;
}
public void setAge(int age) {
this.age = age;
}
public void setSex(char sex) {
this.sex = sex;
}
public void setMother(Person mother) {
this.mother = mother;
}
public void setFather(Person father) {
this.father = father;
}
public void setSiblings(List<Person> siblings) {
this.siblings = siblings;
}
// ja
public void setChildren(List<Person> children) {
this.children = children;
}
// ja
public void setPets(List<Pet> pets) {
this.pets = pets;
}
// Methods
// Met alleen een father en mother parameter, zie je niet wie het kind is.
// addChild() bestaat niet, omdat het niet aangeeft wie de vader is.
public void addParents(Person father, Person mother, Person child) {
child.setMother(mother);
child.setFather(father);
// ?
mother.addChildToChildren(mother, child);
father.addChildToChildren(father, child);
}
// Hoe deze method opvatten?!
public void addChildToChildren(Person parent, Person child) {
List<Person> kids = new ArrayList<>();
if (parent.getChildren() != null) {
kids.addAll(parent.getChildren());
}
kids.add(child);
parent.setChildren(kids);
}
// Steeds een null of niet gelijk aan null check
// https://youtu.be/lm72_HCd17s?si=KF6wkEMwfPGUCEqc (Coding with John, Null Pointer Exceptions In Java - What EXACTLY They Are and How to Fix Them)
public void addPet(Person person, Pet pet) { // Herschrijven met een Optional?
List<Pet> pets = new ArrayList<>(); // Waarom hier en niet als attribuut? Als field/attribuut geeft het dubbele pet terug. 2x Pablo.
if (person.getPets() != null) { // null = De persoon heeft geen huisdieren. Null geeft Exception error: Cannot invoke iterator
pets.addAll(person.getPets()); // Alleen als een persoon een huisdier of huisdieren heeft, voeg deze dan toe aan de lijst
}
pets.add(pet); // Voeg een huisdier toe aan de lijst pets
person.setPets(pets); // Ken de lijst toe aan een persoon als de eigenaar
}
public void addSibling(Person person, Person sibling) {
List<Person> family = new ArrayList<>();
if (person.getSiblings() != null) {
for (Person people : person.getSiblings()) {
family.add(people);
}
}
family.add(sibling);
person.setSiblings(family);
}
public List<Person> getGrandChildren(Person person) {
List<Person> grandChildren = new ArrayList<>();
if (person.getChildren() != null) {
for (Person children : person.getChildren()) {
if (children.getChildren() != null) {
for (Person grandKid : children.getChildren()) {
grandChildren.add(grandKid);
}
}
}
}
return grandChildren;
}
}
// public void printPets() {
// System.out.println(this.name + " has the following pets:");
// for (Pet pet : pets) {
// System.out.println("- " + pet.getName());
// }
// } | True | 1,225 | 18 | 1,365 | 18 | 1,396 | 17 | 1,365 | 18 | 1,577 | 18 | false | false | false | false | false | true |
4,007 | 24062_1 | /*
* Copyright 2007-2008, Plutext Pty Ltd.
*
* This file is part of docx4j.
docx4j is 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 org.docx4j.dml;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ST_PresetPatternVal.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="ST_PresetPatternVal">
* <restriction base="{http://www.w3.org/2001/XMLSchema}token">
* <enumeration value="pct5"/>
* <enumeration value="pct10"/>
* <enumeration value="pct20"/>
* <enumeration value="pct25"/>
* <enumeration value="pct30"/>
* <enumeration value="pct40"/>
* <enumeration value="pct50"/>
* <enumeration value="pct60"/>
* <enumeration value="pct70"/>
* <enumeration value="pct75"/>
* <enumeration value="pct80"/>
* <enumeration value="pct90"/>
* <enumeration value="horz"/>
* <enumeration value="vert"/>
* <enumeration value="ltHorz"/>
* <enumeration value="ltVert"/>
* <enumeration value="dkHorz"/>
* <enumeration value="dkVert"/>
* <enumeration value="narHorz"/>
* <enumeration value="narVert"/>
* <enumeration value="dashHorz"/>
* <enumeration value="dashVert"/>
* <enumeration value="cross"/>
* <enumeration value="dnDiag"/>
* <enumeration value="upDiag"/>
* <enumeration value="ltDnDiag"/>
* <enumeration value="ltUpDiag"/>
* <enumeration value="dkDnDiag"/>
* <enumeration value="dkUpDiag"/>
* <enumeration value="wdDnDiag"/>
* <enumeration value="wdUpDiag"/>
* <enumeration value="dashDnDiag"/>
* <enumeration value="dashUpDiag"/>
* <enumeration value="diagCross"/>
* <enumeration value="smCheck"/>
* <enumeration value="lgCheck"/>
* <enumeration value="smGrid"/>
* <enumeration value="lgGrid"/>
* <enumeration value="dotGrid"/>
* <enumeration value="smConfetti"/>
* <enumeration value="lgConfetti"/>
* <enumeration value="horzBrick"/>
* <enumeration value="diagBrick"/>
* <enumeration value="solidDmnd"/>
* <enumeration value="openDmnd"/>
* <enumeration value="dotDmnd"/>
* <enumeration value="plaid"/>
* <enumeration value="sphere"/>
* <enumeration value="weave"/>
* <enumeration value="divot"/>
* <enumeration value="shingle"/>
* <enumeration value="wave"/>
* <enumeration value="trellis"/>
* <enumeration value="zigZag"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "ST_PresetPatternVal")
@XmlEnum
public enum STPresetPatternVal {
/**
* 5%
*
*/
@XmlEnumValue("pct5")
PCT_5("pct5"),
/**
* 10%
*
*/
@XmlEnumValue("pct10")
PCT_10("pct10"),
/**
* 20%
*
*/
@XmlEnumValue("pct20")
PCT_20("pct20"),
/**
* 25%
*
*/
@XmlEnumValue("pct25")
PCT_25("pct25"),
/**
* 30%
*
*/
@XmlEnumValue("pct30")
PCT_30("pct30"),
/**
* 40%
*
*/
@XmlEnumValue("pct40")
PCT_40("pct40"),
/**
* 50%
*
*/
@XmlEnumValue("pct50")
PCT_50("pct50"),
/**
* 60%
*
*/
@XmlEnumValue("pct60")
PCT_60("pct60"),
/**
* 70%
*
*/
@XmlEnumValue("pct70")
PCT_70("pct70"),
/**
* 75%
*
*/
@XmlEnumValue("pct75")
PCT_75("pct75"),
/**
* 80%
*
*/
@XmlEnumValue("pct80")
PCT_80("pct80"),
/**
* 90%
*
*/
@XmlEnumValue("pct90")
PCT_90("pct90"),
/**
* Horizontal
*
*/
@XmlEnumValue("horz")
HORZ("horz"),
/**
* Vertical
*
*/
@XmlEnumValue("vert")
VERT("vert"),
/**
* Light Horizontal
*
*/
@XmlEnumValue("ltHorz")
LT_HORZ("ltHorz"),
/**
* Light Vertical
*
*/
@XmlEnumValue("ltVert")
LT_VERT("ltVert"),
/**
* Dark Horizontal
*
*/
@XmlEnumValue("dkHorz")
DK_HORZ("dkHorz"),
/**
* Dark Vertical
*
*/
@XmlEnumValue("dkVert")
DK_VERT("dkVert"),
/**
* Narrow Horizontal
*
*/
@XmlEnumValue("narHorz")
NAR_HORZ("narHorz"),
/**
* Narrow Vertical
*
*/
@XmlEnumValue("narVert")
NAR_VERT("narVert"),
/**
* Dashed Horizontal
*
*/
@XmlEnumValue("dashHorz")
DASH_HORZ("dashHorz"),
/**
* Dashed Vertical
*
*/
@XmlEnumValue("dashVert")
DASH_VERT("dashVert"),
/**
* Cross
*
*/
@XmlEnumValue("cross")
CROSS("cross"),
/**
* Downward Diagonal
*
*/
@XmlEnumValue("dnDiag")
DN_DIAG("dnDiag"),
/**
* Upward Diagonal
*
*/
@XmlEnumValue("upDiag")
UP_DIAG("upDiag"),
/**
* Light Downward Diagonal
*
*/
@XmlEnumValue("ltDnDiag")
LT_DN_DIAG("ltDnDiag"),
/**
* Light Upward Diagonal
*
*/
@XmlEnumValue("ltUpDiag")
LT_UP_DIAG("ltUpDiag"),
/**
* Dark Downward Diagonal
*
*/
@XmlEnumValue("dkDnDiag")
DK_DN_DIAG("dkDnDiag"),
/**
* Dark Upward Diagonal
*
*/
@XmlEnumValue("dkUpDiag")
DK_UP_DIAG("dkUpDiag"),
/**
* Wide Downward Diagonal
*
*/
@XmlEnumValue("wdDnDiag")
WD_DN_DIAG("wdDnDiag"),
/**
* Wide Upward Diagonal
*
*/
@XmlEnumValue("wdUpDiag")
WD_UP_DIAG("wdUpDiag"),
/**
* Dashed Downward Diagonal
*
*/
@XmlEnumValue("dashDnDiag")
DASH_DN_DIAG("dashDnDiag"),
/**
* Dashed Upward DIagonal
*
*/
@XmlEnumValue("dashUpDiag")
DASH_UP_DIAG("dashUpDiag"),
/**
* Diagonal Cross
*
*/
@XmlEnumValue("diagCross")
DIAG_CROSS("diagCross"),
/**
* Small Checker Board
*
*/
@XmlEnumValue("smCheck")
SM_CHECK("smCheck"),
/**
* Large Checker Board
*
*/
@XmlEnumValue("lgCheck")
LG_CHECK("lgCheck"),
/**
* Small Grid
*
*/
@XmlEnumValue("smGrid")
SM_GRID("smGrid"),
/**
* Large Grid
*
*/
@XmlEnumValue("lgGrid")
LG_GRID("lgGrid"),
/**
* Dotted Grid
*
*/
@XmlEnumValue("dotGrid")
DOT_GRID("dotGrid"),
/**
* Small Confetti
*
*/
@XmlEnumValue("smConfetti")
SM_CONFETTI("smConfetti"),
/**
* Large Confetti
*
*/
@XmlEnumValue("lgConfetti")
LG_CONFETTI("lgConfetti"),
/**
* Horizontal Brick
*
*/
@XmlEnumValue("horzBrick")
HORZ_BRICK("horzBrick"),
/**
* Diagonal Brick
*
*/
@XmlEnumValue("diagBrick")
DIAG_BRICK("diagBrick"),
/**
* Solid Diamond
*
*/
@XmlEnumValue("solidDmnd")
SOLID_DMND("solidDmnd"),
/**
* Open Diamond
*
*/
@XmlEnumValue("openDmnd")
OPEN_DMND("openDmnd"),
/**
* Dotted Diamond
*
*/
@XmlEnumValue("dotDmnd")
DOT_DMND("dotDmnd"),
/**
* Plaid
*
*/
@XmlEnumValue("plaid")
PLAID("plaid"),
/**
* Sphere
*
*/
@XmlEnumValue("sphere")
SPHERE("sphere"),
/**
* Weave
*
*/
@XmlEnumValue("weave")
WEAVE("weave"),
/**
* Divot
*
*/
@XmlEnumValue("divot")
DIVOT("divot"),
/**
* Shingle
*
*/
@XmlEnumValue("shingle")
SHINGLE("shingle"),
/**
* Wave
*
*/
@XmlEnumValue("wave")
WAVE("wave"),
/**
* Trellis
*
*/
@XmlEnumValue("trellis")
TRELLIS("trellis"),
/**
* Zig Zag
*
*/
@XmlEnumValue("zigZag")
ZIG_ZAG("zigZag");
private final String value;
STPresetPatternVal(String v) {
value = v;
}
public String value() {
return value;
}
public static STPresetPatternVal fromValue(String v) {
for (STPresetPatternVal c: STPresetPatternVal.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
| plutext/docx4j | docx4j-openxml-objects/src/main/java/org/docx4j/dml/STPresetPatternVal.java | 3,567 | /**
* <p>Java class for ST_PresetPatternVal.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="ST_PresetPatternVal">
* <restriction base="{http://www.w3.org/2001/XMLSchema}token">
* <enumeration value="pct5"/>
* <enumeration value="pct10"/>
* <enumeration value="pct20"/>
* <enumeration value="pct25"/>
* <enumeration value="pct30"/>
* <enumeration value="pct40"/>
* <enumeration value="pct50"/>
* <enumeration value="pct60"/>
* <enumeration value="pct70"/>
* <enumeration value="pct75"/>
* <enumeration value="pct80"/>
* <enumeration value="pct90"/>
* <enumeration value="horz"/>
* <enumeration value="vert"/>
* <enumeration value="ltHorz"/>
* <enumeration value="ltVert"/>
* <enumeration value="dkHorz"/>
* <enumeration value="dkVert"/>
* <enumeration value="narHorz"/>
* <enumeration value="narVert"/>
* <enumeration value="dashHorz"/>
* <enumeration value="dashVert"/>
* <enumeration value="cross"/>
* <enumeration value="dnDiag"/>
* <enumeration value="upDiag"/>
* <enumeration value="ltDnDiag"/>
* <enumeration value="ltUpDiag"/>
* <enumeration value="dkDnDiag"/>
* <enumeration value="dkUpDiag"/>
* <enumeration value="wdDnDiag"/>
* <enumeration value="wdUpDiag"/>
* <enumeration value="dashDnDiag"/>
* <enumeration value="dashUpDiag"/>
* <enumeration value="diagCross"/>
* <enumeration value="smCheck"/>
* <enumeration value="lgCheck"/>
* <enumeration value="smGrid"/>
* <enumeration value="lgGrid"/>
* <enumeration value="dotGrid"/>
* <enumeration value="smConfetti"/>
* <enumeration value="lgConfetti"/>
* <enumeration value="horzBrick"/>
* <enumeration value="diagBrick"/>
* <enumeration value="solidDmnd"/>
* <enumeration value="openDmnd"/>
* <enumeration value="dotDmnd"/>
* <enumeration value="plaid"/>
* <enumeration value="sphere"/>
* <enumeration value="weave"/>
* <enumeration value="divot"/>
* <enumeration value="shingle"/>
* <enumeration value="wave"/>
* <enumeration value="trellis"/>
* <enumeration value="zigZag"/>
* </restriction>
* </simpleType>
* </pre>
*
*/ | block_comment | nl | /*
* Copyright 2007-2008, Plutext Pty Ltd.
*
* This file is part of docx4j.
docx4j is 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 org.docx4j.dml;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for<SUF>*/
@XmlType(name = "ST_PresetPatternVal")
@XmlEnum
public enum STPresetPatternVal {
/**
* 5%
*
*/
@XmlEnumValue("pct5")
PCT_5("pct5"),
/**
* 10%
*
*/
@XmlEnumValue("pct10")
PCT_10("pct10"),
/**
* 20%
*
*/
@XmlEnumValue("pct20")
PCT_20("pct20"),
/**
* 25%
*
*/
@XmlEnumValue("pct25")
PCT_25("pct25"),
/**
* 30%
*
*/
@XmlEnumValue("pct30")
PCT_30("pct30"),
/**
* 40%
*
*/
@XmlEnumValue("pct40")
PCT_40("pct40"),
/**
* 50%
*
*/
@XmlEnumValue("pct50")
PCT_50("pct50"),
/**
* 60%
*
*/
@XmlEnumValue("pct60")
PCT_60("pct60"),
/**
* 70%
*
*/
@XmlEnumValue("pct70")
PCT_70("pct70"),
/**
* 75%
*
*/
@XmlEnumValue("pct75")
PCT_75("pct75"),
/**
* 80%
*
*/
@XmlEnumValue("pct80")
PCT_80("pct80"),
/**
* 90%
*
*/
@XmlEnumValue("pct90")
PCT_90("pct90"),
/**
* Horizontal
*
*/
@XmlEnumValue("horz")
HORZ("horz"),
/**
* Vertical
*
*/
@XmlEnumValue("vert")
VERT("vert"),
/**
* Light Horizontal
*
*/
@XmlEnumValue("ltHorz")
LT_HORZ("ltHorz"),
/**
* Light Vertical
*
*/
@XmlEnumValue("ltVert")
LT_VERT("ltVert"),
/**
* Dark Horizontal
*
*/
@XmlEnumValue("dkHorz")
DK_HORZ("dkHorz"),
/**
* Dark Vertical
*
*/
@XmlEnumValue("dkVert")
DK_VERT("dkVert"),
/**
* Narrow Horizontal
*
*/
@XmlEnumValue("narHorz")
NAR_HORZ("narHorz"),
/**
* Narrow Vertical
*
*/
@XmlEnumValue("narVert")
NAR_VERT("narVert"),
/**
* Dashed Horizontal
*
*/
@XmlEnumValue("dashHorz")
DASH_HORZ("dashHorz"),
/**
* Dashed Vertical
*
*/
@XmlEnumValue("dashVert")
DASH_VERT("dashVert"),
/**
* Cross
*
*/
@XmlEnumValue("cross")
CROSS("cross"),
/**
* Downward Diagonal
*
*/
@XmlEnumValue("dnDiag")
DN_DIAG("dnDiag"),
/**
* Upward Diagonal
*
*/
@XmlEnumValue("upDiag")
UP_DIAG("upDiag"),
/**
* Light Downward Diagonal
*
*/
@XmlEnumValue("ltDnDiag")
LT_DN_DIAG("ltDnDiag"),
/**
* Light Upward Diagonal
*
*/
@XmlEnumValue("ltUpDiag")
LT_UP_DIAG("ltUpDiag"),
/**
* Dark Downward Diagonal
*
*/
@XmlEnumValue("dkDnDiag")
DK_DN_DIAG("dkDnDiag"),
/**
* Dark Upward Diagonal
*
*/
@XmlEnumValue("dkUpDiag")
DK_UP_DIAG("dkUpDiag"),
/**
* Wide Downward Diagonal
*
*/
@XmlEnumValue("wdDnDiag")
WD_DN_DIAG("wdDnDiag"),
/**
* Wide Upward Diagonal
*
*/
@XmlEnumValue("wdUpDiag")
WD_UP_DIAG("wdUpDiag"),
/**
* Dashed Downward Diagonal
*
*/
@XmlEnumValue("dashDnDiag")
DASH_DN_DIAG("dashDnDiag"),
/**
* Dashed Upward DIagonal
*
*/
@XmlEnumValue("dashUpDiag")
DASH_UP_DIAG("dashUpDiag"),
/**
* Diagonal Cross
*
*/
@XmlEnumValue("diagCross")
DIAG_CROSS("diagCross"),
/**
* Small Checker Board
*
*/
@XmlEnumValue("smCheck")
SM_CHECK("smCheck"),
/**
* Large Checker Board
*
*/
@XmlEnumValue("lgCheck")
LG_CHECK("lgCheck"),
/**
* Small Grid
*
*/
@XmlEnumValue("smGrid")
SM_GRID("smGrid"),
/**
* Large Grid
*
*/
@XmlEnumValue("lgGrid")
LG_GRID("lgGrid"),
/**
* Dotted Grid
*
*/
@XmlEnumValue("dotGrid")
DOT_GRID("dotGrid"),
/**
* Small Confetti
*
*/
@XmlEnumValue("smConfetti")
SM_CONFETTI("smConfetti"),
/**
* Large Confetti
*
*/
@XmlEnumValue("lgConfetti")
LG_CONFETTI("lgConfetti"),
/**
* Horizontal Brick
*
*/
@XmlEnumValue("horzBrick")
HORZ_BRICK("horzBrick"),
/**
* Diagonal Brick
*
*/
@XmlEnumValue("diagBrick")
DIAG_BRICK("diagBrick"),
/**
* Solid Diamond
*
*/
@XmlEnumValue("solidDmnd")
SOLID_DMND("solidDmnd"),
/**
* Open Diamond
*
*/
@XmlEnumValue("openDmnd")
OPEN_DMND("openDmnd"),
/**
* Dotted Diamond
*
*/
@XmlEnumValue("dotDmnd")
DOT_DMND("dotDmnd"),
/**
* Plaid
*
*/
@XmlEnumValue("plaid")
PLAID("plaid"),
/**
* Sphere
*
*/
@XmlEnumValue("sphere")
SPHERE("sphere"),
/**
* Weave
*
*/
@XmlEnumValue("weave")
WEAVE("weave"),
/**
* Divot
*
*/
@XmlEnumValue("divot")
DIVOT("divot"),
/**
* Shingle
*
*/
@XmlEnumValue("shingle")
SHINGLE("shingle"),
/**
* Wave
*
*/
@XmlEnumValue("wave")
WAVE("wave"),
/**
* Trellis
*
*/
@XmlEnumValue("trellis")
TRELLIS("trellis"),
/**
* Zig Zag
*
*/
@XmlEnumValue("zigZag")
ZIG_ZAG("zigZag");
private final String value;
STPresetPatternVal(String v) {
value = v;
}
public String value() {
return value;
}
public static STPresetPatternVal fromValue(String v) {
for (STPresetPatternVal c: STPresetPatternVal.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
| False | 3,044 | 972 | 2,907 | 959 | 3,221 | 953 | 2,907 | 959 | 3,764 | 1,114 | true | true | true | true | true | false |
2,316 | 76494_0 | package nl.hva.ict.ds.util;
import nl.hva.ict.ds.Player;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class LinearProbingMultiValueSymbolTable implements MultiValueSymbolTable<String, Player> {
String[] keys;
Player[] values;
int collisions;
int maxSize;
public LinearProbingMultiValueSymbolTable(int arraySize) {
keys = new String[arraySize];
values = new Player[arraySize];
collisions = 0;
maxSize = arraySize;
}
/**
* Berekent de positie voor het in te voegen of op te halen key.
*
* @param key
* @return hash
*/
private int hash(String key) {
return (key.hashCode() & 0x7fffffff) % maxSize;
}
/**
* Plaatst een key met een bijbehoorende value in de tabel. Wanneer er een collision optreedt, wordt de positie
* vergroot met 1. Net zolang totdat er een beschikbare positie gevonden is.
*
* @param key the key to use.
* @param value the value to be stored.
*/
@Override
public void put(String key, Player value) {
int i = hash(key);
while (keys[i] != null) {
i = (i + 1) % maxSize;
collisions++;
}
keys[i] = key;
values[i] = value;
}
/**
* Geeft de lijst met values terug voor gegeven key.
*
* @param key the key for which the values must be returned.
* @return de gevonden values voor de gegeven key.
*/
@Override
public List<Player> get(String key) {
List<Player> foundPlayers = new ArrayList<>();
int i = hash(key);
while (keys[i] != null) {
if (keys[i].equals(key)) {
if (!foundPlayers.contains(values[i])) {
foundPlayers.add(values[i]);
}
}
i = (i + 1) % maxSize;
}
return foundPlayers;
}
/**
* @return totale aantal collisions.
*/
@Override
public int getCollisions() {
return collisions;
}
}
| buracc/Data-Structures | assignment-3/src/main/java/nl/hva/ict/ds/util/LinearProbingMultiValueSymbolTable.java | 642 | /**
* Berekent de positie voor het in te voegen of op te halen key.
*
* @param key
* @return hash
*/ | block_comment | nl | package nl.hva.ict.ds.util;
import nl.hva.ict.ds.Player;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class LinearProbingMultiValueSymbolTable implements MultiValueSymbolTable<String, Player> {
String[] keys;
Player[] values;
int collisions;
int maxSize;
public LinearProbingMultiValueSymbolTable(int arraySize) {
keys = new String[arraySize];
values = new Player[arraySize];
collisions = 0;
maxSize = arraySize;
}
/**
* Berekent de positie<SUF>*/
private int hash(String key) {
return (key.hashCode() & 0x7fffffff) % maxSize;
}
/**
* Plaatst een key met een bijbehoorende value in de tabel. Wanneer er een collision optreedt, wordt de positie
* vergroot met 1. Net zolang totdat er een beschikbare positie gevonden is.
*
* @param key the key to use.
* @param value the value to be stored.
*/
@Override
public void put(String key, Player value) {
int i = hash(key);
while (keys[i] != null) {
i = (i + 1) % maxSize;
collisions++;
}
keys[i] = key;
values[i] = value;
}
/**
* Geeft de lijst met values terug voor gegeven key.
*
* @param key the key for which the values must be returned.
* @return de gevonden values voor de gegeven key.
*/
@Override
public List<Player> get(String key) {
List<Player> foundPlayers = new ArrayList<>();
int i = hash(key);
while (keys[i] != null) {
if (keys[i].equals(key)) {
if (!foundPlayers.contains(values[i])) {
foundPlayers.add(values[i]);
}
}
i = (i + 1) % maxSize;
}
return foundPlayers;
}
/**
* @return totale aantal collisions.
*/
@Override
public int getCollisions() {
return collisions;
}
}
| True | 513 | 38 | 566 | 37 | 606 | 39 | 566 | 37 | 647 | 41 | false | false | false | false | false | true |
304 | 11692_30 | // Mastermind versie 1.0
// author: Caspar Steinebach
import java.util.*; // Import Library
public class Main { // Hoofdklasse
static char[] codeComputer = new char[4];
static char[] codeMens = new char[4];
static String doorgeven = "abcd";
public static void main(String[] args) {
clearScreen();
System.out.println("** MASTERMIND - Caspar Steinebach **");
System.out.println("toets 'q' om het spel te verlaten");
lijstLettersRandom();
while (true) {
lettersKloppen();
checkRun();
}
}
static void clearScreen() {
System.out.flush();
}
static void lijstLettersRandom() { // Deze methode laat de computer een code genereren.
String alfabet = "abcdef"; // Dit zijn de beschikbare letters.
Random r = new Random(); // een nieuwe randomgeneratoer wordt aangemaakt met de naam 'r'.
for (int i = 0; i < 4; i++) { // forloop om een dobbelsteen te gooien.
char willekeur = alfabet.charAt(r.nextInt(6)); // willekeurig karakter uit de string alfabet (uit die 6 karaters) wordt gekozen.
codeComputer[i] = willekeur; // karakters worden in de charArray 'codeComputer' gestopt.
}
//System.out.println(codeComputer);
doorgeven = String.valueOf(codeComputer); // 'codeComputer' wordt omgezet in een string en opgeslagen in de string 'doorgeven'
}
static void lettersKloppen() { //deze methode laat de gebruiker letters intoetsen en slaat ze op in een Array
System.out.println("-------------------------------------");
System.out.println("Voer je code in: 4 letters (a t/m f)");
Scanner scanner = new Scanner(System.in);
String invoer = scanner.nextLine();
if (invoer.equals("q")){ // Als de gebruiker 'q' intoetst dan eindigt het spel
System.out.print("Bedankt en tot ziens!");
System.exit(0);
}
codeMens = invoer.toCharArray(); // De string invoer wordt in losse leters omgezet en in de charArray 'codeMens' gezet. Om later weer te gebruiken als het spel over is. (zie regel 67).
}
static void checkRun() { // deze methode checkt op juiste letters op de juiste plek
int lettersJuistePlek = 0; // Een int wordt aangemaakt die als teller genereert om de gebruiker te laten weten hoeveel letters op de juiste plek staan.
int goedeLettersOnjuistePlek = 0; // Een int wordt aangemaakt die als teller genereert om de gebruiker te laten weten hoeveel letters op de juiste plek staan.
for (int i = 0; i < 4; i++) { // Forloop om door de verschillende lettercombinaties te lopen en te checken of
if (codeComputer[i] == codeMens[i]) { // de combinatie klopt. Als die klopt heeft de speler de code gekraakt.
lettersJuistePlek += 1; // Bij elke goede letter gaat de teller 1 omhoog.
}
}
if (lettersJuistePlek == 4) { // Als de teller op '4' staat dan heeft de speler alle letters goed geraden en
System.out.println("********** Gewonnen! **********"); // is de code gekraakt. Een felicitatie valt de speler ten deel.
System.out.println("De juiste codecombinatie was : " + doorgeven);
System.exit(0); // Het spel is afgelopen en wordt automatisch afgesloten.
}
lettersJuistePlek = 0; // Als niet alle letters goed zijn, dan betekent dat dat de code niet gekraakt is.
// In dat geval wordt de teller weer op '0' gezet en worden de cijfers opnieuw
if (codeComputer[0] == codeMens[0]) { // met elkaar vergeleken. Hier de eerste letter.
lettersJuistePlek += 1; // Teller 'lettersJuistePlek' gaat 1 omhoog als die klopt
} else { // Als de eerste letter niet overeenkomst gaan we kijen of hij vaker voorkomt
for (int i = 0; i < 4; i++) {
if (codeComputer[i] == codeMens[0]) { // hij wordt veregeleken met andere letters
goedeLettersOnjuistePlek += 1; // als die ergens op een andere plek voorkomt dan wordt de teller met 1 verhoogt
}
}
}
if (codeComputer[1] == codeMens[1]) { // Hier de tweede letter.
lettersJuistePlek += 1; // Teller 'lettersJuistePlek' gaat 1 omhoog als die klopt
} else {
for (int i = 0; i < 4; i++) { // Als de eerste letter niet overeenkomst gaan we kijen of hij vaker voorkomt
if (codeComputer[i] == codeMens[1]) {
goedeLettersOnjuistePlek += 1;
}
}
}
if (codeComputer[2] == codeMens[2]) { // Hier de derde letter
lettersJuistePlek += 1; // Teller 'lettersJuistePlek' gaat 1 omhoog als die klopt
} else {
for (int i = 0; i < 4; i++) {
if (codeComputer[i] == codeMens[2]) {
goedeLettersOnjuistePlek += 1;
}
}
}
if (codeComputer[3] == codeMens[3]) { // Hier de vierde letter
lettersJuistePlek += 1; // Teller 'lettersJuistePlek' gaat 1 omhoog als die klopt
} else {
for (int i = 0; i < 4; i++) {
if (codeComputer[i] == codeMens[3]) {
goedeLettersOnjuistePlek += 1;
}
}
}
System.out.println("Aantal letters op de juiste plek: " + lettersJuistePlek); // Een print van hoeveel letters er op de juiste plek staan.
System.out.println("Aantal goede letters op een onjuiste plek: " + goedeLettersOnjuistePlek); // Een print wordt gemaakt van hoeveel letters er voorkomend zijn maar niet op de juiste plek staan.
}
}
/* Mastermind
De opdracht
Programmeer het spel Mastermind tegen de computer, waarbij je gebruik maakt van Object Oriented Programming. Hieronder staat het spelverloop uitgelegd.
Spelverloop
De computer kiest random vier letters uit de verzameling {a, b, c, d, e, f}. De gekozen rij wordt verder “code” genoemd.
De volgorde is van belang; een letter mag vaker voorkomen.
De gebruiker moet de verborgen code proberen te achterhalen.
De gebruiker geeft een code van vier letters op.
De computer geeft een reactie op de ingegeven code, door te antwoorden met:
-> het aantal correcte letters die op de juiste plaats staan
-> het aantal correcte letters dat NIET op de juiste plaats staat
De gebruiker geeft nu een nieuwe code op, gebaseerd op deze nieuwe informatie.
Als alle vier letters op de juiste plaats staan, is de code gekraakt en het spel ten einde.
Een lopend spel kan worden beëindigd door het invoeren van een q; alle andere invoer moet ofwel correct zijn (dus in de verzameling voorkomen), ofwel resulteren in opnieuw bevragen van de gebruiker
*/
| CasparSteinebach/Qien1 | Mastermind/Mastermind.java | 2,181 | // Als de eerste letter niet overeenkomst gaan we kijen of hij vaker voorkomt | line_comment | nl | // Mastermind versie 1.0
// author: Caspar Steinebach
import java.util.*; // Import Library
public class Main { // Hoofdklasse
static char[] codeComputer = new char[4];
static char[] codeMens = new char[4];
static String doorgeven = "abcd";
public static void main(String[] args) {
clearScreen();
System.out.println("** MASTERMIND - Caspar Steinebach **");
System.out.println("toets 'q' om het spel te verlaten");
lijstLettersRandom();
while (true) {
lettersKloppen();
checkRun();
}
}
static void clearScreen() {
System.out.flush();
}
static void lijstLettersRandom() { // Deze methode laat de computer een code genereren.
String alfabet = "abcdef"; // Dit zijn de beschikbare letters.
Random r = new Random(); // een nieuwe randomgeneratoer wordt aangemaakt met de naam 'r'.
for (int i = 0; i < 4; i++) { // forloop om een dobbelsteen te gooien.
char willekeur = alfabet.charAt(r.nextInt(6)); // willekeurig karakter uit de string alfabet (uit die 6 karaters) wordt gekozen.
codeComputer[i] = willekeur; // karakters worden in de charArray 'codeComputer' gestopt.
}
//System.out.println(codeComputer);
doorgeven = String.valueOf(codeComputer); // 'codeComputer' wordt omgezet in een string en opgeslagen in de string 'doorgeven'
}
static void lettersKloppen() { //deze methode laat de gebruiker letters intoetsen en slaat ze op in een Array
System.out.println("-------------------------------------");
System.out.println("Voer je code in: 4 letters (a t/m f)");
Scanner scanner = new Scanner(System.in);
String invoer = scanner.nextLine();
if (invoer.equals("q")){ // Als de gebruiker 'q' intoetst dan eindigt het spel
System.out.print("Bedankt en tot ziens!");
System.exit(0);
}
codeMens = invoer.toCharArray(); // De string invoer wordt in losse leters omgezet en in de charArray 'codeMens' gezet. Om later weer te gebruiken als het spel over is. (zie regel 67).
}
static void checkRun() { // deze methode checkt op juiste letters op de juiste plek
int lettersJuistePlek = 0; // Een int wordt aangemaakt die als teller genereert om de gebruiker te laten weten hoeveel letters op de juiste plek staan.
int goedeLettersOnjuistePlek = 0; // Een int wordt aangemaakt die als teller genereert om de gebruiker te laten weten hoeveel letters op de juiste plek staan.
for (int i = 0; i < 4; i++) { // Forloop om door de verschillende lettercombinaties te lopen en te checken of
if (codeComputer[i] == codeMens[i]) { // de combinatie klopt. Als die klopt heeft de speler de code gekraakt.
lettersJuistePlek += 1; // Bij elke goede letter gaat de teller 1 omhoog.
}
}
if (lettersJuistePlek == 4) { // Als de teller op '4' staat dan heeft de speler alle letters goed geraden en
System.out.println("********** Gewonnen! **********"); // is de code gekraakt. Een felicitatie valt de speler ten deel.
System.out.println("De juiste codecombinatie was : " + doorgeven);
System.exit(0); // Het spel is afgelopen en wordt automatisch afgesloten.
}
lettersJuistePlek = 0; // Als niet alle letters goed zijn, dan betekent dat dat de code niet gekraakt is.
// In dat geval wordt de teller weer op '0' gezet en worden de cijfers opnieuw
if (codeComputer[0] == codeMens[0]) { // met elkaar vergeleken. Hier de eerste letter.
lettersJuistePlek += 1; // Teller 'lettersJuistePlek' gaat 1 omhoog als die klopt
} else { // Als de eerste letter niet overeenkomst gaan we kijen of hij vaker voorkomt
for (int i = 0; i < 4; i++) {
if (codeComputer[i] == codeMens[0]) { // hij wordt veregeleken met andere letters
goedeLettersOnjuistePlek += 1; // als die ergens op een andere plek voorkomt dan wordt de teller met 1 verhoogt
}
}
}
if (codeComputer[1] == codeMens[1]) { // Hier de tweede letter.
lettersJuistePlek += 1; // Teller 'lettersJuistePlek' gaat 1 omhoog als die klopt
} else {
for (int i = 0; i < 4; i++) { // Als de<SUF>
if (codeComputer[i] == codeMens[1]) {
goedeLettersOnjuistePlek += 1;
}
}
}
if (codeComputer[2] == codeMens[2]) { // Hier de derde letter
lettersJuistePlek += 1; // Teller 'lettersJuistePlek' gaat 1 omhoog als die klopt
} else {
for (int i = 0; i < 4; i++) {
if (codeComputer[i] == codeMens[2]) {
goedeLettersOnjuistePlek += 1;
}
}
}
if (codeComputer[3] == codeMens[3]) { // Hier de vierde letter
lettersJuistePlek += 1; // Teller 'lettersJuistePlek' gaat 1 omhoog als die klopt
} else {
for (int i = 0; i < 4; i++) {
if (codeComputer[i] == codeMens[3]) {
goedeLettersOnjuistePlek += 1;
}
}
}
System.out.println("Aantal letters op de juiste plek: " + lettersJuistePlek); // Een print van hoeveel letters er op de juiste plek staan.
System.out.println("Aantal goede letters op een onjuiste plek: " + goedeLettersOnjuistePlek); // Een print wordt gemaakt van hoeveel letters er voorkomend zijn maar niet op de juiste plek staan.
}
}
/* Mastermind
De opdracht
Programmeer het spel Mastermind tegen de computer, waarbij je gebruik maakt van Object Oriented Programming. Hieronder staat het spelverloop uitgelegd.
Spelverloop
De computer kiest random vier letters uit de verzameling {a, b, c, d, e, f}. De gekozen rij wordt verder “code” genoemd.
De volgorde is van belang; een letter mag vaker voorkomen.
De gebruiker moet de verborgen code proberen te achterhalen.
De gebruiker geeft een code van vier letters op.
De computer geeft een reactie op de ingegeven code, door te antwoorden met:
-> het aantal correcte letters die op de juiste plaats staan
-> het aantal correcte letters dat NIET op de juiste plaats staat
De gebruiker geeft nu een nieuwe code op, gebaseerd op deze nieuwe informatie.
Als alle vier letters op de juiste plaats staan, is de code gekraakt en het spel ten einde.
Een lopend spel kan worden beëindigd door het invoeren van een q; alle andere invoer moet ofwel correct zijn (dus in de verzameling voorkomen), ofwel resulteren in opnieuw bevragen van de gebruiker
*/
| True | 1,898 | 23 | 2,049 | 28 | 1,842 | 18 | 2,049 | 28 | 2,191 | 25 | false | false | false | false | false | true |
1,675 | 22477_4 | package domein;
public class Waitress {
private PancakeHouseMenu pancakeHouseMenu;
private DinerMenu dinerMenu;
public Waitress(PancakeHouseMenu pancakeHouseMenu, DinerMenu dinerMenu) {
this.pancakeHouseMenu = pancakeHouseMenu;
this.dinerMenu = dinerMenu;
}
//ZONDER ITERATOR-PATTERN (OOK NIET JAVA INGEBOUWDE ITERATOR)
// public void printMenu() {
// ArrayList<MenuItem> breakfastItems = pancakeHouseMenu.getMenuItems();
// for (int index =0; index<breakfastItems.size(); index++) {
// MenuItem menuItem = breakfastItems.get(index);
// System.out.print(menuItem.getName() + ", ");
// System.out.print(menuItem.getPrice() + " -- ");
// System.out.println(menuItem.getDescription());
// }
// MenuItem[] lunchItems = dinerMenu.getMenuItems();
// for (int index = 0; index<lunchItems.length; index++) {
// MenuItem menuItem = lunchItems[index];
// System.out.print(menuItem.getName() + ", ");
// System.out.print(menuItem.getPrice() + " -- ");
// System.out.println(menuItem.getDescription());
// }
//MET ITERATOR-PATTERN
public void printMenu() {
//TODO creëer iterators voor PancakeHouse ne Objectville Dinner
Iterator dinerMenuIt = dinerMenu.createIterator();
Iterator pancakeHouseMenuIt = pancakeHouseMenu.createIterator();
System.out.println("MENU\n----\nBREAKFAST");
//TODO print menu voor PancakeHouse (gebruik methode printmenu)
printMenu(pancakeHouseMenuIt);
System.out.println("\nLUNCH");
//TODO print menu for Objectville Diner
printMenu(dinerMenuIt);
}
private void printMenu(Iterator iterator) {
//TODO gebruik iterator om de items te doorlopen
while (iterator.hasNext()) {
MenuItem menuItem = (MenuItem) iterator.next();
System.out.print(menuItem.getName() + ", ");
System.out.print(menuItem.getPrice() + " -- ");
System.out.println(
menuItem.getDescription());
}
}
}
| TIData/IteratorTODO | src/domein/Waitress.java | 645 | // MenuItem menuItem = breakfastItems.get(index); | line_comment | nl | package domein;
public class Waitress {
private PancakeHouseMenu pancakeHouseMenu;
private DinerMenu dinerMenu;
public Waitress(PancakeHouseMenu pancakeHouseMenu, DinerMenu dinerMenu) {
this.pancakeHouseMenu = pancakeHouseMenu;
this.dinerMenu = dinerMenu;
}
//ZONDER ITERATOR-PATTERN (OOK NIET JAVA INGEBOUWDE ITERATOR)
// public void printMenu() {
// ArrayList<MenuItem> breakfastItems = pancakeHouseMenu.getMenuItems();
// for (int index =0; index<breakfastItems.size(); index++) {
// MenuItem menuItem<SUF>
// System.out.print(menuItem.getName() + ", ");
// System.out.print(menuItem.getPrice() + " -- ");
// System.out.println(menuItem.getDescription());
// }
// MenuItem[] lunchItems = dinerMenu.getMenuItems();
// for (int index = 0; index<lunchItems.length; index++) {
// MenuItem menuItem = lunchItems[index];
// System.out.print(menuItem.getName() + ", ");
// System.out.print(menuItem.getPrice() + " -- ");
// System.out.println(menuItem.getDescription());
// }
//MET ITERATOR-PATTERN
public void printMenu() {
//TODO creëer iterators voor PancakeHouse ne Objectville Dinner
Iterator dinerMenuIt = dinerMenu.createIterator();
Iterator pancakeHouseMenuIt = pancakeHouseMenu.createIterator();
System.out.println("MENU\n----\nBREAKFAST");
//TODO print menu voor PancakeHouse (gebruik methode printmenu)
printMenu(pancakeHouseMenuIt);
System.out.println("\nLUNCH");
//TODO print menu for Objectville Diner
printMenu(dinerMenuIt);
}
private void printMenu(Iterator iterator) {
//TODO gebruik iterator om de items te doorlopen
while (iterator.hasNext()) {
MenuItem menuItem = (MenuItem) iterator.next();
System.out.print(menuItem.getName() + ", ");
System.out.print(menuItem.getPrice() + " -- ");
System.out.println(
menuItem.getDescription());
}
}
}
| False | 471 | 10 | 567 | 14 | 544 | 12 | 567 | 14 | 659 | 14 | false | false | false | false | false | true |
1,456 | 193546_7 | package io.rtr.alchemy.db.mongo.util;
import com.google.common.collect.AbstractIterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Iterator;
/**
* Ensures that if there's a problem loading an entity that we don't fail loading the rest but
* instead just skip over it
*
* @param <T> The type of thing we're iterating over
*/
public class ExceptionSafeIterator<T> implements Iterator<T> {
private static final Logger LOG = LoggerFactory.getLogger(ExceptionSafeIterator.class);
private final Iterator<T> abstractIterator;
private final Iterator<T> iterator;
private boolean nextCalled;
private ExceptionSafeIterator(final Iterator<T> iterator) {
this.abstractIterator =
new AbstractIterator<T>() {
@Override
protected T computeNext() {
while (iterator.hasNext()) {
try {
return iterator.next();
} catch (final Exception e) {
LOG.error(
"failed to retrieve next item from iterator, skipping item",
e);
}
}
return endOfData();
}
};
this.iterator = iterator;
}
public static <T> ExceptionSafeIterator<T> wrap(final Iterator<T> iterator) {
return new ExceptionSafeIterator<>(iterator);
}
@Override
public boolean hasNext() {
nextCalled = false;
return abstractIterator.hasNext();
}
@Override
public T next() {
nextCalled = true;
return abstractIterator.next();
}
// AbstractIterator<T> doesn't support remove(), because it peeks ahead and can cause ambiguity
// as to which element
// is being removed. Here we make a compromise where assuming that next() has been called after
// a hasNext(), which
// is the most common use case, we can safely call remove()
@Override
public void remove() {
if (!nextCalled) {
// because elements are peeked in advanced, to avoid confusion as to which element is
// being been removed
// one must first call next() after calling hasNext() before being able to call remove()
throw new UnsupportedOperationException(
"cannot remove element until next() has been called after calling hasNext()");
}
iterator.remove();
}
}
| RentTheRunway/alchemy | alchemy-db-mongo/src/main/java/io/rtr/alchemy/db/mongo/util/ExceptionSafeIterator.java | 638 | // being been removed | line_comment | nl | package io.rtr.alchemy.db.mongo.util;
import com.google.common.collect.AbstractIterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Iterator;
/**
* Ensures that if there's a problem loading an entity that we don't fail loading the rest but
* instead just skip over it
*
* @param <T> The type of thing we're iterating over
*/
public class ExceptionSafeIterator<T> implements Iterator<T> {
private static final Logger LOG = LoggerFactory.getLogger(ExceptionSafeIterator.class);
private final Iterator<T> abstractIterator;
private final Iterator<T> iterator;
private boolean nextCalled;
private ExceptionSafeIterator(final Iterator<T> iterator) {
this.abstractIterator =
new AbstractIterator<T>() {
@Override
protected T computeNext() {
while (iterator.hasNext()) {
try {
return iterator.next();
} catch (final Exception e) {
LOG.error(
"failed to retrieve next item from iterator, skipping item",
e);
}
}
return endOfData();
}
};
this.iterator = iterator;
}
public static <T> ExceptionSafeIterator<T> wrap(final Iterator<T> iterator) {
return new ExceptionSafeIterator<>(iterator);
}
@Override
public boolean hasNext() {
nextCalled = false;
return abstractIterator.hasNext();
}
@Override
public T next() {
nextCalled = true;
return abstractIterator.next();
}
// AbstractIterator<T> doesn't support remove(), because it peeks ahead and can cause ambiguity
// as to which element
// is being removed. Here we make a compromise where assuming that next() has been called after
// a hasNext(), which
// is the most common use case, we can safely call remove()
@Override
public void remove() {
if (!nextCalled) {
// because elements are peeked in advanced, to avoid confusion as to which element is
// being been<SUF>
// one must first call next() after calling hasNext() before being able to call remove()
throw new UnsupportedOperationException(
"cannot remove element until next() has been called after calling hasNext()");
}
iterator.remove();
}
}
| False | 474 | 4 | 521 | 4 | 571 | 4 | 521 | 4 | 631 | 4 | false | false | false | false | false | true |
329 | 113506_2 | /*
* Copyright (c) 2018 Cisco and/or its affiliates.
*
* This software is licensed to you under the terms of the Cisco Sample
* Code License, Version 1.0 (the "License"). You may obtain a copy of the
* License at
*
* https://developer.cisco.com/docs/licenses
*
* All use of the material herein must be in accordance with the terms of
* the License. All rights not expressly granted by the License are
* reserved. Unless required by applicable law or agreed to separately 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.
*/
package com.cisco.dnac;
import android.util.Base64;
import android.util.Log;
import java.util.List;
import cisco.com.dnac.v1.api.client.ApiInvoker;
import cisco.com.dnac.v1.api.*;
import api.NetworkDeviceApi;
import model.CountResult;
import model.NetworkDeviceListResult;
import model.NetworkDeviceListResultResponse;
import api.MiscApi;
/* THIS FILE IS RESPONSIBLE FOR ACCESSING THE ACTUAL METHODS IN INTERACTING WITH DNAC */
public class DnacAccessClass {
private String REQUEST_TAG ="DnacAccessClass";
private String cookie = null;
private String username = null;
private String password = null;
private String DnacIPaddress = null;
private ApiInvoker apiInvoker = null;
private MiscApi miscApi = null;
private NetworkDeviceApi networkDeviceApi = null;
private static DnacAccessClass instance = null;
//Device Details parameters
List<String> hostname = null;
List<String> managementIpAddress = null;
List<String> macAddress = null;
List<String> locationName = null;
List<String> serialNumber = null;
List<String> location = null;
List<String> family = null;
List<String> type = null;
List<String> series = null;
List<String> collectionStatus = null;
List<String> collectionInterval = null;
List<String> notSyncedForMinutes = null;
List<String> errorCode = null;
List<String> errorDescription = null;
List<String> softwareVersion = null;
List<String> softwareType = null;
List<String> platformId = null;
List<String> role = null;
List<String> reachabilityStatus = null;
List<String> upTime = null;
List<String> associatedWlcIp = null;
List<String> licenseName = null;
List<String> licenseType = null;
List<String> licenseStatus = null;
List<String> modulename = null;
List<String> moduleequpimenttype = null;
List<String> moduleservicestate = null;
List<String> modulevendorequipmenttype = null;
List<String> modulepartnumber = null;
List<String> moduleoperationstatecode = null;
String id = null;
//
public String getcookie()
{
return cookie;
}
public String getusername()
{
return username;
}
public String getPassword() { return password;}
public String getDnacIPaddress() { return DnacIPaddress; }
public void setCookie(String rawCookie) { cookie = rawCookie; }
public void setUsername(String username_) { username = username_; }
public void setDnacIPaddress(String IpAddress) { DnacIPaddress = IpAddress; }
public void setPassword(String pwd) { password = pwd; }
private DnacAccessClass() {
Log.e(REQUEST_TAG,"DnacAccessClass constructor");
miscApi = new MiscApi();
networkDeviceApi = new NetworkDeviceApi();
}
/* SINGLETON INSTANCE FOR ACCESSING THE DNAC METHODS */
public static DnacAccessClass getInstance() {
if (instance == null) {
synchronized(DnacAccessClass.class) {
if (instance == null) {
instance = new DnacAccessClass();
}
}
}
return instance;
}
/* METHOD TO RETRIEVE THE COUNT FROM DNAC
* networkDeviceApi to be configured for Cookie and Dnac IP Address
* */
public Integer getNetworkDeviceCount_() {
Integer count = 0;
Log.e(REQUEST_TAG,"entering getNetworkDeviceCount_ function ");
networkDeviceApi.addHeader("cookie", cookie);
networkDeviceApi.setBasePath(DnacIPaddress);
try {
CountResult result = networkDeviceApi.getNetworkDeviceCount();
count = result.getResponse();
Log.e(REQUEST_TAG,"result "+count);
}catch (Exception e){
e.printStackTrace();
}
return count;
}
/* METHOD TO FETCH THE AUTH TOKEN FROM DNAC
* miscApi to be configured for DnacIpAddress and Authorization
* */
public String getAuthToken(){
Log.e(REQUEST_TAG,"entering getAuthToken function ");
String credentials = username+":"+password;
String auth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
miscApi.setBasePath(DnacIPaddress);
miscApi.addHeader("Authorization",auth);
try {
return miscApi.postAuthToken(null,auth).getToken();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
/* METHOD TO RETRIEVE THE NETWORK DEVICE LIST FROM DNAC
* networkDeviceApi to be configured for Cookie and Dnac IP Address
* */
public List<NetworkDeviceListResultResponse> getNetworkDeviceAllResponse_(){
Log.e(REQUEST_TAG,"entering getDeviceList function ");
networkDeviceApi.setBasePath(DnacIPaddress);
networkDeviceApi.addHeader("cookie",cookie);
try {
return networkDeviceApi.getNetworkDevice(hostname, managementIpAddress, macAddress, locationName, serialNumber, location, family, type, series, collectionStatus, collectionInterval, notSyncedForMinutes, errorCode, errorDescription, softwareVersion, softwareType, platformId, role, reachabilityStatus, upTime, associatedWlcIp, licenseName, licenseType, licenseStatus, modulename, moduleequpimenttype, moduleservicestate, modulevendorequipmenttype, modulepartnumber, moduleoperationstatecode, id).getResponse();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
/* METHOD TO RETRIEVE THE SPECIFIC DEVICE DETAILS
* networkDeviceApi to be configured for Cookie and Dnac IP Address
* */
public String[] getListViewButtonDetails(){
String[] ButtonDetails =null;
List<NetworkDeviceListResultResponse> networkDeviceAllResponseResponseList;
networkDeviceAllResponseResponseList = getNetworkDeviceAllResponse_();
Log.e(REQUEST_TAG, "entering getListviewButtonDetails function ");
ButtonDetails =new String[networkDeviceAllResponseResponseList.size()];
for (int i = 0; i < networkDeviceAllResponseResponseList.size(); i++) {
ButtonDetails[i] = "MgmtIp - " + networkDeviceAllResponseResponseList.get(i).getManagementIpAddress() + "\n" + "Hostname - " + networkDeviceAllResponseResponseList.get(i).getHostname();
}
return ButtonDetails;
}
}
| CiscoDevNet/DNAC-Android-SDK | sample-app/DNAC-Android-SDK/app/src/main/java/com/cisco/dnac/DnacAccessClass.java | 1,952 | //Device Details parameters | line_comment | nl | /*
* Copyright (c) 2018 Cisco and/or its affiliates.
*
* This software is licensed to you under the terms of the Cisco Sample
* Code License, Version 1.0 (the "License"). You may obtain a copy of the
* License at
*
* https://developer.cisco.com/docs/licenses
*
* All use of the material herein must be in accordance with the terms of
* the License. All rights not expressly granted by the License are
* reserved. Unless required by applicable law or agreed to separately 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.
*/
package com.cisco.dnac;
import android.util.Base64;
import android.util.Log;
import java.util.List;
import cisco.com.dnac.v1.api.client.ApiInvoker;
import cisco.com.dnac.v1.api.*;
import api.NetworkDeviceApi;
import model.CountResult;
import model.NetworkDeviceListResult;
import model.NetworkDeviceListResultResponse;
import api.MiscApi;
/* THIS FILE IS RESPONSIBLE FOR ACCESSING THE ACTUAL METHODS IN INTERACTING WITH DNAC */
public class DnacAccessClass {
private String REQUEST_TAG ="DnacAccessClass";
private String cookie = null;
private String username = null;
private String password = null;
private String DnacIPaddress = null;
private ApiInvoker apiInvoker = null;
private MiscApi miscApi = null;
private NetworkDeviceApi networkDeviceApi = null;
private static DnacAccessClass instance = null;
//Device Details<SUF>
List<String> hostname = null;
List<String> managementIpAddress = null;
List<String> macAddress = null;
List<String> locationName = null;
List<String> serialNumber = null;
List<String> location = null;
List<String> family = null;
List<String> type = null;
List<String> series = null;
List<String> collectionStatus = null;
List<String> collectionInterval = null;
List<String> notSyncedForMinutes = null;
List<String> errorCode = null;
List<String> errorDescription = null;
List<String> softwareVersion = null;
List<String> softwareType = null;
List<String> platformId = null;
List<String> role = null;
List<String> reachabilityStatus = null;
List<String> upTime = null;
List<String> associatedWlcIp = null;
List<String> licenseName = null;
List<String> licenseType = null;
List<String> licenseStatus = null;
List<String> modulename = null;
List<String> moduleequpimenttype = null;
List<String> moduleservicestate = null;
List<String> modulevendorequipmenttype = null;
List<String> modulepartnumber = null;
List<String> moduleoperationstatecode = null;
String id = null;
//
public String getcookie()
{
return cookie;
}
public String getusername()
{
return username;
}
public String getPassword() { return password;}
public String getDnacIPaddress() { return DnacIPaddress; }
public void setCookie(String rawCookie) { cookie = rawCookie; }
public void setUsername(String username_) { username = username_; }
public void setDnacIPaddress(String IpAddress) { DnacIPaddress = IpAddress; }
public void setPassword(String pwd) { password = pwd; }
private DnacAccessClass() {
Log.e(REQUEST_TAG,"DnacAccessClass constructor");
miscApi = new MiscApi();
networkDeviceApi = new NetworkDeviceApi();
}
/* SINGLETON INSTANCE FOR ACCESSING THE DNAC METHODS */
public static DnacAccessClass getInstance() {
if (instance == null) {
synchronized(DnacAccessClass.class) {
if (instance == null) {
instance = new DnacAccessClass();
}
}
}
return instance;
}
/* METHOD TO RETRIEVE THE COUNT FROM DNAC
* networkDeviceApi to be configured for Cookie and Dnac IP Address
* */
public Integer getNetworkDeviceCount_() {
Integer count = 0;
Log.e(REQUEST_TAG,"entering getNetworkDeviceCount_ function ");
networkDeviceApi.addHeader("cookie", cookie);
networkDeviceApi.setBasePath(DnacIPaddress);
try {
CountResult result = networkDeviceApi.getNetworkDeviceCount();
count = result.getResponse();
Log.e(REQUEST_TAG,"result "+count);
}catch (Exception e){
e.printStackTrace();
}
return count;
}
/* METHOD TO FETCH THE AUTH TOKEN FROM DNAC
* miscApi to be configured for DnacIpAddress and Authorization
* */
public String getAuthToken(){
Log.e(REQUEST_TAG,"entering getAuthToken function ");
String credentials = username+":"+password;
String auth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
miscApi.setBasePath(DnacIPaddress);
miscApi.addHeader("Authorization",auth);
try {
return miscApi.postAuthToken(null,auth).getToken();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
/* METHOD TO RETRIEVE THE NETWORK DEVICE LIST FROM DNAC
* networkDeviceApi to be configured for Cookie and Dnac IP Address
* */
public List<NetworkDeviceListResultResponse> getNetworkDeviceAllResponse_(){
Log.e(REQUEST_TAG,"entering getDeviceList function ");
networkDeviceApi.setBasePath(DnacIPaddress);
networkDeviceApi.addHeader("cookie",cookie);
try {
return networkDeviceApi.getNetworkDevice(hostname, managementIpAddress, macAddress, locationName, serialNumber, location, family, type, series, collectionStatus, collectionInterval, notSyncedForMinutes, errorCode, errorDescription, softwareVersion, softwareType, platformId, role, reachabilityStatus, upTime, associatedWlcIp, licenseName, licenseType, licenseStatus, modulename, moduleequpimenttype, moduleservicestate, modulevendorequipmenttype, modulepartnumber, moduleoperationstatecode, id).getResponse();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
/* METHOD TO RETRIEVE THE SPECIFIC DEVICE DETAILS
* networkDeviceApi to be configured for Cookie and Dnac IP Address
* */
public String[] getListViewButtonDetails(){
String[] ButtonDetails =null;
List<NetworkDeviceListResultResponse> networkDeviceAllResponseResponseList;
networkDeviceAllResponseResponseList = getNetworkDeviceAllResponse_();
Log.e(REQUEST_TAG, "entering getListviewButtonDetails function ");
ButtonDetails =new String[networkDeviceAllResponseResponseList.size()];
for (int i = 0; i < networkDeviceAllResponseResponseList.size(); i++) {
ButtonDetails[i] = "MgmtIp - " + networkDeviceAllResponseResponseList.get(i).getManagementIpAddress() + "\n" + "Hostname - " + networkDeviceAllResponseResponseList.get(i).getHostname();
}
return ButtonDetails;
}
}
| False | 1,582 | 4 | 1,693 | 4 | 1,789 | 4 | 1,693 | 4 | 2,018 | 4 | false | false | false | false | false | true |
2,577 | 90371_1 | package de.reutlingen.university.aufgabe3;_x000D_
/**_x000D_
* @author Anastasia Baron_x000D_
* @author Dmitry Petrov_x000D_
* _x000D_
* Jedes Schuhpaar soll in einer eigenen Schachtel untergebracht werden._x000D_
* Um die generische Klasse Box wiederverwenden zu konnen soll eine neue_x000D_
* Klasse ShoeBox erstellt werden, welche von Box erbt. Um zu_x000D_
* verhindern, dass neben Schuhobjekten auch andere Objekte in ShoeBox_x000D_
* abgelegt werden koennen, ist es erforderlich den generischen_x000D_
* Platzhalter der Klasse entsprechend einzuschranken._x000D_
* _x000D_
* @param <T>_x000D_
*/_x000D_
_x000D_
// Nur Shoes koennen abgelegt werden_x000D_
public class ShoeBox<T extends Shoes> extends Box<T> {_x000D_
_x000D_
private T pairShoe;_x000D_
_x000D_
public ShoeBox() {_x000D_
_x000D_
}_x000D_
_x000D_
// hinzufuegen_x000D_
public void addShoes(T pairShoe) {_x000D_
this.pairShoe = pairShoe;_x000D_
}_x000D_
_x000D_
// entfernen_x000D_
public void removePairShoe() {_x000D_
pairShoe = null;_x000D_
}_x000D_
_x000D_
// gibt den Inhalt der Schachtel zurueck_x000D_
public String toString() {_x000D_
return "in diesem Schachtel liegen: " + pairShoe.toString();_x000D_
}_x000D_
}_x000D_
| dmpe/Homeworks2 | Aufgabe4/src/de/reutlingen/university/aufgabe3/ShoeBox.java | 359 | // Nur Shoes koennen abgelegt werden_x000D_ | line_comment | nl | package de.reutlingen.university.aufgabe3;_x000D_
/**_x000D_
* @author Anastasia Baron_x000D_
* @author Dmitry Petrov_x000D_
* _x000D_
* Jedes Schuhpaar soll in einer eigenen Schachtel untergebracht werden._x000D_
* Um die generische Klasse Box wiederverwenden zu konnen soll eine neue_x000D_
* Klasse ShoeBox erstellt werden, welche von Box erbt. Um zu_x000D_
* verhindern, dass neben Schuhobjekten auch andere Objekte in ShoeBox_x000D_
* abgelegt werden koennen, ist es erforderlich den generischen_x000D_
* Platzhalter der Klasse entsprechend einzuschranken._x000D_
* _x000D_
* @param <T>_x000D_
*/_x000D_
_x000D_
// Nur Shoes<SUF>
public class ShoeBox<T extends Shoes> extends Box<T> {_x000D_
_x000D_
private T pairShoe;_x000D_
_x000D_
public ShoeBox() {_x000D_
_x000D_
}_x000D_
_x000D_
// hinzufuegen_x000D_
public void addShoes(T pairShoe) {_x000D_
this.pairShoe = pairShoe;_x000D_
}_x000D_
_x000D_
// entfernen_x000D_
public void removePairShoe() {_x000D_
pairShoe = null;_x000D_
}_x000D_
_x000D_
// gibt den Inhalt der Schachtel zurueck_x000D_
public String toString() {_x000D_
return "in diesem Schachtel liegen: " + pairShoe.toString();_x000D_
}_x000D_
}_x000D_
| False | 513 | 15 | 607 | 20 | 544 | 15 | 607 | 20 | 608 | 17 | false | false | false | false | false | true |