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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,477 | 79324_11 | package framework.database;_x000D_
_x000D_
import java.lang.reflect.Constructor;_x000D_
import java.sql.Connection;_x000D_
import java.sql.Driver;_x000D_
import java.sql.DriverManager;_x000D_
import java.sql.PreparedStatement;_x000D_
import java.sql.ResultSet;_x000D_
import java.sql.ResultSetMetaData;_x000D_
import java.sql.SQLException;_x000D_
import java.util.ArrayList;_x000D_
import java.util.Enumeration;_x000D_
import java.util.HashMap;_x000D_
_x000D_
public class Database {_x000D_
_x000D_
protected Connection conn;_x000D_
protected String connectionUrl;_x000D_
protected String username;_x000D_
protected String password; // TODO: kijken in hoeverre het haalbaar is het wachtwoord hier weg te laten_x000D_
_x000D_
@SuppressWarnings({ "unchecked", "rawtypes" })_x000D_
public Database(String driver, String connectionUrl, String username, String password)_x000D_
{_x000D_
try {_x000D_
// Kijken of de driver bestaat_x000D_
Class DriverClass = Class.forName(driver);_x000D_
_x000D_
Constructor constructorClass = DriverClass.getConstructor();_x000D_
Driver dbDriver = (Driver) constructorClass.newInstance();_x000D_
DriverManager.registerDriver(dbDriver);_x000D_
_x000D_
} catch (Exception e) {_x000D_
// TODO Exception-handling_x000D_
e.printStackTrace();_x000D_
}_x000D_
_x000D_
this.connectionUrl = connectionUrl;_x000D_
this.username = username;_x000D_
this.password = password;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Maakt connectie naar de databank_x000D_
* _x000D_
* @return_x000D_
* @throws SQLException_x000D_
*/_x000D_
public Connection getConnection() throws SQLException_x000D_
{_x000D_
if(this.conn == null || this.conn.isClosed())_x000D_
this.conn = DriverManager.getConnection(connectionUrl,username,password);_x000D_
_x000D_
return this.conn;_x000D_
}_x000D_
_x000D_
public PreparedStatement prepareStatement(String query) throws SQLException_x000D_
{_x000D_
return conn.prepareStatement(query);_x000D_
}_x000D_
_x000D_
public NamedParamStatement namedParamStatement(String query) throws SQLException_x000D_
{_x000D_
return new NamedParamStatement(getConnection(), query);_x000D_
}_x000D_
_x000D_
/**_x000D_
* Geeft alle rows van een result in een handige ArrayList_x000D_
* _x000D_
* @param res_x000D_
* @return_x000D_
* @throws SQLException_x000D_
*/_x000D_
public ArrayList<DatabaseRow> getAllRows(ResultSet res) throws SQLException_x000D_
{_x000D_
ArrayList<DatabaseRow> rows = new ArrayList<DatabaseRow>();_x000D_
_x000D_
// Cursor naar -1 zetten._x000D_
res.beforeFirst();_x000D_
_x000D_
// Kijken of er op index 0 iets zit._x000D_
if(res.next()){_x000D_
// Blijkbaar zijn er rows_x000D_
// Cursor terug naar -1 zetten alle rows aflopen._x000D_
res.beforeFirst();_x000D_
_x000D_
// Pas als we aan de EOL zitten van de resultset stoppen we_x000D_
while(!res.isAfterLast()) {_x000D_
// Row ophalen en toevoegen aan Arraylist_x000D_
DatabaseRow row = this.getRow(res);_x000D_
if(row != null)_x000D_
rows.add(row);_x000D_
}_x000D_
}_x000D_
_x000D_
res.close();_x000D_
_x000D_
return rows;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Haalt de volgende row uit een resultset een geeft dit terug in een Hashmap<Kolomnaam,Object>_x000D_
* _x000D_
* @param res_x000D_
* @return_x000D_
* @throws SQLException_x000D_
*/_x000D_
public DatabaseRow getRow(ResultSet res) throws SQLException_x000D_
{_x000D_
HashMap<String, Object> row = new HashMap<String, Object>();_x000D_
_x000D_
// MetaData is nodig, daarin zit het aantal kolommen en hoe ze heten_x000D_
ResultSetMetaData metaData = res.getMetaData();_x000D_
int columnCount = metaData.getColumnCount();_x000D_
_x000D_
ArrayList<String> columns = new ArrayList<String>();_x000D_
_x000D_
// Alle kolommen aflopen en hun naam bijhouden in de Array._x000D_
for (int columnNr=1; columnNr<=columnCount; columnNr++){_x000D_
String columnName = metaData.getColumnName(columnNr);_x000D_
columns.add(columnName);_x000D_
}_x000D_
_x000D_
// Springen naar de volgende row_x000D_
if (res.next()){_x000D_
// Alle kolommen in deze row aflopen_x000D_
for (String columnName:columns) {_x000D_
// De waarde van deze kolom ophalen_x000D_
Object rowData = res.getObject(columnName);_x000D_
// Toevoegen aan de hashmap_x000D_
row.put(columnName,rowData);_x000D_
}_x000D_
}_x000D_
_x000D_
if(row.size() <= 0)_x000D_
return null;_x000D_
_x000D_
return new DatabaseRow(row);_x000D_
}_x000D_
_x000D_
public void closeConnection() {_x000D_
try {_x000D_
conn.close();_x000D_
_x000D_
// This manually deregisters JDBC driver, which prevents Tomcat 7_x000D_
// from complaining about memory leaks wrto this class_x000D_
// http://stackoverflow.com/a/5315467/1306509_x000D_
Enumeration<Driver> drivers = DriverManager.getDrivers();_x000D_
while (drivers.hasMoreElements()) {_x000D_
Driver driver = drivers.nextElement();_x000D_
DriverManager.deregisterDriver(driver);_x000D_
}_x000D_
_x000D_
} catch (SQLException e) {_x000D_
// TODO Exception-handling_x000D_
e.printStackTrace();_x000D_
}_x000D_
}_x000D_
}_x000D_
| RobinHoutevelts/DynwebFramework | src/java/framework/database/Database.java | 1,400 | // MetaData is nodig, daarin zit het aantal kolommen en hoe ze heten_x000D_ | line_comment | nl | package framework.database;_x000D_
_x000D_
import java.lang.reflect.Constructor;_x000D_
import java.sql.Connection;_x000D_
import java.sql.Driver;_x000D_
import java.sql.DriverManager;_x000D_
import java.sql.PreparedStatement;_x000D_
import java.sql.ResultSet;_x000D_
import java.sql.ResultSetMetaData;_x000D_
import java.sql.SQLException;_x000D_
import java.util.ArrayList;_x000D_
import java.util.Enumeration;_x000D_
import java.util.HashMap;_x000D_
_x000D_
public class Database {_x000D_
_x000D_
protected Connection conn;_x000D_
protected String connectionUrl;_x000D_
protected String username;_x000D_
protected String password; // TODO: kijken in hoeverre het haalbaar is het wachtwoord hier weg te laten_x000D_
_x000D_
@SuppressWarnings({ "unchecked", "rawtypes" })_x000D_
public Database(String driver, String connectionUrl, String username, String password)_x000D_
{_x000D_
try {_x000D_
// Kijken of de driver bestaat_x000D_
Class DriverClass = Class.forName(driver);_x000D_
_x000D_
Constructor constructorClass = DriverClass.getConstructor();_x000D_
Driver dbDriver = (Driver) constructorClass.newInstance();_x000D_
DriverManager.registerDriver(dbDriver);_x000D_
_x000D_
} catch (Exception e) {_x000D_
// TODO Exception-handling_x000D_
e.printStackTrace();_x000D_
}_x000D_
_x000D_
this.connectionUrl = connectionUrl;_x000D_
this.username = username;_x000D_
this.password = password;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Maakt connectie naar de databank_x000D_
* _x000D_
* @return_x000D_
* @throws SQLException_x000D_
*/_x000D_
public Connection getConnection() throws SQLException_x000D_
{_x000D_
if(this.conn == null || this.conn.isClosed())_x000D_
this.conn = DriverManager.getConnection(connectionUrl,username,password);_x000D_
_x000D_
return this.conn;_x000D_
}_x000D_
_x000D_
public PreparedStatement prepareStatement(String query) throws SQLException_x000D_
{_x000D_
return conn.prepareStatement(query);_x000D_
}_x000D_
_x000D_
public NamedParamStatement namedParamStatement(String query) throws SQLException_x000D_
{_x000D_
return new NamedParamStatement(getConnection(), query);_x000D_
}_x000D_
_x000D_
/**_x000D_
* Geeft alle rows van een result in een handige ArrayList_x000D_
* _x000D_
* @param res_x000D_
* @return_x000D_
* @throws SQLException_x000D_
*/_x000D_
public ArrayList<DatabaseRow> getAllRows(ResultSet res) throws SQLException_x000D_
{_x000D_
ArrayList<DatabaseRow> rows = new ArrayList<DatabaseRow>();_x000D_
_x000D_
// Cursor naar -1 zetten._x000D_
res.beforeFirst();_x000D_
_x000D_
// Kijken of er op index 0 iets zit._x000D_
if(res.next()){_x000D_
// Blijkbaar zijn er rows_x000D_
// Cursor terug naar -1 zetten alle rows aflopen._x000D_
res.beforeFirst();_x000D_
_x000D_
// Pas als we aan de EOL zitten van de resultset stoppen we_x000D_
while(!res.isAfterLast()) {_x000D_
// Row ophalen en toevoegen aan Arraylist_x000D_
DatabaseRow row = this.getRow(res);_x000D_
if(row != null)_x000D_
rows.add(row);_x000D_
}_x000D_
}_x000D_
_x000D_
res.close();_x000D_
_x000D_
return rows;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Haalt de volgende row uit een resultset een geeft dit terug in een Hashmap<Kolomnaam,Object>_x000D_
* _x000D_
* @param res_x000D_
* @return_x000D_
* @throws SQLException_x000D_
*/_x000D_
public DatabaseRow getRow(ResultSet res) throws SQLException_x000D_
{_x000D_
HashMap<String, Object> row = new HashMap<String, Object>();_x000D_
_x000D_
// MetaData is<SUF>
ResultSetMetaData metaData = res.getMetaData();_x000D_
int columnCount = metaData.getColumnCount();_x000D_
_x000D_
ArrayList<String> columns = new ArrayList<String>();_x000D_
_x000D_
// Alle kolommen aflopen en hun naam bijhouden in de Array._x000D_
for (int columnNr=1; columnNr<=columnCount; columnNr++){_x000D_
String columnName = metaData.getColumnName(columnNr);_x000D_
columns.add(columnName);_x000D_
}_x000D_
_x000D_
// Springen naar de volgende row_x000D_
if (res.next()){_x000D_
// Alle kolommen in deze row aflopen_x000D_
for (String columnName:columns) {_x000D_
// De waarde van deze kolom ophalen_x000D_
Object rowData = res.getObject(columnName);_x000D_
// Toevoegen aan de hashmap_x000D_
row.put(columnName,rowData);_x000D_
}_x000D_
}_x000D_
_x000D_
if(row.size() <= 0)_x000D_
return null;_x000D_
_x000D_
return new DatabaseRow(row);_x000D_
}_x000D_
_x000D_
public void closeConnection() {_x000D_
try {_x000D_
conn.close();_x000D_
_x000D_
// This manually deregisters JDBC driver, which prevents Tomcat 7_x000D_
// from complaining about memory leaks wrto this class_x000D_
// http://stackoverflow.com/a/5315467/1306509_x000D_
Enumeration<Driver> drivers = DriverManager.getDrivers();_x000D_
while (drivers.hasMoreElements()) {_x000D_
Driver driver = drivers.nextElement();_x000D_
DriverManager.deregisterDriver(driver);_x000D_
}_x000D_
_x000D_
} catch (SQLException e) {_x000D_
// TODO Exception-handling_x000D_
e.printStackTrace();_x000D_
}_x000D_
}_x000D_
}_x000D_
| True | 1,989 | 26 | 2,171 | 32 | 2,249 | 25 | 2,171 | 32 | 2,394 | 28 | false | false | false | false | false | true |
2,528 | 6614_13 | /*
* Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 ai.djl.modality.nlp.generate;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDList;
import ai.djl.ndarray.index.NDIndex;
import ai.djl.ndarray.types.DataType;
import ai.djl.ndarray.types.Shape;
/**
* {@code StepGeneration} is a utility class containing the step generation utility functions used
* in autoregressive search.
*/
public final class StepGeneration {
private StepGeneration() {}
/**
* Generate the output token id and selecting indices used in contrastive search.
*
* @param topKIds the topk candidate token ids
* @param logits the logits from the language model
* @param contextHiddenStates the embedding of the past generated token ids
* @param topkHiddenStates the embedding of the topk candidate token ids
* @param offSets the offsets
* @param alpha the repetition penalty
* @return the output token ids and selecting indices
*/
public static NDList constrastiveStepGeneration(
NDArray topKIds,
NDArray logits,
NDArray contextHiddenStates,
NDArray topkHiddenStates,
NDArray offSets,
float alpha) {
/*
topKIds: [batch, topK]
attentionMask: [batch, past_seq]
logits: [batch, vocabSize]
contextHiddenStates: [batch, past_seq, dim]
topkHiddenStates: [batch*topK, seq=1, dim]
attentionMaskSlice: [batch, 2]: (startPosition, endPosition)
*/
long batch = topKIds.getShape().get(0);
long topK = topKIds.getShape().get(1);
long hiddenDim = topkHiddenStates.getShape().getLastDimension();
// [batch*topK, seq=1, dim] -> [batch, topK, dim]
topkHiddenStates = topkHiddenStates.reshape(batch, topK, hiddenDim);
// [batch, topK, dim] * [batch, past_seq, dim] -> [batch, topK, past_seq]
topkHiddenStates = topkHiddenStates.normalize(2, 2);
contextHiddenStates = contextHiddenStates.normalize(2, 2);
NDArray cosSimilarity =
topkHiddenStates.batchMatMul(contextHiddenStates.transpose(0, 2, 1));
// Deactivate entries (batch_idx, :, zero_attention_idx_slice) in max{cosSim} step
long[] offSetsArray = offSets.toLongArray();
for (int i = 0; i < offSetsArray.length; i++) {
cosSimilarity.set(new NDIndex("{}, :, {}:{}", i, 0, offSetsArray[i]), -1);
}
// [batch, topK, past_seq] -> [batch, topK]
NDArray topkScorePart1 = cosSimilarity.max(new int[] {2});
assert topkScorePart1.getShape().getShape().length == 2 : "Wrong output size";
// [batch, logitDim].gather([batch, topK) -> [batch, topK]
NDArray topkScorePart2 = logits.softmax(1).gather(topKIds, 1);
NDArray topkScore = topkScorePart2.muli(1 - alpha).subi(topkScorePart1.muli(alpha));
// [batch, topK] => [batch, 1]
NDArray select = topkScore.argMax(1);
NDIndex selectIndex =
new NDIndex(
"{}, {}, ...",
logits.getManager().arange(0, topKIds.getShape().get(0), 1, DataType.INT64),
select);
NDArray outputIds = topKIds.get(selectIndex).reshape(-1, 1);
return new NDList(outputIds, select);
}
// TODO: add support of Einstein summation:
// a = torch.randn(batch, past_seq, dim)
// b = torch.randn(batch, topK, dim)
// result = torch.einsum('bik,bjk->bij', a, b)
/**
* Generates the output token id for greedy search.
*
* @param logits the logits from the language model
* @return the output token ids
*/
public static NDArray greedyStepGen(NDArray logits) {
// logits: [batch, seq, probDim]
assert logits.getShape().getShape().length == 3 : "unexpected input";
logits = logits.get(":, -1, :");
return logits.argMax(-1).expandDims(1); // [batch, vacDim]
}
/**
* Generates the output token id and selecting indices used in beam search.
*
* @param lastProbs the probabilities of the past prefix sequences
* @param logits the logits
* @param numBatch number of batch
* @param numBeam number of beam
* @return the output token ids and selecting indices
*/
public static NDList beamStepGeneration(
NDArray lastProbs, NDArray logits, long numBatch, long numBeam) {
// [batch * beamSource, seq, probDim] -> [batch, beamSource, probDim]
NDArray allProbs = logits.get(":, -1, :").softmax(1).reshape(numBatch, numBeam, -1);
// Argmax over the probs in the prob dimension.
// [batch, beamSource, probDim] -> [batch, beamSource, beamChild]
NDList topK = allProbs.topK(Math.toIntExact(numBeam), -1, true, false);
NDArray outputIs = topK.get(1);
NDArray stepProbs = topK.get(0);
// Chain the probability
// [batch, beamSource] -> [batch, beamSource, 1]
lastProbs = lastProbs.reshape(numBatch, numBeam, 1);
// [batch, beamSource, beamChild]
NDArray newProbs = stepProbs.muli(lastProbs);
// Argmax over the (beamSource * beamChild) dimension
topK =
newProbs.reshape(numBatch, numBeam * numBeam)
.topK(Math.toIntExact(numBeam), -1, true, false);
// The select indices act on (beamSource, beamChild) dimension. Decides how the new
// generated tokenIds correspond to the past tokenIds.
// [batch, beamNew].
NDArray select = topK.get(1);
// Act on [batch, beam, ...] dimension and the output will be [batch, beam, ...]
NDIndex selectIndex =
new NDIndex(
"{}, {}, ...",
logits.getManager()
.arange(0, numBatch, 1, DataType.INT64)
.expandDims(1)
.repeat(1, numBeam),
select);
// [batch, beamNew]
outputIs = outputIs.reshape(numBatch, numBeam * numBeam).get(selectIndex).expandDims(2);
// [batch, beamNew]
newProbs = newProbs.reshape(numBatch, numBeam * numBeam).get(selectIndex).normalize(1, 1);
/* During the beam selection process, some source beams are selected several times while
some source beams are not selected even once. The pastOutputs should be reselected to
have the right correspondence to the newInputIds.
*/
// [batch, beamNew]
assert select.getDataType() == DataType.INT64 : "Wrong output! Expect integer division";
assert select.getShape().getShape().length == 2 : "Wrong size. Expect [batch, beamNew]";
// For each batch, convert the index1 in beamSource*beamChild dimension to its index2 in
// beamSource dimension: index2 = index1 / numBeam.
long[] index = select.toLongArray();
for (int i = 0; i < index.length; i++) {
index[i] = Math.floorDiv(index[i], numBeam);
}
NDArray sourceBeamSelected =
logits.getManager().create(index, new Shape(numBatch, numBeam));
return new NDList(outputIs, newProbs, sourceBeamSelected);
}
// TODO: implement pytorch floor_divide.
}
| deepjavalibrary/djl | api/src/main/java/ai/djl/modality/nlp/generate/StepGeneration.java | 2,376 | // result = torch.einsum('bik,bjk->bij', a, b) | line_comment | nl | /*
* Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 ai.djl.modality.nlp.generate;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDList;
import ai.djl.ndarray.index.NDIndex;
import ai.djl.ndarray.types.DataType;
import ai.djl.ndarray.types.Shape;
/**
* {@code StepGeneration} is a utility class containing the step generation utility functions used
* in autoregressive search.
*/
public final class StepGeneration {
private StepGeneration() {}
/**
* Generate the output token id and selecting indices used in contrastive search.
*
* @param topKIds the topk candidate token ids
* @param logits the logits from the language model
* @param contextHiddenStates the embedding of the past generated token ids
* @param topkHiddenStates the embedding of the topk candidate token ids
* @param offSets the offsets
* @param alpha the repetition penalty
* @return the output token ids and selecting indices
*/
public static NDList constrastiveStepGeneration(
NDArray topKIds,
NDArray logits,
NDArray contextHiddenStates,
NDArray topkHiddenStates,
NDArray offSets,
float alpha) {
/*
topKIds: [batch, topK]
attentionMask: [batch, past_seq]
logits: [batch, vocabSize]
contextHiddenStates: [batch, past_seq, dim]
topkHiddenStates: [batch*topK, seq=1, dim]
attentionMaskSlice: [batch, 2]: (startPosition, endPosition)
*/
long batch = topKIds.getShape().get(0);
long topK = topKIds.getShape().get(1);
long hiddenDim = topkHiddenStates.getShape().getLastDimension();
// [batch*topK, seq=1, dim] -> [batch, topK, dim]
topkHiddenStates = topkHiddenStates.reshape(batch, topK, hiddenDim);
// [batch, topK, dim] * [batch, past_seq, dim] -> [batch, topK, past_seq]
topkHiddenStates = topkHiddenStates.normalize(2, 2);
contextHiddenStates = contextHiddenStates.normalize(2, 2);
NDArray cosSimilarity =
topkHiddenStates.batchMatMul(contextHiddenStates.transpose(0, 2, 1));
// Deactivate entries (batch_idx, :, zero_attention_idx_slice) in max{cosSim} step
long[] offSetsArray = offSets.toLongArray();
for (int i = 0; i < offSetsArray.length; i++) {
cosSimilarity.set(new NDIndex("{}, :, {}:{}", i, 0, offSetsArray[i]), -1);
}
// [batch, topK, past_seq] -> [batch, topK]
NDArray topkScorePart1 = cosSimilarity.max(new int[] {2});
assert topkScorePart1.getShape().getShape().length == 2 : "Wrong output size";
// [batch, logitDim].gather([batch, topK) -> [batch, topK]
NDArray topkScorePart2 = logits.softmax(1).gather(topKIds, 1);
NDArray topkScore = topkScorePart2.muli(1 - alpha).subi(topkScorePart1.muli(alpha));
// [batch, topK] => [batch, 1]
NDArray select = topkScore.argMax(1);
NDIndex selectIndex =
new NDIndex(
"{}, {}, ...",
logits.getManager().arange(0, topKIds.getShape().get(0), 1, DataType.INT64),
select);
NDArray outputIds = topKIds.get(selectIndex).reshape(-1, 1);
return new NDList(outputIds, select);
}
// TODO: add support of Einstein summation:
// a = torch.randn(batch, past_seq, dim)
// b = torch.randn(batch, topK, dim)
// result =<SUF>
/**
* Generates the output token id for greedy search.
*
* @param logits the logits from the language model
* @return the output token ids
*/
public static NDArray greedyStepGen(NDArray logits) {
// logits: [batch, seq, probDim]
assert logits.getShape().getShape().length == 3 : "unexpected input";
logits = logits.get(":, -1, :");
return logits.argMax(-1).expandDims(1); // [batch, vacDim]
}
/**
* Generates the output token id and selecting indices used in beam search.
*
* @param lastProbs the probabilities of the past prefix sequences
* @param logits the logits
* @param numBatch number of batch
* @param numBeam number of beam
* @return the output token ids and selecting indices
*/
public static NDList beamStepGeneration(
NDArray lastProbs, NDArray logits, long numBatch, long numBeam) {
// [batch * beamSource, seq, probDim] -> [batch, beamSource, probDim]
NDArray allProbs = logits.get(":, -1, :").softmax(1).reshape(numBatch, numBeam, -1);
// Argmax over the probs in the prob dimension.
// [batch, beamSource, probDim] -> [batch, beamSource, beamChild]
NDList topK = allProbs.topK(Math.toIntExact(numBeam), -1, true, false);
NDArray outputIs = topK.get(1);
NDArray stepProbs = topK.get(0);
// Chain the probability
// [batch, beamSource] -> [batch, beamSource, 1]
lastProbs = lastProbs.reshape(numBatch, numBeam, 1);
// [batch, beamSource, beamChild]
NDArray newProbs = stepProbs.muli(lastProbs);
// Argmax over the (beamSource * beamChild) dimension
topK =
newProbs.reshape(numBatch, numBeam * numBeam)
.topK(Math.toIntExact(numBeam), -1, true, false);
// The select indices act on (beamSource, beamChild) dimension. Decides how the new
// generated tokenIds correspond to the past tokenIds.
// [batch, beamNew].
NDArray select = topK.get(1);
// Act on [batch, beam, ...] dimension and the output will be [batch, beam, ...]
NDIndex selectIndex =
new NDIndex(
"{}, {}, ...",
logits.getManager()
.arange(0, numBatch, 1, DataType.INT64)
.expandDims(1)
.repeat(1, numBeam),
select);
// [batch, beamNew]
outputIs = outputIs.reshape(numBatch, numBeam * numBeam).get(selectIndex).expandDims(2);
// [batch, beamNew]
newProbs = newProbs.reshape(numBatch, numBeam * numBeam).get(selectIndex).normalize(1, 1);
/* During the beam selection process, some source beams are selected several times while
some source beams are not selected even once. The pastOutputs should be reselected to
have the right correspondence to the newInputIds.
*/
// [batch, beamNew]
assert select.getDataType() == DataType.INT64 : "Wrong output! Expect integer division";
assert select.getShape().getShape().length == 2 : "Wrong size. Expect [batch, beamNew]";
// For each batch, convert the index1 in beamSource*beamChild dimension to its index2 in
// beamSource dimension: index2 = index1 / numBeam.
long[] index = select.toLongArray();
for (int i = 0; i < index.length; i++) {
index[i] = Math.floorDiv(index[i], numBeam);
}
NDArray sourceBeamSelected =
logits.getManager().create(index, new Shape(numBatch, numBeam));
return new NDList(outputIs, newProbs, sourceBeamSelected);
}
// TODO: implement pytorch floor_divide.
}
| False | 1,948 | 19 | 2,056 | 20 | 2,178 | 19 | 2,056 | 20 | 2,429 | 22 | false | false | false | false | false | true |
3,194 | 187427_1 | class RingBuffer {
int size;
int[] smg;
int start;
int end;
// returns a rb of the size
RingBuffer(int size) {
this.size = size;
this.smg = new int[size];
this.start = 0;
this.end = 0;
}
// insert : int ->
public RingBuffer insert( int elem ) {
this.smg[ this.end ] = elem;
this.end = (this.end + 1) % this.size;
return this;
}
// read : int -> int
// REQUIRES: insert() has been called at least idx times
// idx < size
// returns the element inserted idx times in the past
// EXAMPLE
// (new RingBuffer(2)).insert(1).insert(2).insert(3).read(1)
// = 2
public int read ( int idx ) {
return
this.smg[ (this.end - idx + this.size - 1)
% this.size ];
}
// BEFORE: start = 0, end = 0, size = 2, smg = { ? , ? }
// insert(1)
// AFTER: smg = { 1 , ? }, end = 1
// insert(2)
// AFTER: smg = { 1 , 2 }, end = 0
// insert(3)
// AFTER: smg = { 3 , 2 }, end = 1
// read(1)
}
class Box {
boolean d;
Box() {
this.d = true;
}
// observe : -> bool
// EFFECTS: this
// IMPL: flips the booleanosity of this.d
// CLIENT: cycles between false and true
// CLIENT: the next call to observe will return the opposite of what this one does; the first call returns false
// BIG DEAL: Specs are for clients, not implementers
public boolean observe() {
this.d = ! this.d;
return this.d;
}
}
class C7 {
// returns three more than the input
// REQUIRES: x be even
static int f ( int x ) {
return x + 3;
}
// g : ->
// REQUIRES: amanda_before is even
// EFFECTS: amanda
// amanda_after is amanda_before + 3
static int amanda = 0;
static void g ( ) {
amanda = amanda + 3;
}
static class Store {
public int amanda;
Store ( int amanda ) {
this.amanda = amanda;
}
}
// XXXg : Store -> Store
// REQUIRES: the store contain an even amanda
// produces a new store that contains an amanda three degrees
// cooler
static Store XXXg ( Store st ) {
return new Store ( st.amanda + 3 );
}
static int isabella = 0;
// hm : int -> int
// REQUIRES: y can't be zero
// EFFECTS: isabella
// isabella_after is one more than isabella_before
// returns isabella_before divided by y
static int hm ( int y ) {
int r = isabella / y;
isabella = isabella + 1;
return r;
}
static class HMStore {
public int isabella;
HMStore ( int isabella ) {
this.isabella = isabella;
}
}
static class IntAndHMStore {
int r;
HMStore st;
IntAndHMStore( int r, HMStore st ) {
this.r = r;
this.st = st;
}
}
// XXXh : Store int -> int x Store
// REQUIRES: y can't be zero
// returns st.isabella divided by y and a store where isabella is
// one more than st.isabella
static IntAndHMStore XXXhm ( HMStore st, int y ) {
int r = st.isabella / y;
HMStore stp = new HMStore( st.isabella + 1 );
return new IntAndHMStore( r, stp );
}
// The transformation is called "Store-Passing Style"
public static void main(String[] args) {
System.out.println("Yo! Raps!");
System.out.println(f(4) + " should be " + 7);
int x = 4;
System.out.println(f(x) + " should be " + 7);
System.out.println((x + 3) + " should be " + 7);
System.out.println((4 + 3) + " should be " + 7);
x = x / 2;
System.out.println(f(x) + " should be " + 5);
System.out.println((x + 3) + " should be " + 5);
System.out.println((2 + 3) + " should be " + 5);
amanda = 4;
// BEFORE amanda = 4
g();
// AFTER amanda = 7
System.out.println(amanda + " should be " + 7);
g();
System.out.println(amanda + " should be " + 10);
// From here
Store st_0 = new Store( 4 );
Store st_1 = XXXg( st_0 );
System.out.println(st_1.amanda + " should be " + 7);
Store st_2 = XXXg( st_1 );
System.out.println(st_2.amanda + " should be " + 10);
// to here
// st_x is used "linearly"
System.out.println(st_0.amanda + " should be " + 4);
Box sb = new Box();
System.out.println("The box says, " + sb.observe());
System.out.println("The box says, " + sb.observe());
System.out.println("The box says, " + sb.observe());
System.out.println("The fox says, ?");
RingBuffer rb = (new RingBuffer(2));
rb.insert(1);
System.out.println(rb.read(0) + " should be " + 1 );
rb.insert(2);
System.out.println(rb.read(0) + " should be " + 2 );
System.out.println(rb.read(1) + " should be " + 1 );
rb.insert(3);
System.out.println(rb.read(0) + " should be " + 3 );
System.out.println(rb.read(1) + " should be " + 2 );
rb.insert(4);
System.out.println(rb.read(0) + " should be " + 4 );
System.out.println(rb.read(1) + " should be " + 3 );
}
}
| jeapostrophe/jeapostrophe.github.com | courses/2014/fall/203/notes/7.java | 1,812 | // insert : int -> | line_comment | nl | class RingBuffer {
int size;
int[] smg;
int start;
int end;
// returns a rb of the size
RingBuffer(int size) {
this.size = size;
this.smg = new int[size];
this.start = 0;
this.end = 0;
}
// insert :<SUF>
public RingBuffer insert( int elem ) {
this.smg[ this.end ] = elem;
this.end = (this.end + 1) % this.size;
return this;
}
// read : int -> int
// REQUIRES: insert() has been called at least idx times
// idx < size
// returns the element inserted idx times in the past
// EXAMPLE
// (new RingBuffer(2)).insert(1).insert(2).insert(3).read(1)
// = 2
public int read ( int idx ) {
return
this.smg[ (this.end - idx + this.size - 1)
% this.size ];
}
// BEFORE: start = 0, end = 0, size = 2, smg = { ? , ? }
// insert(1)
// AFTER: smg = { 1 , ? }, end = 1
// insert(2)
// AFTER: smg = { 1 , 2 }, end = 0
// insert(3)
// AFTER: smg = { 3 , 2 }, end = 1
// read(1)
}
class Box {
boolean d;
Box() {
this.d = true;
}
// observe : -> bool
// EFFECTS: this
// IMPL: flips the booleanosity of this.d
// CLIENT: cycles between false and true
// CLIENT: the next call to observe will return the opposite of what this one does; the first call returns false
// BIG DEAL: Specs are for clients, not implementers
public boolean observe() {
this.d = ! this.d;
return this.d;
}
}
class C7 {
// returns three more than the input
// REQUIRES: x be even
static int f ( int x ) {
return x + 3;
}
// g : ->
// REQUIRES: amanda_before is even
// EFFECTS: amanda
// amanda_after is amanda_before + 3
static int amanda = 0;
static void g ( ) {
amanda = amanda + 3;
}
static class Store {
public int amanda;
Store ( int amanda ) {
this.amanda = amanda;
}
}
// XXXg : Store -> Store
// REQUIRES: the store contain an even amanda
// produces a new store that contains an amanda three degrees
// cooler
static Store XXXg ( Store st ) {
return new Store ( st.amanda + 3 );
}
static int isabella = 0;
// hm : int -> int
// REQUIRES: y can't be zero
// EFFECTS: isabella
// isabella_after is one more than isabella_before
// returns isabella_before divided by y
static int hm ( int y ) {
int r = isabella / y;
isabella = isabella + 1;
return r;
}
static class HMStore {
public int isabella;
HMStore ( int isabella ) {
this.isabella = isabella;
}
}
static class IntAndHMStore {
int r;
HMStore st;
IntAndHMStore( int r, HMStore st ) {
this.r = r;
this.st = st;
}
}
// XXXh : Store int -> int x Store
// REQUIRES: y can't be zero
// returns st.isabella divided by y and a store where isabella is
// one more than st.isabella
static IntAndHMStore XXXhm ( HMStore st, int y ) {
int r = st.isabella / y;
HMStore stp = new HMStore( st.isabella + 1 );
return new IntAndHMStore( r, stp );
}
// The transformation is called "Store-Passing Style"
public static void main(String[] args) {
System.out.println("Yo! Raps!");
System.out.println(f(4) + " should be " + 7);
int x = 4;
System.out.println(f(x) + " should be " + 7);
System.out.println((x + 3) + " should be " + 7);
System.out.println((4 + 3) + " should be " + 7);
x = x / 2;
System.out.println(f(x) + " should be " + 5);
System.out.println((x + 3) + " should be " + 5);
System.out.println((2 + 3) + " should be " + 5);
amanda = 4;
// BEFORE amanda = 4
g();
// AFTER amanda = 7
System.out.println(amanda + " should be " + 7);
g();
System.out.println(amanda + " should be " + 10);
// From here
Store st_0 = new Store( 4 );
Store st_1 = XXXg( st_0 );
System.out.println(st_1.amanda + " should be " + 7);
Store st_2 = XXXg( st_1 );
System.out.println(st_2.amanda + " should be " + 10);
// to here
// st_x is used "linearly"
System.out.println(st_0.amanda + " should be " + 4);
Box sb = new Box();
System.out.println("The box says, " + sb.observe());
System.out.println("The box says, " + sb.observe());
System.out.println("The box says, " + sb.observe());
System.out.println("The fox says, ?");
RingBuffer rb = (new RingBuffer(2));
rb.insert(1);
System.out.println(rb.read(0) + " should be " + 1 );
rb.insert(2);
System.out.println(rb.read(0) + " should be " + 2 );
System.out.println(rb.read(1) + " should be " + 1 );
rb.insert(3);
System.out.println(rb.read(0) + " should be " + 3 );
System.out.println(rb.read(1) + " should be " + 2 );
rb.insert(4);
System.out.println(rb.read(0) + " should be " + 4 );
System.out.println(rb.read(1) + " should be " + 3 );
}
}
| False | 1,518 | 5 | 1,654 | 5 | 1,743 | 5 | 1,654 | 5 | 1,867 | 5 | false | false | false | false | false | true |
325 | 30224_11 | package nl.novi.techiteasy.controllers;
import nl.novi.techiteasy.exceptions.RecordNotFoundException;
import nl.novi.techiteasy.exceptions.TelevisionNameTooLongException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
// Deze RequestMapping" op klasse niveau betekent dat elke Mapping in deze klasse begint met "localhost:8080/bonus/..."
@RequestMapping(value = "/bonus")
public class TelevisionControllerBonus {
// De lijst is static, omdat er maar 1 lijst kan zijn.
// De lijst is final, omdat de lijst op zich niet kan veranderen, enkel de waardes die er in staan.
private static final List<String> televisionDatabase = new ArrayList<>();
@GetMapping("/televisions")
public ResponseEntity<List<String>> getAllTelevisions() {
// Return de complete lijst met een 200 status
return ResponseEntity.ok(televisionDatabase);
}
@GetMapping("/televisions/{id}")
public ResponseEntity<String> getTelevision(@PathVariable int id) {
// Return de waarde die op index(id) staat en een 200 status
// Wanneer de gebruiker een request doet met id=300, maar de lijst heeft maar 3 items.
// Dan gooit java een IndexOutOfBoundsException. De bonus methode in de ExceptionController vangt dit op en stuurt de gebruiker een berichtje.
return ResponseEntity.ok(televisionDatabase.get(id));
}
@PostMapping("/televisions")
public ResponseEntity<String> addTelevision(@RequestBody String television) {
// Bonus bonus: check voor 20 letters:
if(television.length()>20){
throw new TelevisionNameTooLongException("Televisienaam is te lang");
} else {
// Voeg de televisie uit de parameter toe aan de lijst
televisionDatabase.add(television);
// Return de televisie uit de parameter met een 201 status
return ResponseEntity.created(null).body(television);
}
}
@DeleteMapping("/televisions/{id}")
public ResponseEntity<Void> deleteTelevision(@PathVariable int id) {
// Vervang de waarde op index(id) met null. Als we de waarde zouden verwijderen, zouden alle indexen die na deze waarden komen in de lijst met 1 afnemen.
televisionDatabase.set(id, null);
// Return een 204 status
return ResponseEntity.noContent().build();
}
@PutMapping("/televisions/{id}")
public ResponseEntity<Void> updateTelevision(@PathVariable int id, @RequestBody String television) {
// In de vorige methodes hebben we impliciet gebruik gemaakt van "IndexOUtOfBoundsException" als het id groter was dan de lijst.
// In deze methode checken we daar expliciet voor en gooien we een custom exception op.
if(televisionDatabase.isEmpty() || id>televisionDatabase.size()){
throw new RecordNotFoundException("Record met id: " + id + " niet gevonden in de database.");
} else {
// Vervang de waarde op index(id) met de television uit de parameter
televisionDatabase.set(id, television);
// Return een 204 status
return ResponseEntity.noContent().build();
}
}
} | Christiaan83/backend-spring-boot-tech-it-easy | src/main/java/nl/novi/techiteasy/controllers/TelevisionControllerBonus.java | 897 | // Return een 204 status | line_comment | nl | package nl.novi.techiteasy.controllers;
import nl.novi.techiteasy.exceptions.RecordNotFoundException;
import nl.novi.techiteasy.exceptions.TelevisionNameTooLongException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
// Deze RequestMapping" op klasse niveau betekent dat elke Mapping in deze klasse begint met "localhost:8080/bonus/..."
@RequestMapping(value = "/bonus")
public class TelevisionControllerBonus {
// De lijst is static, omdat er maar 1 lijst kan zijn.
// De lijst is final, omdat de lijst op zich niet kan veranderen, enkel de waardes die er in staan.
private static final List<String> televisionDatabase = new ArrayList<>();
@GetMapping("/televisions")
public ResponseEntity<List<String>> getAllTelevisions() {
// Return de complete lijst met een 200 status
return ResponseEntity.ok(televisionDatabase);
}
@GetMapping("/televisions/{id}")
public ResponseEntity<String> getTelevision(@PathVariable int id) {
// Return de waarde die op index(id) staat en een 200 status
// Wanneer de gebruiker een request doet met id=300, maar de lijst heeft maar 3 items.
// Dan gooit java een IndexOutOfBoundsException. De bonus methode in de ExceptionController vangt dit op en stuurt de gebruiker een berichtje.
return ResponseEntity.ok(televisionDatabase.get(id));
}
@PostMapping("/televisions")
public ResponseEntity<String> addTelevision(@RequestBody String television) {
// Bonus bonus: check voor 20 letters:
if(television.length()>20){
throw new TelevisionNameTooLongException("Televisienaam is te lang");
} else {
// Voeg de televisie uit de parameter toe aan de lijst
televisionDatabase.add(television);
// Return de televisie uit de parameter met een 201 status
return ResponseEntity.created(null).body(television);
}
}
@DeleteMapping("/televisions/{id}")
public ResponseEntity<Void> deleteTelevision(@PathVariable int id) {
// Vervang de waarde op index(id) met null. Als we de waarde zouden verwijderen, zouden alle indexen die na deze waarden komen in de lijst met 1 afnemen.
televisionDatabase.set(id, null);
// Return een<SUF>
return ResponseEntity.noContent().build();
}
@PutMapping("/televisions/{id}")
public ResponseEntity<Void> updateTelevision(@PathVariable int id, @RequestBody String television) {
// In de vorige methodes hebben we impliciet gebruik gemaakt van "IndexOUtOfBoundsException" als het id groter was dan de lijst.
// In deze methode checken we daar expliciet voor en gooien we een custom exception op.
if(televisionDatabase.isEmpty() || id>televisionDatabase.size()){
throw new RecordNotFoundException("Record met id: " + id + " niet gevonden in de database.");
} else {
// Vervang de waarde op index(id) met de television uit de parameter
televisionDatabase.set(id, television);
// Return een 204 status
return ResponseEntity.noContent().build();
}
}
} | True | 725 | 8 | 831 | 8 | 776 | 8 | 831 | 8 | 919 | 8 | false | false | false | false | false | true |
62 | 25179_6 | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.LinkedHashMap;
import java.util.Map;
import java.awt.event.ActionListener;
/**
* A graphical view of the simulation grid.
* The view displays a colored rectangle for each location
* representing its contents. It uses a default background color.
* Colors for each type of species can be defined using the
* setColor method.
*
* @author Adriaan van Elk, Eric Gunnink & Jelmer Postma
* @version 27-1-2015
*/
public class SimulatorView extends JFrame implements ActionListener
{
// Colors used for empty locations.
private static final Color EMPTY_COLOR = Color.white;
// Color used for objects that have no defined color.
private static final Color UNKNOWN_COLOR = Color.gray;
private final String STEP_PREFIX = "Step: ";
private final String POPULATION_PREFIX = "Population: ";
private JLabel stepLabel, population;
private JPanel linkerMenu;
private FieldView fieldView;
public JButton oneStepButton = new JButton("1 stap");
public JButton oneHundredStepButton = new JButton("100 stappen");
// A map for storing colors for participants in the simulation
private Map<Class, Color> colors;
// A statistics object computing and storing simulation information
private FieldStats stats;
private Simulator theSimulator;
/**
* Create a view of the given width and height.
* @param height The simulation's height.
* @param width The simulation's width.
*/
public SimulatorView(int height, int width, Simulator simulator)
{
stats = new FieldStats();
colors = new LinkedHashMap<Class, Color>();
setTitle("Fox and Rabbit Simulation");
stepLabel = new JLabel(STEP_PREFIX, JLabel.CENTER);
population = new JLabel(POPULATION_PREFIX, JLabel.CENTER);
linkerMenu = new JPanel(new GridLayout(2,1));
theSimulator = simulator;
setLocation(100, 50);
fieldView = new FieldView(height, width);
Container contents = getContentPane();
contents.add(stepLabel, BorderLayout.NORTH);
contents.add(fieldView, BorderLayout.CENTER);
contents.add(population, BorderLayout.SOUTH);
contents.add(linkerMenu, BorderLayout.WEST);
addButton();
pack();
setVisible(true);
}
private void addButton()
{
linkerMenu.add(oneStepButton);
linkerMenu.add(oneHundredStepButton);
oneStepButton.addActionListener(this);
oneHundredStepButton.addActionListener(this);
}
/**
* Methode om een actie uit te voeren wanneer er op een knop wordt geklikt
*/
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();
if(command.equals("1 stap"))
{
theSimulator.simulateOneStep();
}
if(command.equals("100 stappen"))
{
theSimulator.simulate(100);
}
}
/**
* Define a color to be used for a given class of animal.
* @param animalClass The animal's Class object.
* @param color The color to be used for the given class.
*/
public void setColor(Class animalClass, Color color)
{
colors.put(animalClass, color);
}
/**
* @return The color to be used for a given class of animal.
*/
private Color getColor(Class animalClass)
{
Color col = colors.get(animalClass);
if(col == null) {
// no color defined for this class
return UNKNOWN_COLOR;
}
else {
return col;
}
}
/**
* Show the current status of the field.
* @param step Which iteration step it is.
* @param field The field whose status is to be displayed.
*/
public void showStatus(int step, Field field)
{
if(!isVisible()) {
setVisible(true);
}
stepLabel.setText(STEP_PREFIX + step);
stats.reset();
fieldView.preparePaint();
for(int row = 0; row < field.getDepth(); row++) {
for(int col = 0; col < field.getWidth(); col++) {
Object animal = field.getObjectAt(row, col);
if(animal != null) {
stats.incrementCount(animal.getClass());
fieldView.drawMark(col, row, getColor(animal.getClass()));
}
else {
fieldView.drawMark(col, row, EMPTY_COLOR);
}
}
}
stats.countFinished();
population.setText(POPULATION_PREFIX + stats.getPopulationDetails(field));
fieldView.repaint();
}
/**
* Determine whether the simulation should continue to run.
* @return true If there is more than one species alive.
*/
public boolean isViable(Field field)
{
return stats.isViable(field);
}
/**
* Provide a graphical view of a rectangular field. This is
* a nested class (a class defined inside a class) which
* defines a custom component for the user interface. This
* component displays the field.
* This is rather advanced GUI stuff - you can ignore this
* for your project if you like.
*/
private class FieldView extends JPanel
{
private final int GRID_VIEW_SCALING_FACTOR = 6;
private int gridWidth, gridHeight;
private int xScale, yScale;
Dimension size;
private Graphics g;
private Image fieldImage;
/**
* Create a new FieldView component.
*/
public FieldView(int height, int width)
{
gridHeight = height;
gridWidth = width;
size = new Dimension(0, 0);
}
/**
* Tell the GUI manager how big we would like to be.
*/
public Dimension getPreferredSize()
{
return new Dimension(gridWidth * GRID_VIEW_SCALING_FACTOR,
gridHeight * GRID_VIEW_SCALING_FACTOR);
}
/**
* Prepare for a new round of painting. Since the component
* may be resized, compute the scaling factor again.
*/
public void preparePaint()
{
if(! size.equals(getSize())) { // if the size has changed...
size = getSize();
fieldImage = fieldView.createImage(size.width, size.height);
g = fieldImage.getGraphics();
xScale = size.width / gridWidth;
if(xScale < 1) {
xScale = GRID_VIEW_SCALING_FACTOR;
}
yScale = size.height / gridHeight;
if(yScale < 1) {
yScale = GRID_VIEW_SCALING_FACTOR;
}
}
}
/**
* Paint on grid location on this field in a given color.
*/
public void drawMark(int x, int y, Color color)
{
g.setColor(color);
g.fillRect(x * xScale, y * yScale, xScale-1, yScale-1);
}
/**
* The field view component needs to be redisplayed. Copy the
* internal image to screen.
*/
public void paintComponent(Graphics g)
{
if(fieldImage != null) {
Dimension currentSize = getSize();
if(size.equals(currentSize)) {
g.drawImage(fieldImage, 0, 0, null);
}
else {
// Rescale the previous image.
g.drawImage(fieldImage, 0, 0, currentSize.width, currentSize.height, null);
}
}
}
}
}
| AVEHD/fox_bunny | SimulatorView.java | 2,166 | /**
* Methode om een actie uit te voeren wanneer er op een knop wordt geklikt
*/ | block_comment | nl | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.LinkedHashMap;
import java.util.Map;
import java.awt.event.ActionListener;
/**
* A graphical view of the simulation grid.
* The view displays a colored rectangle for each location
* representing its contents. It uses a default background color.
* Colors for each type of species can be defined using the
* setColor method.
*
* @author Adriaan van Elk, Eric Gunnink & Jelmer Postma
* @version 27-1-2015
*/
public class SimulatorView extends JFrame implements ActionListener
{
// Colors used for empty locations.
private static final Color EMPTY_COLOR = Color.white;
// Color used for objects that have no defined color.
private static final Color UNKNOWN_COLOR = Color.gray;
private final String STEP_PREFIX = "Step: ";
private final String POPULATION_PREFIX = "Population: ";
private JLabel stepLabel, population;
private JPanel linkerMenu;
private FieldView fieldView;
public JButton oneStepButton = new JButton("1 stap");
public JButton oneHundredStepButton = new JButton("100 stappen");
// A map for storing colors for participants in the simulation
private Map<Class, Color> colors;
// A statistics object computing and storing simulation information
private FieldStats stats;
private Simulator theSimulator;
/**
* Create a view of the given width and height.
* @param height The simulation's height.
* @param width The simulation's width.
*/
public SimulatorView(int height, int width, Simulator simulator)
{
stats = new FieldStats();
colors = new LinkedHashMap<Class, Color>();
setTitle("Fox and Rabbit Simulation");
stepLabel = new JLabel(STEP_PREFIX, JLabel.CENTER);
population = new JLabel(POPULATION_PREFIX, JLabel.CENTER);
linkerMenu = new JPanel(new GridLayout(2,1));
theSimulator = simulator;
setLocation(100, 50);
fieldView = new FieldView(height, width);
Container contents = getContentPane();
contents.add(stepLabel, BorderLayout.NORTH);
contents.add(fieldView, BorderLayout.CENTER);
contents.add(population, BorderLayout.SOUTH);
contents.add(linkerMenu, BorderLayout.WEST);
addButton();
pack();
setVisible(true);
}
private void addButton()
{
linkerMenu.add(oneStepButton);
linkerMenu.add(oneHundredStepButton);
oneStepButton.addActionListener(this);
oneHundredStepButton.addActionListener(this);
}
/**
* Methode om een<SUF>*/
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();
if(command.equals("1 stap"))
{
theSimulator.simulateOneStep();
}
if(command.equals("100 stappen"))
{
theSimulator.simulate(100);
}
}
/**
* Define a color to be used for a given class of animal.
* @param animalClass The animal's Class object.
* @param color The color to be used for the given class.
*/
public void setColor(Class animalClass, Color color)
{
colors.put(animalClass, color);
}
/**
* @return The color to be used for a given class of animal.
*/
private Color getColor(Class animalClass)
{
Color col = colors.get(animalClass);
if(col == null) {
// no color defined for this class
return UNKNOWN_COLOR;
}
else {
return col;
}
}
/**
* Show the current status of the field.
* @param step Which iteration step it is.
* @param field The field whose status is to be displayed.
*/
public void showStatus(int step, Field field)
{
if(!isVisible()) {
setVisible(true);
}
stepLabel.setText(STEP_PREFIX + step);
stats.reset();
fieldView.preparePaint();
for(int row = 0; row < field.getDepth(); row++) {
for(int col = 0; col < field.getWidth(); col++) {
Object animal = field.getObjectAt(row, col);
if(animal != null) {
stats.incrementCount(animal.getClass());
fieldView.drawMark(col, row, getColor(animal.getClass()));
}
else {
fieldView.drawMark(col, row, EMPTY_COLOR);
}
}
}
stats.countFinished();
population.setText(POPULATION_PREFIX + stats.getPopulationDetails(field));
fieldView.repaint();
}
/**
* Determine whether the simulation should continue to run.
* @return true If there is more than one species alive.
*/
public boolean isViable(Field field)
{
return stats.isViable(field);
}
/**
* Provide a graphical view of a rectangular field. This is
* a nested class (a class defined inside a class) which
* defines a custom component for the user interface. This
* component displays the field.
* This is rather advanced GUI stuff - you can ignore this
* for your project if you like.
*/
private class FieldView extends JPanel
{
private final int GRID_VIEW_SCALING_FACTOR = 6;
private int gridWidth, gridHeight;
private int xScale, yScale;
Dimension size;
private Graphics g;
private Image fieldImage;
/**
* Create a new FieldView component.
*/
public FieldView(int height, int width)
{
gridHeight = height;
gridWidth = width;
size = new Dimension(0, 0);
}
/**
* Tell the GUI manager how big we would like to be.
*/
public Dimension getPreferredSize()
{
return new Dimension(gridWidth * GRID_VIEW_SCALING_FACTOR,
gridHeight * GRID_VIEW_SCALING_FACTOR);
}
/**
* Prepare for a new round of painting. Since the component
* may be resized, compute the scaling factor again.
*/
public void preparePaint()
{
if(! size.equals(getSize())) { // if the size has changed...
size = getSize();
fieldImage = fieldView.createImage(size.width, size.height);
g = fieldImage.getGraphics();
xScale = size.width / gridWidth;
if(xScale < 1) {
xScale = GRID_VIEW_SCALING_FACTOR;
}
yScale = size.height / gridHeight;
if(yScale < 1) {
yScale = GRID_VIEW_SCALING_FACTOR;
}
}
}
/**
* Paint on grid location on this field in a given color.
*/
public void drawMark(int x, int y, Color color)
{
g.setColor(color);
g.fillRect(x * xScale, y * yScale, xScale-1, yScale-1);
}
/**
* The field view component needs to be redisplayed. Copy the
* internal image to screen.
*/
public void paintComponent(Graphics g)
{
if(fieldImage != null) {
Dimension currentSize = getSize();
if(size.equals(currentSize)) {
g.drawImage(fieldImage, 0, 0, null);
}
else {
// Rescale the previous image.
g.drawImage(fieldImage, 0, 0, currentSize.width, currentSize.height, null);
}
}
}
}
}
| True | 1,619 | 28 | 1,769 | 29 | 1,966 | 24 | 1,769 | 29 | 2,183 | 31 | false | false | false | false | false | true |
1,216 | 42865_0 | package controllers;
import data.ReadData;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.BorderPane;
import models.Player;
import views.CreateNewPlayerView;
import views.TicTacToeView;
/**
* Zorgt voor de setup en het uitvoeren het spel
*
* @author Miguel
*/
public class PlayController {
private BorderPane borderPane;
private Player player1;
private Player player2;
private ComboBox p1ComboBox;
private ComboBox p2ComboBox;
private Button playButton;
private ObservableList players;
/**
* initialiseerd de play controller
*/
public void initialize() {
CreateNewPlayerController createNewPlayerController = new CreateNewPlayerController();
CreateNewPlayerView createNewPlayerView = new CreateNewPlayerView(createNewPlayerController);
players = FXCollections.observableList(ReadData.readDataFile("Player_Archive.dat"));
p1ComboBox.setItems(players);
p1ComboBox.setValue("Choose");
p1ComboBox.setOnAction(t -> {
onComboBoxChange();
});
p2ComboBox.setItems(players);
p2ComboBox.setValue("Choose");
p2ComboBox.setOnAction(t -> {
onComboBoxChange();
});
playButton.setOnAction(t -> {
System.out.println("play game");
TicTacToeController ticTacToeController = new TicTacToeController(player1, player2);
TicTacToeView ticTacToeView = new TicTacToeView(ticTacToeController);
borderPane = ticTacToeView.changeBorderPane(borderPane);
});
}
/**
* veranderd de visibility als de players een waarde hebben die niet hetzelfde zijn
*/
private void onComboBoxChange() {
if (!p1ComboBox.getValue().toString().equals("Choose")) {
player1 = (Player) p1ComboBox.getValue();
}
if (!p2ComboBox.getValue().toString().equals("Choose")) {
player2 = (Player) p2ComboBox.getValue();
}
playButton.setDisable(!(player1 != null && player2 != null && !player1.equals(player2)));
}
/**
* setter voor p1 combobox
* @param p1ComboBox
*/
public void setP1ComboBox(ComboBox p1ComboBox) {
this.p1ComboBox = p1ComboBox;
}
/**
* setter voor p2 combobox
* @param p2ComboBox
*/
public void setP2ComboBox(ComboBox p2ComboBox) {
this.p2ComboBox = p2ComboBox;
}
/**
* setter voor play button
* @param playButton
*/
public void setPlayButton(Button playButton) {
this.playButton = playButton;
}
/**
* setter voor borderpane
* @param borderPane
*/
public void setBorderPane(BorderPane borderPane) {
this.borderPane = borderPane;
}
}
| NoNamer777/hva-tic-tac-toe | src/controllers/PlayController.java | 900 | /**
* Zorgt voor de setup en het uitvoeren het spel
*
* @author Miguel
*/ | block_comment | nl | package controllers;
import data.ReadData;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.BorderPane;
import models.Player;
import views.CreateNewPlayerView;
import views.TicTacToeView;
/**
* Zorgt voor de<SUF>*/
public class PlayController {
private BorderPane borderPane;
private Player player1;
private Player player2;
private ComboBox p1ComboBox;
private ComboBox p2ComboBox;
private Button playButton;
private ObservableList players;
/**
* initialiseerd de play controller
*/
public void initialize() {
CreateNewPlayerController createNewPlayerController = new CreateNewPlayerController();
CreateNewPlayerView createNewPlayerView = new CreateNewPlayerView(createNewPlayerController);
players = FXCollections.observableList(ReadData.readDataFile("Player_Archive.dat"));
p1ComboBox.setItems(players);
p1ComboBox.setValue("Choose");
p1ComboBox.setOnAction(t -> {
onComboBoxChange();
});
p2ComboBox.setItems(players);
p2ComboBox.setValue("Choose");
p2ComboBox.setOnAction(t -> {
onComboBoxChange();
});
playButton.setOnAction(t -> {
System.out.println("play game");
TicTacToeController ticTacToeController = new TicTacToeController(player1, player2);
TicTacToeView ticTacToeView = new TicTacToeView(ticTacToeController);
borderPane = ticTacToeView.changeBorderPane(borderPane);
});
}
/**
* veranderd de visibility als de players een waarde hebben die niet hetzelfde zijn
*/
private void onComboBoxChange() {
if (!p1ComboBox.getValue().toString().equals("Choose")) {
player1 = (Player) p1ComboBox.getValue();
}
if (!p2ComboBox.getValue().toString().equals("Choose")) {
player2 = (Player) p2ComboBox.getValue();
}
playButton.setDisable(!(player1 != null && player2 != null && !player1.equals(player2)));
}
/**
* setter voor p1 combobox
* @param p1ComboBox
*/
public void setP1ComboBox(ComboBox p1ComboBox) {
this.p1ComboBox = p1ComboBox;
}
/**
* setter voor p2 combobox
* @param p2ComboBox
*/
public void setP2ComboBox(ComboBox p2ComboBox) {
this.p2ComboBox = p2ComboBox;
}
/**
* setter voor play button
* @param playButton
*/
public void setPlayButton(Button playButton) {
this.playButton = playButton;
}
/**
* setter voor borderpane
* @param borderPane
*/
public void setBorderPane(BorderPane borderPane) {
this.borderPane = borderPane;
}
}
| True | 629 | 22 | 724 | 28 | 731 | 23 | 724 | 28 | 829 | 25 | false | false | false | false | false | true |
3,400 | 43884_1 | package nerdygadgets.backoffice.main.JDBC;
import nerdygadgets.backoffice.main.data.Shaa256;
import java.sql.*;
public class Driver {
public static void main(String[] args) {
}
//Functies
//Functie adressen
public static ResultSet adressen() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT DeliveryInstructions FROM invoices");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//Zo lees je de gegevens uit
/*ResultSet myRs = Driver.adressen();
try {
while (myRs.next()) {
System.out.println(myRs.getString("DeliveryInstructions"));
System.out.println();
}
}
catch (Exception e) {
e.printStackTrace();
}*/
//Functie medewerkers
public static ResultSet medewerkers() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT FullName, EmailAddress, PhoneNumber FROM people");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static ResultSet login(String username, String password) {
try {
password = Shaa256.toHexString(Shaa256.getSHA(password));
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
String sql = "SELECT COUNT(*) FROM people WHERE LogonName = ? AND fixedpassword = ?";
PreparedStatement ps = myConn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
ResultSet myRs = ps.executeQuery();
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//Zo lees je de gegevens uit
/*ResultSet myRs = Driver.medewerkers();
try {
while (myRs.next()) {
System.out.println(myRs.getString("FullName"));
System.out.println(myRs.getString("EmailAddress"));
System.out.println(myRs.getString("PhoneNumber"));
System.out.println();
}
}
catch (Exception e) {
e.printStackTrace();
}*/
//Functie Orders
public static ResultSet orders() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT o.OrderID, c.CustomerName, ci.Cityname FROM orders o LEFT JOIN customers c ON o.CustomerID = c.CustomerID LEFT JOIN cities ci ON c.DeliveryCityID = ci.CityID ORDER BY OrderID");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static ResultSet getStock() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT o.StockItemID, o.StockItemName AS `Productnaam`, QuantityOnHand AS `Aantal`FROM wideworldimporters.stockitems o LEFT JOIN stockitemholdings sh ON o.StockItemID = sh.StockItemID ORDER BY o.StockItemID");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static ResultSet getCustomers() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT * FROM customer_ned");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void UpdateCustomer(String id, String cust, String city, String adres, String post, String email, String tel){
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
// create the java mysql update preparedstatement
String query = "UPDATE customer_ned SET CustomerName = ?, City = ?, Adres = ?, Postalcode = ?, EmailAddress = ?, TelephoneNumber = ? WHERE CustomerID = ?";
PreparedStatement preparedStmt = myConn.prepareStatement(query);
preparedStmt.setString(1, cust);
preparedStmt.setString(2, city);
preparedStmt.setString(3, adres);
preparedStmt.setString(4, post);
preparedStmt.setString(5, email);
preparedStmt.setString(6, tel);
preparedStmt.setString(7, id);
// execute the java preparedstatement
int rowsAffected = preparedStmt.executeUpdate();
System.out.println("Hoeveelheid rows veranderd: "+rowsAffected);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void UpdateVoorraad(String id, String itemname, String Quantity){ //Moet nog iets gebeuren als 1 niet werkt
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
// create the java mysql update preparedstatement
String query1 = "UPDATE stockitems SET StockItemName = ? WHERE StockItemId = ?";
PreparedStatement preparedStmt1 = myConn.prepareStatement(query1);
preparedStmt1.setString(1, itemname);
preparedStmt1.setString(2, id);
int rowsAffected1 = preparedStmt1.executeUpdate();
String query2 = "UPDATE stockitemholdings SET QuantityOnHand = ? WHERE StockItemId = ?";
PreparedStatement preparedStmt2 = myConn.prepareStatement(query2);
preparedStmt2.setString(1, Quantity);
preparedStmt2.setString(2, id);
int rowsAffected2 = preparedStmt2.executeUpdate();
System.out.println("Hoeveelheid rows veranderd in tabel 1: "+rowsAffected1);
System.out.println("Hoeveelheid rows veranderd in tabel 2: "+rowsAffected2);
} catch (Exception e) {
e.printStackTrace();
}
}
} | krisBroekstra1/Nerdygadgets | src/nerdygadgets/backoffice/main/JDBC/Driver.java | 1,876 | //Zo lees je de gegevens uit | line_comment | nl | package nerdygadgets.backoffice.main.JDBC;
import nerdygadgets.backoffice.main.data.Shaa256;
import java.sql.*;
public class Driver {
public static void main(String[] args) {
}
//Functies
//Functie adressen
public static ResultSet adressen() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT DeliveryInstructions FROM invoices");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//Zo lees<SUF>
/*ResultSet myRs = Driver.adressen();
try {
while (myRs.next()) {
System.out.println(myRs.getString("DeliveryInstructions"));
System.out.println();
}
}
catch (Exception e) {
e.printStackTrace();
}*/
//Functie medewerkers
public static ResultSet medewerkers() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT FullName, EmailAddress, PhoneNumber FROM people");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static ResultSet login(String username, String password) {
try {
password = Shaa256.toHexString(Shaa256.getSHA(password));
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
String sql = "SELECT COUNT(*) FROM people WHERE LogonName = ? AND fixedpassword = ?";
PreparedStatement ps = myConn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
ResultSet myRs = ps.executeQuery();
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//Zo lees je de gegevens uit
/*ResultSet myRs = Driver.medewerkers();
try {
while (myRs.next()) {
System.out.println(myRs.getString("FullName"));
System.out.println(myRs.getString("EmailAddress"));
System.out.println(myRs.getString("PhoneNumber"));
System.out.println();
}
}
catch (Exception e) {
e.printStackTrace();
}*/
//Functie Orders
public static ResultSet orders() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT o.OrderID, c.CustomerName, ci.Cityname FROM orders o LEFT JOIN customers c ON o.CustomerID = c.CustomerID LEFT JOIN cities ci ON c.DeliveryCityID = ci.CityID ORDER BY OrderID");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static ResultSet getStock() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT o.StockItemID, o.StockItemName AS `Productnaam`, QuantityOnHand AS `Aantal`FROM wideworldimporters.stockitems o LEFT JOIN stockitemholdings sh ON o.StockItemID = sh.StockItemID ORDER BY o.StockItemID");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static ResultSet getCustomers() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT * FROM customer_ned");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void UpdateCustomer(String id, String cust, String city, String adres, String post, String email, String tel){
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
// create the java mysql update preparedstatement
String query = "UPDATE customer_ned SET CustomerName = ?, City = ?, Adres = ?, Postalcode = ?, EmailAddress = ?, TelephoneNumber = ? WHERE CustomerID = ?";
PreparedStatement preparedStmt = myConn.prepareStatement(query);
preparedStmt.setString(1, cust);
preparedStmt.setString(2, city);
preparedStmt.setString(3, adres);
preparedStmt.setString(4, post);
preparedStmt.setString(5, email);
preparedStmt.setString(6, tel);
preparedStmt.setString(7, id);
// execute the java preparedstatement
int rowsAffected = preparedStmt.executeUpdate();
System.out.println("Hoeveelheid rows veranderd: "+rowsAffected);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void UpdateVoorraad(String id, String itemname, String Quantity){ //Moet nog iets gebeuren als 1 niet werkt
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
// create the java mysql update preparedstatement
String query1 = "UPDATE stockitems SET StockItemName = ? WHERE StockItemId = ?";
PreparedStatement preparedStmt1 = myConn.prepareStatement(query1);
preparedStmt1.setString(1, itemname);
preparedStmt1.setString(2, id);
int rowsAffected1 = preparedStmt1.executeUpdate();
String query2 = "UPDATE stockitemholdings SET QuantityOnHand = ? WHERE StockItemId = ?";
PreparedStatement preparedStmt2 = myConn.prepareStatement(query2);
preparedStmt2.setString(1, Quantity);
preparedStmt2.setString(2, id);
int rowsAffected2 = preparedStmt2.executeUpdate();
System.out.println("Hoeveelheid rows veranderd in tabel 1: "+rowsAffected1);
System.out.println("Hoeveelheid rows veranderd in tabel 2: "+rowsAffected2);
} catch (Exception e) {
e.printStackTrace();
}
}
} | True | 1,370 | 11 | 1,493 | 8 | 1,593 | 7 | 1,493 | 8 | 1,855 | 11 | false | false | false | false | false | true |
4,369 | 60894_0 | package org.robolectric.gradle;
import static org.gradle.api.internal.artifacts.ArtifactAttributes.ARTIFACT_FORMAT;
import com.android.build.gradle.internal.dependency.ExtractAarTransform;
import com.google.common.base.Joiner;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.file.FileCollection;
import org.gradle.api.tasks.compile.JavaCompile;
/** Resolve aar dependencies into jars for non-Android projects. */
public class AarDepsPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
project
.getDependencies()
.registerTransform(
reg -> {
reg.getFrom().attribute(ARTIFACT_FORMAT, "aar");
reg.getTo().attribute(ARTIFACT_FORMAT, "jar");
reg.artifactTransform(ClassesJarExtractor.class);
});
project.afterEvaluate(
p ->
project
.getConfigurations()
.forEach(
c -> {
// I suspect we're meant to use the org.gradle.usage attribute, but this
// works.
if (c.getName().endsWith("Classpath")) {
c.attributes(cfgAttrs -> cfgAttrs.attribute(ARTIFACT_FORMAT, "jar"));
}
}));
// warn if any AARs do make it through somehow; there must be a gradle configuration
// that isn't matched above.
project
.getTasks()
.withType(JavaCompile.class)
.all(
t -> {
t.doFirst(
task -> {
List<File> aarFiles = findAarFiles(t.getClasspath());
if (!aarFiles.isEmpty()) {
throw new IllegalStateException(
"AARs on classpath: " + Joiner.on("\n ").join(aarFiles));
}
});
});
}
private List<File> findAarFiles(FileCollection files) {
List<File> bad = new ArrayList<>();
for (File file : files.getFiles()) {
if (file.getName().toLowerCase().endsWith(".aar")) {
bad.add(file);
}
}
return bad;
}
static class ClassesJarExtractor extends ExtractAarTransform {
@Override
public List<File> transform(File input) {
List<File> out = super.transform(input);
File classesJar = new File(out.get(0), "jars/classes.jar");
// jar needs a quasi-unique name or IntelliJ Gradle/Android plugins get confused...
File renamed = new File(classesJar.getParent(), input.getName().replace(".aar", ".jar"));
classesJar.renameTo(renamed);
return Collections.singletonList(renamed);
}
}
}
| spotify/robolectric | buildSrc/src/main/groovy/org/robolectric/gradle/AarDepsPlugin.java | 811 | /** Resolve aar dependencies into jars for non-Android projects. */ | block_comment | nl | package org.robolectric.gradle;
import static org.gradle.api.internal.artifacts.ArtifactAttributes.ARTIFACT_FORMAT;
import com.android.build.gradle.internal.dependency.ExtractAarTransform;
import com.google.common.base.Joiner;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.file.FileCollection;
import org.gradle.api.tasks.compile.JavaCompile;
/** Resolve aar dependencies<SUF>*/
public class AarDepsPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
project
.getDependencies()
.registerTransform(
reg -> {
reg.getFrom().attribute(ARTIFACT_FORMAT, "aar");
reg.getTo().attribute(ARTIFACT_FORMAT, "jar");
reg.artifactTransform(ClassesJarExtractor.class);
});
project.afterEvaluate(
p ->
project
.getConfigurations()
.forEach(
c -> {
// I suspect we're meant to use the org.gradle.usage attribute, but this
// works.
if (c.getName().endsWith("Classpath")) {
c.attributes(cfgAttrs -> cfgAttrs.attribute(ARTIFACT_FORMAT, "jar"));
}
}));
// warn if any AARs do make it through somehow; there must be a gradle configuration
// that isn't matched above.
project
.getTasks()
.withType(JavaCompile.class)
.all(
t -> {
t.doFirst(
task -> {
List<File> aarFiles = findAarFiles(t.getClasspath());
if (!aarFiles.isEmpty()) {
throw new IllegalStateException(
"AARs on classpath: " + Joiner.on("\n ").join(aarFiles));
}
});
});
}
private List<File> findAarFiles(FileCollection files) {
List<File> bad = new ArrayList<>();
for (File file : files.getFiles()) {
if (file.getName().toLowerCase().endsWith(".aar")) {
bad.add(file);
}
}
return bad;
}
static class ClassesJarExtractor extends ExtractAarTransform {
@Override
public List<File> transform(File input) {
List<File> out = super.transform(input);
File classesJar = new File(out.get(0), "jars/classes.jar");
// jar needs a quasi-unique name or IntelliJ Gradle/Android plugins get confused...
File renamed = new File(classesJar.getParent(), input.getName().replace(".aar", ".jar"));
classesJar.renameTo(renamed);
return Collections.singletonList(renamed);
}
}
}
| False | 574 | 14 | 662 | 15 | 714 | 13 | 662 | 15 | 794 | 16 | false | false | false | false | false | true |
2,215 | 29018_8 | /*
* EigenDecomposition.java
*
* Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* BEAST 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 BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.evomodel.substmodel;
import java.io.Serializable;
/**
* @author Andrew Rambaut
* @author Alexei Drummond
* @Author Marc A. Suchard
* @version $Id$
*/
public class EigenDecomposition implements Serializable {
public EigenDecomposition(double[] evec, double[] ievc, double[] eval) {
Evec = evec;
Ievc = ievc;
Eval = eval;
}
public EigenDecomposition copy() {
double[] evec = Evec.clone();
double[] ievc = Ievc.clone();
double[] eval = Eval.clone();
return new EigenDecomposition(evec, ievc, eval);
}
public EigenDecomposition transpose() {
// note: exchange e/ivec
int dim = (int) Math.sqrt(Ievc.length);
double[] evec = Ievc.clone();
transposeInPlace(evec, dim);
double[] ievc = Evec.clone();
transposeInPlace(ievc, dim);
double[] eval = Eval.clone();
return new EigenDecomposition(evec, ievc, eval);
}
private static void transposeInPlace(double[] matrix, int n) {
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int index1 = i * n + j;
int index2 = j * n + i;
double temp = matrix[index1];
matrix[index1] = matrix[index2];
matrix[index2] = temp;
}
}
}
/**
* This function returns the Eigen vectors.
* @return the array
*/
public final double[] getEigenVectors() {
return Evec;
}
/**
* This function returns the inverse Eigen vectors.
* @return the array
*/
public final double[] getInverseEigenVectors() {
return Ievc;
}
/**
* This function returns the Eigen values.
* @return the Eigen values
*/
public final double[] getEigenValues() {
return Eval;
}
/**
* This function returns the normalization factor
* @return normalization factor
*/
public final double getNormalization() { return normalization; }
/**
* This function rescales the eigen values; this is more stable than
* rescaling the original Q matrix, also O(stateCount) instead of O(stateCount^2)
*/
public void normalizeEigenValues(double scale) {
this.normalization = scale;
int dim = Eval.length;
for (int i = 0; i < dim; i++) {
Eval[i] /= scale;
}
}
// Eigenvalues, eigenvectors, and inverse eigenvectors
private final double[] Evec;
private final double[] Ievc;
private final double[] Eval;
private double normalization = 1.0;
}
| beast-dev/beast-mcmc | src/dr/evomodel/substmodel/EigenDecomposition.java | 1,060 | // Eigenvalues, eigenvectors, and inverse eigenvectors | line_comment | nl | /*
* EigenDecomposition.java
*
* Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* BEAST 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 BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.evomodel.substmodel;
import java.io.Serializable;
/**
* @author Andrew Rambaut
* @author Alexei Drummond
* @Author Marc A. Suchard
* @version $Id$
*/
public class EigenDecomposition implements Serializable {
public EigenDecomposition(double[] evec, double[] ievc, double[] eval) {
Evec = evec;
Ievc = ievc;
Eval = eval;
}
public EigenDecomposition copy() {
double[] evec = Evec.clone();
double[] ievc = Ievc.clone();
double[] eval = Eval.clone();
return new EigenDecomposition(evec, ievc, eval);
}
public EigenDecomposition transpose() {
// note: exchange e/ivec
int dim = (int) Math.sqrt(Ievc.length);
double[] evec = Ievc.clone();
transposeInPlace(evec, dim);
double[] ievc = Evec.clone();
transposeInPlace(ievc, dim);
double[] eval = Eval.clone();
return new EigenDecomposition(evec, ievc, eval);
}
private static void transposeInPlace(double[] matrix, int n) {
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int index1 = i * n + j;
int index2 = j * n + i;
double temp = matrix[index1];
matrix[index1] = matrix[index2];
matrix[index2] = temp;
}
}
}
/**
* This function returns the Eigen vectors.
* @return the array
*/
public final double[] getEigenVectors() {
return Evec;
}
/**
* This function returns the inverse Eigen vectors.
* @return the array
*/
public final double[] getInverseEigenVectors() {
return Ievc;
}
/**
* This function returns the Eigen values.
* @return the Eigen values
*/
public final double[] getEigenValues() {
return Eval;
}
/**
* This function returns the normalization factor
* @return normalization factor
*/
public final double getNormalization() { return normalization; }
/**
* This function rescales the eigen values; this is more stable than
* rescaling the original Q matrix, also O(stateCount) instead of O(stateCount^2)
*/
public void normalizeEigenValues(double scale) {
this.normalization = scale;
int dim = Eval.length;
for (int i = 0; i < dim; i++) {
Eval[i] /= scale;
}
}
// Eigenvalues, eigenvectors,<SUF>
private final double[] Evec;
private final double[] Ievc;
private final double[] Eval;
private double normalization = 1.0;
}
| False | 895 | 13 | 931 | 15 | 987 | 9 | 930 | 15 | 1,101 | 14 | false | false | false | false | false | true |
792 | 175575_7 | import java.util.Scanner;_x000D_
_x000D_
public class Exercise19 {_x000D_
public static void main(String[] args) {_x000D_
// INTERLEAVE_x000D_
Scanner console = new Scanner(System.in);_x000D_
_x000D_
System.out.print("First string: ");_x000D_
String first = console.nextLine();_x000D_
_x000D_
System.out.print("Second string: ");_x000D_
String second = console.nextLine();_x000D_
_x000D_
// 1. Write a loop to interleave two strings to form a new string._x000D_
// To interleave, during each loop take one character from the first string and add it to the result_x000D_
// and take one character from the second string and add it to the result._x000D_
// If there are no more characters available, don't add characters._x000D_
// 2. Print the result._x000D_
int max = Math.max(first.length(),second.length());_x000D_
String mix = "";_x000D_
for (int i = 0; i < max; i++) {_x000D_
if (i < Math.min(first.length(), second.length())) {_x000D_
mix += (Character.toString(first.charAt(i)) + Character.toString(second.charAt(i)));_x000D_
continue;_x000D_
}_x000D_
if (first.length() == max){_x000D_
mix += (Character.toString((first.charAt(i))));_x000D_
}_x000D_
if (second.length() == max){_x000D_
mix += (Character.toString((second.charAt(i))));_x000D_
}_x000D_
}_x000D_
System.out.println(mix);_x000D_
_x000D_
// Examples_x000D_
// "abc", "123" -> "a1b2c3"_x000D_
// "cat", "dog" -> "cdaotg"_x000D_
// "wonder", "o" -> "woonder"_x000D_
// "B", "igstar" -> "Bigstar"_x000D_
// "", "huh?" -> "huh?"_x000D_
// "wha?", "" -> "wha?"_x000D_
}_x000D_
}_x000D_
| JacobBMitchell/java-exercises-JacobMitchell | week-01/exercises/repetition-exercises/src/Exercise19.java | 479 | // "wonder", "o" -> "woonder"_x000D_ | line_comment | nl | import java.util.Scanner;_x000D_
_x000D_
public class Exercise19 {_x000D_
public static void main(String[] args) {_x000D_
// INTERLEAVE_x000D_
Scanner console = new Scanner(System.in);_x000D_
_x000D_
System.out.print("First string: ");_x000D_
String first = console.nextLine();_x000D_
_x000D_
System.out.print("Second string: ");_x000D_
String second = console.nextLine();_x000D_
_x000D_
// 1. Write a loop to interleave two strings to form a new string._x000D_
// To interleave, during each loop take one character from the first string and add it to the result_x000D_
// and take one character from the second string and add it to the result._x000D_
// If there are no more characters available, don't add characters._x000D_
// 2. Print the result._x000D_
int max = Math.max(first.length(),second.length());_x000D_
String mix = "";_x000D_
for (int i = 0; i < max; i++) {_x000D_
if (i < Math.min(first.length(), second.length())) {_x000D_
mix += (Character.toString(first.charAt(i)) + Character.toString(second.charAt(i)));_x000D_
continue;_x000D_
}_x000D_
if (first.length() == max){_x000D_
mix += (Character.toString((first.charAt(i))));_x000D_
}_x000D_
if (second.length() == max){_x000D_
mix += (Character.toString((second.charAt(i))));_x000D_
}_x000D_
}_x000D_
System.out.println(mix);_x000D_
_x000D_
// Examples_x000D_
// "abc", "123" -> "a1b2c3"_x000D_
// "cat", "dog" -> "cdaotg"_x000D_
// "wonder", "o"<SUF>
// "B", "igstar" -> "Bigstar"_x000D_
// "", "huh?" -> "huh?"_x000D_
// "wha?", "" -> "wha?"_x000D_
}_x000D_
}_x000D_
| False | 645 | 19 | 691 | 19 | 720 | 18 | 691 | 19 | 757 | 20 | false | false | false | false | false | true |
662 | 33859_6 | package nl.hu.husacct.game31.domein;
import java.util.*;
public class ComputerSpeler extends Speler{
private double[][][] kaartenTabel;
private Kaart[] kaartenIndex;
private Vector alleKaarten;
private Spel spel;
private int schuifCounter = 0;
public ComputerSpeler(String naam, int fices, Tafel tafel, Pot pot, KaartStapel kaartStapel, Spel spel)
{
super(naam,fices, tafel, pot);
this.alleKaarten = kaartStapel.getKaarten();
this.spel = spel;
vulKaartenTabel();
printTabel();
}
private void vulKaartenTabel()
{
kaartenIndex = new Kaart[32];
Vector kaarten = alleKaarten;
//kaarten ophalen en in een array plaatsen
int index = 0;
for(Iterator itr = kaarten.iterator();itr.hasNext();index++)
{
Kaart k = (Kaart) itr.next();
kaartenIndex[index] = k;
//System.out.println(index + " " + k.geefSymbool() + " " + k.geefGetal());
}
//kaartenTabel invullen, de coordinaten geven de index van de Kaart in de kaartenIndex aan
//op de locatie staat het aantal punten dat een combinatie oplevert
kaartenTabel = new double[32][32][32];
for(int i=0;i<32;i++)
{
for(int j=0;j<32;j++)
{
for(int k=0;k<32;k++)
{
//niet dezelfde kaart
if(kaartenIndex[i] != kaartenIndex[j] && kaartenIndex[i] != kaartenIndex[k] && kaartenIndex[j] != kaartenIndex[k])
{
//zelfde getal
String getalK1 = kaartenIndex[i].geefGetal();
String getalK2 = kaartenIndex[j].geefGetal();
String getalK3 = kaartenIndex[k].geefGetal();
if(getalK1.equals(getalK2) && getalK1.equals(getalK3) && getalK3.equals(getalK2))
{
kaartenTabel[i][j][k] = 30.5;
}
//zelfde kleur
String symbool = kaartenIndex[i].geefSymbool();
if(symbool.equals(kaartenIndex[j].geefSymbool()) && symbool.equals(kaartenIndex[k].geefSymbool()))
{
kaartenTabel[i][j][k] = kaartenIndex[i].geefWaarde() + kaartenIndex[j].geefWaarde() + kaartenIndex[k].geefWaarde();
}
else if(symbool.equals(kaartenIndex[j].geefSymbool()))
{
kaartenTabel[i][j][k] = kaartenIndex[i].geefWaarde() + kaartenIndex[j].geefWaarde();
}
else if(symbool.equals(kaartenIndex[k].geefSymbool()))
{
kaartenTabel[i][j][k] = kaartenIndex[i].geefWaarde() + kaartenIndex[k].geefWaarde();
}
else if(kaartenIndex[j].geefSymbool().equals(kaartenIndex[k].geefSymbool()))
{
kaartenTabel[i][j][k] = kaartenIndex[j].geefWaarde() + kaartenIndex[k].geefWaarde();
}
}
}
}
}
}
//de computerspeler krijgt de beurt
public void aanDeBeurt()
{
Vector opTafel = tafel.getKaarten();
Vector inHand = deelname.getKaarten();
double puntenOpTafel = zoekPunten(opTafel);
double puntenInHand = zoekPunten(inHand);
int[] indexHand = new int[3];
int[] indexTafel = new int[3];
for(int i=0;i<3;i++)
{
indexHand[i] = zoekIndex((Kaart)inHand.elementAt(i));
indexTafel[i] = zoekIndex((Kaart)opTafel.elementAt(i));
}
double[][] puntenTabel = combineer(indexHand, indexTafel);
int[] besteCoords = zoekCoordsBeste(puntenTabel);
double bestePunten = puntenTabel[besteCoords[0]][besteCoords[1]];
if(bestePunten > puntenOpTafel && bestePunten > puntenInHand)
{
//1kaart wisselen
tafel.selecteerKaart(besteCoords[1]);
deelname.selecteerKaart(besteCoords[0]);
spel.ruil1Kaart(deelname.getSelected(), tafel.getSelected());
}
else if(bestePunten < puntenOpTafel)
{
//alles wisselen
spel.ruil3Kaart();
schuifCounter = 0;
}
else if(bestePunten <= puntenInHand)
{
if(puntenInHand > 25 || schuifCounter == 2)
{
//pass
spel.pas();
}
else
{
//doorschuiven
schuifCounter++;
spel.doorSchuiven();
}
}
Vector handkaartjes = deelname.getKaarten();
for(int i=0;i<3;i++)
{
Kaart k = (Kaart)handkaartjes.elementAt(i);
System.out.println(k.geefSymbool() + " " + k.geefGetal());
}
}
//de computerspeler krijgt als eerste de beurt in een nieuwe ronde
public void eersteKeerInRonde()
{
schuifCounter = 0;
Vector inHand = deelname.getKaarten();
double puntenInHand = zoekPunten(inHand);
//kan er 30.5 worden gescoord met deze kaarten?
Vector kaarten = deelname.getKaarten();
Kaart krt1 = (Kaart) kaarten.elementAt(0);
Kaart krt2 = (Kaart) kaarten.elementAt(1);
Kaart krt3 = (Kaart) kaarten.elementAt(2);
if(puntenInHand == 31.0)
{
//doorschuiven
spel.doorSchuiven();
schuifCounter++;
}
else if(puntenInHand > 25)
{
//pass
spel.pas();
}
else if(krt1.geefGetal().equals(krt2.geefGetal()) || krt1.geefGetal().equals(krt3.geefGetal()) || krt2.geefGetal().equals(krt3.geefGetal()))
{
//kaarten bekijken
//zoek beste ruil
//aanDeBeurt heeft dezelfde functionaliteiten dus roep ik die hier aan
aanDeBeurt();
}
else if(puntenInHand == 0.0)
{
spel.ruil3Kaart();
}
}
private int[] zoekCoordsBeste(double[][] puntenTabel)
{
int[] coords = new int[2];
double grootste = 0;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(puntenTabel[i][j] > grootste)
{
coords[0] = i;
coords[1] = j;
}
}
}
return coords;
}
private double[][] combineer(int[] hand, int[] tafel)
{
double[][] tabel = new double[3][3];
for(int i=0;i<3;i++) //regel
{
for(int j=0;j<3;j++) //kolom
{
int[] combinatie = new int[3];
for(int k=0;k<3;k++)
{
if(k == i)
{
combinatie[k] = tafel[j];
}
else
{
combinatie[k] = hand[k];
}
}
tabel[i][j] = kaartenTabel[combinatie[0]][combinatie[1]][combinatie[2]];
}
}
return tabel;
}
private int zoekIndex(Kaart k)
{
int index = 0;
for(int i=0;i<32;i++)
{
if(kaartenIndex[i] == k)
{
return i;
}
}
return -1;
}
private double zoekPunten(Vector kaarten)
{
double aantalPunten = 0;
int[] index = new int[3];
index[0] = zoekIndex((Kaart)kaarten.elementAt(0));
index[1] = zoekIndex((Kaart)kaarten.elementAt(1));
index[2] = zoekIndex((Kaart)kaarten.elementAt(2));
aantalPunten = kaartenTabel[index[0]][index[1]][index[2]];
return aantalPunten;
}
private void printTabel()
{
for(int i=0;i<32;i++)
{
for(int j=0;j<32;j++)
{
for(int k=0;k<32;k++)
{
System.out.print(" " + kaartenTabel[i][j][k]);
}
System.out.print('\n');
}
System.out.print('\n');
}
}
}
| HUSACCT/SaccWithHusacctExample_Maven | src/main/java/nl/hu/husacct/game31/domein/ComputerSpeler.java | 2,758 | //de computerspeler krijgt als eerste de beurt in een nieuwe ronde | line_comment | nl | package nl.hu.husacct.game31.domein;
import java.util.*;
public class ComputerSpeler extends Speler{
private double[][][] kaartenTabel;
private Kaart[] kaartenIndex;
private Vector alleKaarten;
private Spel spel;
private int schuifCounter = 0;
public ComputerSpeler(String naam, int fices, Tafel tafel, Pot pot, KaartStapel kaartStapel, Spel spel)
{
super(naam,fices, tafel, pot);
this.alleKaarten = kaartStapel.getKaarten();
this.spel = spel;
vulKaartenTabel();
printTabel();
}
private void vulKaartenTabel()
{
kaartenIndex = new Kaart[32];
Vector kaarten = alleKaarten;
//kaarten ophalen en in een array plaatsen
int index = 0;
for(Iterator itr = kaarten.iterator();itr.hasNext();index++)
{
Kaart k = (Kaart) itr.next();
kaartenIndex[index] = k;
//System.out.println(index + " " + k.geefSymbool() + " " + k.geefGetal());
}
//kaartenTabel invullen, de coordinaten geven de index van de Kaart in de kaartenIndex aan
//op de locatie staat het aantal punten dat een combinatie oplevert
kaartenTabel = new double[32][32][32];
for(int i=0;i<32;i++)
{
for(int j=0;j<32;j++)
{
for(int k=0;k<32;k++)
{
//niet dezelfde kaart
if(kaartenIndex[i] != kaartenIndex[j] && kaartenIndex[i] != kaartenIndex[k] && kaartenIndex[j] != kaartenIndex[k])
{
//zelfde getal
String getalK1 = kaartenIndex[i].geefGetal();
String getalK2 = kaartenIndex[j].geefGetal();
String getalK3 = kaartenIndex[k].geefGetal();
if(getalK1.equals(getalK2) && getalK1.equals(getalK3) && getalK3.equals(getalK2))
{
kaartenTabel[i][j][k] = 30.5;
}
//zelfde kleur
String symbool = kaartenIndex[i].geefSymbool();
if(symbool.equals(kaartenIndex[j].geefSymbool()) && symbool.equals(kaartenIndex[k].geefSymbool()))
{
kaartenTabel[i][j][k] = kaartenIndex[i].geefWaarde() + kaartenIndex[j].geefWaarde() + kaartenIndex[k].geefWaarde();
}
else if(symbool.equals(kaartenIndex[j].geefSymbool()))
{
kaartenTabel[i][j][k] = kaartenIndex[i].geefWaarde() + kaartenIndex[j].geefWaarde();
}
else if(symbool.equals(kaartenIndex[k].geefSymbool()))
{
kaartenTabel[i][j][k] = kaartenIndex[i].geefWaarde() + kaartenIndex[k].geefWaarde();
}
else if(kaartenIndex[j].geefSymbool().equals(kaartenIndex[k].geefSymbool()))
{
kaartenTabel[i][j][k] = kaartenIndex[j].geefWaarde() + kaartenIndex[k].geefWaarde();
}
}
}
}
}
}
//de computerspeler krijgt de beurt
public void aanDeBeurt()
{
Vector opTafel = tafel.getKaarten();
Vector inHand = deelname.getKaarten();
double puntenOpTafel = zoekPunten(opTafel);
double puntenInHand = zoekPunten(inHand);
int[] indexHand = new int[3];
int[] indexTafel = new int[3];
for(int i=0;i<3;i++)
{
indexHand[i] = zoekIndex((Kaart)inHand.elementAt(i));
indexTafel[i] = zoekIndex((Kaart)opTafel.elementAt(i));
}
double[][] puntenTabel = combineer(indexHand, indexTafel);
int[] besteCoords = zoekCoordsBeste(puntenTabel);
double bestePunten = puntenTabel[besteCoords[0]][besteCoords[1]];
if(bestePunten > puntenOpTafel && bestePunten > puntenInHand)
{
//1kaart wisselen
tafel.selecteerKaart(besteCoords[1]);
deelname.selecteerKaart(besteCoords[0]);
spel.ruil1Kaart(deelname.getSelected(), tafel.getSelected());
}
else if(bestePunten < puntenOpTafel)
{
//alles wisselen
spel.ruil3Kaart();
schuifCounter = 0;
}
else if(bestePunten <= puntenInHand)
{
if(puntenInHand > 25 || schuifCounter == 2)
{
//pass
spel.pas();
}
else
{
//doorschuiven
schuifCounter++;
spel.doorSchuiven();
}
}
Vector handkaartjes = deelname.getKaarten();
for(int i=0;i<3;i++)
{
Kaart k = (Kaart)handkaartjes.elementAt(i);
System.out.println(k.geefSymbool() + " " + k.geefGetal());
}
}
//de computerspeler<SUF>
public void eersteKeerInRonde()
{
schuifCounter = 0;
Vector inHand = deelname.getKaarten();
double puntenInHand = zoekPunten(inHand);
//kan er 30.5 worden gescoord met deze kaarten?
Vector kaarten = deelname.getKaarten();
Kaart krt1 = (Kaart) kaarten.elementAt(0);
Kaart krt2 = (Kaart) kaarten.elementAt(1);
Kaart krt3 = (Kaart) kaarten.elementAt(2);
if(puntenInHand == 31.0)
{
//doorschuiven
spel.doorSchuiven();
schuifCounter++;
}
else if(puntenInHand > 25)
{
//pass
spel.pas();
}
else if(krt1.geefGetal().equals(krt2.geefGetal()) || krt1.geefGetal().equals(krt3.geefGetal()) || krt2.geefGetal().equals(krt3.geefGetal()))
{
//kaarten bekijken
//zoek beste ruil
//aanDeBeurt heeft dezelfde functionaliteiten dus roep ik die hier aan
aanDeBeurt();
}
else if(puntenInHand == 0.0)
{
spel.ruil3Kaart();
}
}
private int[] zoekCoordsBeste(double[][] puntenTabel)
{
int[] coords = new int[2];
double grootste = 0;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(puntenTabel[i][j] > grootste)
{
coords[0] = i;
coords[1] = j;
}
}
}
return coords;
}
private double[][] combineer(int[] hand, int[] tafel)
{
double[][] tabel = new double[3][3];
for(int i=0;i<3;i++) //regel
{
for(int j=0;j<3;j++) //kolom
{
int[] combinatie = new int[3];
for(int k=0;k<3;k++)
{
if(k == i)
{
combinatie[k] = tafel[j];
}
else
{
combinatie[k] = hand[k];
}
}
tabel[i][j] = kaartenTabel[combinatie[0]][combinatie[1]][combinatie[2]];
}
}
return tabel;
}
private int zoekIndex(Kaart k)
{
int index = 0;
for(int i=0;i<32;i++)
{
if(kaartenIndex[i] == k)
{
return i;
}
}
return -1;
}
private double zoekPunten(Vector kaarten)
{
double aantalPunten = 0;
int[] index = new int[3];
index[0] = zoekIndex((Kaart)kaarten.elementAt(0));
index[1] = zoekIndex((Kaart)kaarten.elementAt(1));
index[2] = zoekIndex((Kaart)kaarten.elementAt(2));
aantalPunten = kaartenTabel[index[0]][index[1]][index[2]];
return aantalPunten;
}
private void printTabel()
{
for(int i=0;i<32;i++)
{
for(int j=0;j<32;j++)
{
for(int k=0;k<32;k++)
{
System.out.print(" " + kaartenTabel[i][j][k]);
}
System.out.print('\n');
}
System.out.print('\n');
}
}
}
| True | 2,300 | 17 | 2,669 | 23 | 2,477 | 15 | 2,670 | 23 | 3,188 | 18 | false | false | false | false | false | true |
322 | 81720_14 | package com.chickenmobile.chickensorigins.client.renderers;
import com.chickenmobile.chickensorigins.ChickensOrigins;
import com.chickenmobile.chickensorigins.ChickensOriginsClient;
import com.chickenmobile.chickensorigins.client.models.ButterflyWingModel;
import com.chickenmobile.chickensorigins.client.particles.ParticlePixieDust;
import com.chickenmobile.chickensorigins.core.registry.ModParticles;
import com.chickenmobile.chickensorigins.util.WingsData;
import net.minecraft.client.render.OverlayTexture;
import net.minecraft.client.render.RenderLayer;
import net.minecraft.client.render.VertexConsumer;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.entity.feature.FeatureRenderer;
import net.minecraft.client.render.entity.feature.FeatureRendererContext;
import net.minecraft.client.render.entity.model.EntityModel;
import net.minecraft.client.render.entity.model.EntityModelLoader;
import net.minecraft.client.render.item.ItemRenderer;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.DyeColor;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.random.Random;
public class WingsFeatureRenderer<T extends LivingEntity, M extends EntityModel<T>> extends FeatureRenderer<T, M> {
private final ButterflyWingModel<T> butterflyWings;
private long lastRenderTime;
private final int sparkleRenderDelay = 10;
public WingsFeatureRenderer(FeatureRendererContext<T, M> context, EntityModelLoader loader) {
super(context);
this.butterflyWings = new ButterflyWingModel<>(loader.getModelPart(ChickensOriginsClient.BUTTERFLY));
}
@Override
public void render(MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, T entity, float limbAngle, float limbDistance, float tickDelta, float animationProgress, float headYaw, float headPitch) {
if (entity instanceof PlayerEntity player && ChickensOrigins.IS_PIXIE.test(player)) {
// Get wingType from wings data.
String wingType = WingsData.WINGS_DATA.WING_MAP.getOrDefault(player.getUuidAsString(), "none");
// 'None' is a valid, even for pixie. Don't render.
if (wingType == "none") {
return;
}
Identifier layer = new Identifier(ChickensOrigins.MOD_ID, "textures/entity/" + wingType + ".png");
matrices.push();
matrices.translate(0.0D, -0.5D, 0.2D);
this.getContextModel().copyStateTo(this.butterflyWings);
this.butterflyWings.setAngles(entity, limbAngle, limbDistance, animationProgress, headYaw, headPitch);
float[] color = DyeColor.WHITE.getColorComponents();
this.renderWings(matrices, vertexConsumers, RenderLayer.getEntityTranslucent(layer), light, color[0], color[1], color[2]);
matrices.pop();
// Render pixie sparkle.
renderParticles(player, wingType);
}
}
public void renderWings(MatrixStack matrices, VertexConsumerProvider vertexConsumers, RenderLayer renderLayer, int light, float r, float g, float b) {
VertexConsumer vertexConsumer = ItemRenderer.getArmorGlintConsumer(vertexConsumers, renderLayer, false, false);
this.butterflyWings.render(matrices, vertexConsumer, light, OverlayTexture.DEFAULT_UV, r, g, b, 0.9F);
}
// Unused for now
public void renderParticles(PlayerEntity player, String wingType) {
//Random rand = player.world.random;
// Don't render too many sparkles, render is 3x a tick (too much). This includes when game is paused in SP.
if (player.age != lastRenderTime && !player.isOnGround() && player.age % sparkleRenderDelay == 0) {
lastRenderTime = player.age;
// Create particle based on facing of player
// minecraft is off by 90deg for normal sin/cos circle mathos
// double yaw = Math.toRadians(player.getBodyYaw() - 90);
// double xCos = Math.cos(yaw);
// double zSin = Math.sin(yaw);
ParticlePixieDust.SparkleColor color = switch (wingType) {
case "birdwing", "green_spotted_triangle" -> ParticlePixieDust.SparkleColor.GREEN;
case "blue_morpho" -> ParticlePixieDust.SparkleColor.BLUE;
case "buckeye" -> ParticlePixieDust.SparkleColor.BROWN;
case "monarch" -> ParticlePixieDust.SparkleColor.ORANGE;
case "pink_rose" -> ParticlePixieDust.SparkleColor.PINK;
case "purple_emperor" -> ParticlePixieDust.SparkleColor.PURPLE;
case "red_lacewing" -> ParticlePixieDust.SparkleColor.RED;
case "tiger_swallowtail" -> ParticlePixieDust.SparkleColor.YELLOW;
default -> ParticlePixieDust.SparkleColor.WHITE;
};
// Create & Render the particle
// player.getWorld().addParticle(ModParticles.PARTICLE_PIXIE_DUST,
// player.getX() + (0.2F * xCos),
// player.getY() + 0.2F + 0.1F * rand.nextGaussian(),
// player.getZ() + (0.2F * zSin),
// color.r, color.g, color.b);
player.getWorld().addParticle(ModParticles.PARTICLE_PIXIE_DUST,
player.getParticleX(1.0),
player.getRandomBodyY(),
player.getParticleZ(1.0),
color.r, color.g, color.b);
// rand.nextGaussian()) * 0.005D
}
}
} | ChickenMobile/chickens-origins | src/main/java/com/chickenmobile/chickensorigins/client/renderers/WingsFeatureRenderer.java | 1,705 | // player.getZ() + (0.2F * zSin), | line_comment | nl | package com.chickenmobile.chickensorigins.client.renderers;
import com.chickenmobile.chickensorigins.ChickensOrigins;
import com.chickenmobile.chickensorigins.ChickensOriginsClient;
import com.chickenmobile.chickensorigins.client.models.ButterflyWingModel;
import com.chickenmobile.chickensorigins.client.particles.ParticlePixieDust;
import com.chickenmobile.chickensorigins.core.registry.ModParticles;
import com.chickenmobile.chickensorigins.util.WingsData;
import net.minecraft.client.render.OverlayTexture;
import net.minecraft.client.render.RenderLayer;
import net.minecraft.client.render.VertexConsumer;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.entity.feature.FeatureRenderer;
import net.minecraft.client.render.entity.feature.FeatureRendererContext;
import net.minecraft.client.render.entity.model.EntityModel;
import net.minecraft.client.render.entity.model.EntityModelLoader;
import net.minecraft.client.render.item.ItemRenderer;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.DyeColor;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.random.Random;
public class WingsFeatureRenderer<T extends LivingEntity, M extends EntityModel<T>> extends FeatureRenderer<T, M> {
private final ButterflyWingModel<T> butterflyWings;
private long lastRenderTime;
private final int sparkleRenderDelay = 10;
public WingsFeatureRenderer(FeatureRendererContext<T, M> context, EntityModelLoader loader) {
super(context);
this.butterflyWings = new ButterflyWingModel<>(loader.getModelPart(ChickensOriginsClient.BUTTERFLY));
}
@Override
public void render(MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, T entity, float limbAngle, float limbDistance, float tickDelta, float animationProgress, float headYaw, float headPitch) {
if (entity instanceof PlayerEntity player && ChickensOrigins.IS_PIXIE.test(player)) {
// Get wingType from wings data.
String wingType = WingsData.WINGS_DATA.WING_MAP.getOrDefault(player.getUuidAsString(), "none");
// 'None' is a valid, even for pixie. Don't render.
if (wingType == "none") {
return;
}
Identifier layer = new Identifier(ChickensOrigins.MOD_ID, "textures/entity/" + wingType + ".png");
matrices.push();
matrices.translate(0.0D, -0.5D, 0.2D);
this.getContextModel().copyStateTo(this.butterflyWings);
this.butterflyWings.setAngles(entity, limbAngle, limbDistance, animationProgress, headYaw, headPitch);
float[] color = DyeColor.WHITE.getColorComponents();
this.renderWings(matrices, vertexConsumers, RenderLayer.getEntityTranslucent(layer), light, color[0], color[1], color[2]);
matrices.pop();
// Render pixie sparkle.
renderParticles(player, wingType);
}
}
public void renderWings(MatrixStack matrices, VertexConsumerProvider vertexConsumers, RenderLayer renderLayer, int light, float r, float g, float b) {
VertexConsumer vertexConsumer = ItemRenderer.getArmorGlintConsumer(vertexConsumers, renderLayer, false, false);
this.butterflyWings.render(matrices, vertexConsumer, light, OverlayTexture.DEFAULT_UV, r, g, b, 0.9F);
}
// Unused for now
public void renderParticles(PlayerEntity player, String wingType) {
//Random rand = player.world.random;
// Don't render too many sparkles, render is 3x a tick (too much). This includes when game is paused in SP.
if (player.age != lastRenderTime && !player.isOnGround() && player.age % sparkleRenderDelay == 0) {
lastRenderTime = player.age;
// Create particle based on facing of player
// minecraft is off by 90deg for normal sin/cos circle mathos
// double yaw = Math.toRadians(player.getBodyYaw() - 90);
// double xCos = Math.cos(yaw);
// double zSin = Math.sin(yaw);
ParticlePixieDust.SparkleColor color = switch (wingType) {
case "birdwing", "green_spotted_triangle" -> ParticlePixieDust.SparkleColor.GREEN;
case "blue_morpho" -> ParticlePixieDust.SparkleColor.BLUE;
case "buckeye" -> ParticlePixieDust.SparkleColor.BROWN;
case "monarch" -> ParticlePixieDust.SparkleColor.ORANGE;
case "pink_rose" -> ParticlePixieDust.SparkleColor.PINK;
case "purple_emperor" -> ParticlePixieDust.SparkleColor.PURPLE;
case "red_lacewing" -> ParticlePixieDust.SparkleColor.RED;
case "tiger_swallowtail" -> ParticlePixieDust.SparkleColor.YELLOW;
default -> ParticlePixieDust.SparkleColor.WHITE;
};
// Create & Render the particle
// player.getWorld().addParticle(ModParticles.PARTICLE_PIXIE_DUST,
// player.getX() + (0.2F * xCos),
// player.getY() + 0.2F + 0.1F * rand.nextGaussian(),
// player.getZ() +<SUF>
// color.r, color.g, color.b);
player.getWorld().addParticle(ModParticles.PARTICLE_PIXIE_DUST,
player.getParticleX(1.0),
player.getRandomBodyY(),
player.getParticleZ(1.0),
color.r, color.g, color.b);
// rand.nextGaussian()) * 0.005D
}
}
} | False | 1,284 | 15 | 1,581 | 17 | 1,469 | 16 | 1,581 | 17 | 1,849 | 22 | false | false | false | false | false | true |
1,264 | 122744_0 | import java.util.Scanner;
public class OnderdeelC {
// Alles onder de case die geselecteerd wordt zal uitgeprint worden dit komt omdat de code niet weet waar het moet stoppen door het ontbreken van een break
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Vul een maand in:\n");
int month = input.nextInt();
switch (month) {
case 1:
System.out.println("januari");
case 2:
System.out.println("februari");
case 3:
System.out.println("maart");
case 4:
System.out.println("april");
case 5:
System.out.println("mei");
case 6:
System.out.println("juni");
case 7:
System.out.println("juli");
case 8:
System.out.println("augustus");
case 9:
System.out.println("september");
case 10:
System.out.println("oktober");
case 11:
System.out.println("november");
case 12:
System.out.println("december");
default:
System.out.println("Geen geldige invoer");
}
}
}
| Owain94/IOPR-Java | Week2/Werkcolleges/opgave1/src/OnderdeelC.java | 366 | // Alles onder de case die geselecteerd wordt zal uitgeprint worden dit komt omdat de code niet weet waar het moet stoppen door het ontbreken van een break | line_comment | nl | import java.util.Scanner;
public class OnderdeelC {
// Alles onder<SUF>
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Vul een maand in:\n");
int month = input.nextInt();
switch (month) {
case 1:
System.out.println("januari");
case 2:
System.out.println("februari");
case 3:
System.out.println("maart");
case 4:
System.out.println("april");
case 5:
System.out.println("mei");
case 6:
System.out.println("juni");
case 7:
System.out.println("juli");
case 8:
System.out.println("augustus");
case 9:
System.out.println("september");
case 10:
System.out.println("oktober");
case 11:
System.out.println("november");
case 12:
System.out.println("december");
default:
System.out.println("Geen geldige invoer");
}
}
}
| True | 282 | 38 | 326 | 42 | 333 | 34 | 326 | 42 | 359 | 40 | false | false | false | false | false | true |
2,966 | 30795_0 | package nl.novi.uitleg.week2.io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Bestandslezer {
private static final String FILE_LOCATION = "src/nl/novi/uitleg/week2/io/bestand.txt";
/**
* Deze methode maakt een ArrayList<User> BufferedReader aan.
* De BufferedReader wordt vervolgens aan de readAllLines methode gegeven om het tekstbestand
* uit te lezen.
* @return lege of gevulde lijst met User-objecten.
*/
public static List<User> readFile() {
List<User> gebruikers = new ArrayList<>();
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(FILE_LOCATION));
gebruikers = readAllLines(bufferedReader);
} catch (IOException ioException) {
ioException.printStackTrace();
}
return gebruikers;
}
/**
* Deze methode is private en kan dus alleen in de Bestandlezer.java klasse aangeroepen worden.
*
* Deze code ontvangt een BufferedReader en gaat het tekstbestand dat daaronder hangt regel voor regel
* uitlezen.
*
* Daarna wordt de gelezen regel in een String[] array geplaatst. Vanuit deze array wordt uiteindelijk een
* User-object aangemaakt. Dit User-object wordt toegevoegd aan de list en uiteindelijk gereturned.
*
* Deze methode is eigenlijk te groot. Deze heeft te veel verantwoordlijkheden. Het maken van een object op basis
* van een String of Array zou ik bijvoorbeeld in een andere methode of klasse zetten.
* Kun je verzinnen hoe dat moet? Deze oplossing is meer het niveau van Java 1.
*
* @param bufferedReader De bufferedreader met een FileReader en de locatie naar het tekstbestand
* @return Lijst met user-objecten.
* @throws IOException wanneer er iets fout gaat in de IO-operatie.
*/
private static List<User> readAllLines(BufferedReader bufferedReader) throws IOException {
List<User> gebruikers = new ArrayList<>();
String line;
while((line = bufferedReader.readLine()) != null) {
String[] inhoudRegel = line.split("\\|");
String username = inhoudRegel[0];
String score = inhoudRegel[1].trim();
int scoreConverted;
try {
scoreConverted = Integer.parseInt(score);
} catch (NumberFormatException numberFormatException) {
scoreConverted = 0;
}
User user = new User(username, scoreConverted);
gebruikers.add(user);
}
return gebruikers;
}
/**
* Deze methode ontvangt een lijst met User-objecten. Deze worden met een methode uit het user-object omgevormd
* naar Strings die opgeslagen kunnen worden.
* @param users Lijst van users die opgeslagen moeten worden.
* @throws IOException wanneer er iets foutgaat met het opslaan.
*/
public static void save(List<User> users) throws IOException {
FileWriter writer = null;
try {
writer = new FileWriter(FILE_LOCATION);
for (User user : users) {
String lineToSave = user.getTextToSave();
writer.write(lineToSave + "\r\n");
}
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
writer.close();
}
}
/**
* Deze methode schrijft een lege String weg naar het tekstbestand. Alle data verdwijnt dus na het aanroepen van
* deze methode.
*
* Public methode, dus deze kan van buiten deze klasse aangeroepen worden.
*
* @throws IOException wanneer er iets fout gaat met het wegschrijven.
*/
public static void emptyFile() throws IOException {
FileWriter writer = null;
try {
writer = new FileWriter(FILE_LOCATION);
writer.write("");
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
writer.close();
}
}
}
| hogeschoolnovi/SD-BE-JP-oefenopdrachten | src/nl/novi/uitleg/week2/io/Bestandslezer.java | 1,170 | /**
* Deze methode maakt een ArrayList<User> BufferedReader aan.
* De BufferedReader wordt vervolgens aan de readAllLines methode gegeven om het tekstbestand
* uit te lezen.
* @return lege of gevulde lijst met User-objecten.
*/ | block_comment | nl | package nl.novi.uitleg.week2.io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Bestandslezer {
private static final String FILE_LOCATION = "src/nl/novi/uitleg/week2/io/bestand.txt";
/**
* Deze methode maakt<SUF>*/
public static List<User> readFile() {
List<User> gebruikers = new ArrayList<>();
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(FILE_LOCATION));
gebruikers = readAllLines(bufferedReader);
} catch (IOException ioException) {
ioException.printStackTrace();
}
return gebruikers;
}
/**
* Deze methode is private en kan dus alleen in de Bestandlezer.java klasse aangeroepen worden.
*
* Deze code ontvangt een BufferedReader en gaat het tekstbestand dat daaronder hangt regel voor regel
* uitlezen.
*
* Daarna wordt de gelezen regel in een String[] array geplaatst. Vanuit deze array wordt uiteindelijk een
* User-object aangemaakt. Dit User-object wordt toegevoegd aan de list en uiteindelijk gereturned.
*
* Deze methode is eigenlijk te groot. Deze heeft te veel verantwoordlijkheden. Het maken van een object op basis
* van een String of Array zou ik bijvoorbeeld in een andere methode of klasse zetten.
* Kun je verzinnen hoe dat moet? Deze oplossing is meer het niveau van Java 1.
*
* @param bufferedReader De bufferedreader met een FileReader en de locatie naar het tekstbestand
* @return Lijst met user-objecten.
* @throws IOException wanneer er iets fout gaat in de IO-operatie.
*/
private static List<User> readAllLines(BufferedReader bufferedReader) throws IOException {
List<User> gebruikers = new ArrayList<>();
String line;
while((line = bufferedReader.readLine()) != null) {
String[] inhoudRegel = line.split("\\|");
String username = inhoudRegel[0];
String score = inhoudRegel[1].trim();
int scoreConverted;
try {
scoreConverted = Integer.parseInt(score);
} catch (NumberFormatException numberFormatException) {
scoreConverted = 0;
}
User user = new User(username, scoreConverted);
gebruikers.add(user);
}
return gebruikers;
}
/**
* Deze methode ontvangt een lijst met User-objecten. Deze worden met een methode uit het user-object omgevormd
* naar Strings die opgeslagen kunnen worden.
* @param users Lijst van users die opgeslagen moeten worden.
* @throws IOException wanneer er iets foutgaat met het opslaan.
*/
public static void save(List<User> users) throws IOException {
FileWriter writer = null;
try {
writer = new FileWriter(FILE_LOCATION);
for (User user : users) {
String lineToSave = user.getTextToSave();
writer.write(lineToSave + "\r\n");
}
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
writer.close();
}
}
/**
* Deze methode schrijft een lege String weg naar het tekstbestand. Alle data verdwijnt dus na het aanroepen van
* deze methode.
*
* Public methode, dus deze kan van buiten deze klasse aangeroepen worden.
*
* @throws IOException wanneer er iets fout gaat met het wegschrijven.
*/
public static void emptyFile() throws IOException {
FileWriter writer = null;
try {
writer = new FileWriter(FILE_LOCATION);
writer.write("");
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
writer.close();
}
}
}
| True | 921 | 65 | 1,048 | 67 | 989 | 60 | 1,049 | 67 | 1,173 | 75 | false | false | false | false | false | true |
1,159 | 180433_6 | //package nl.hu.fnt.gsos.wsproducer;
//
//import javax.jws.WebService;
//
//@WebService(endpointInterface = "nl.hu.fnt.gsos.wsinterface.WSInterface")
//public class PowerserviceImpl implements WSInterface {
//
// @Override
//// public Response calculatePower(Request request) throws Fault_Exception {
//// ObjectFactory factory = new ObjectFactory();
//// Response response = factory.createResponse();
//// try {
//// Double result = Math.pow(request.getX().doubleValue(), request
//// .getPower().doubleValue());
//// // x en power zijn altijd gehele getallen dan is er geen afronding
//// long actualResult = result.longValue();
//// response.setResult(actualResult);
//// } catch (RuntimeException e) {
//// Fault x = factory.createFault();
//// x.setErrorCode((short) 1);
//// x.setMessage("Kan de macht van " + request.getX()
//// + " tot de macht " + request.getPower().toString()
//// + " niet berekenen.");
//// Fault_Exception fault = new Fault_Exception(
//// "Er ging iets mis met het berekenen van de power", x);
//// throw fault;
//// }
//// return response;
//// }
////
////}
| Murrx/EWDC | ws-parent/ws-producer/src/main/java/nl/hu/fnt/gsos/wsproducer/PowerserviceImpl.java | 343 | //// // x en power zijn altijd gehele getallen dan is er geen afronding | line_comment | nl | //package nl.hu.fnt.gsos.wsproducer;
//
//import javax.jws.WebService;
//
//@WebService(endpointInterface = "nl.hu.fnt.gsos.wsinterface.WSInterface")
//public class PowerserviceImpl implements WSInterface {
//
// @Override
//// public Response calculatePower(Request request) throws Fault_Exception {
//// ObjectFactory factory = new ObjectFactory();
//// Response response = factory.createResponse();
//// try {
//// Double result = Math.pow(request.getX().doubleValue(), request
//// .getPower().doubleValue());
//// // x en<SUF>
//// long actualResult = result.longValue();
//// response.setResult(actualResult);
//// } catch (RuntimeException e) {
//// Fault x = factory.createFault();
//// x.setErrorCode((short) 1);
//// x.setMessage("Kan de macht van " + request.getX()
//// + " tot de macht " + request.getPower().toString()
//// + " niet berekenen.");
//// Fault_Exception fault = new Fault_Exception(
//// "Er ging iets mis met het berekenen van de power", x);
//// throw fault;
//// }
//// return response;
//// }
////
////}
| True | 272 | 21 | 348 | 25 | 315 | 19 | 348 | 25 | 386 | 25 | false | false | false | false | false | true |
599 | 202128_0 | package ss.week6.voteMachine.gui;
import java.awt.Container;
import java.awt.FlowLayout;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
/**
* P2 prac wk3.
* UitslagJFrame: GUI voor een Uitslag.
* @author Arend Rensink en Theo Ruys
* @version 2005.02.15
*/
public class ResultJFrame extends JFrame {
// Grafische componenten
private JTextArea resultField;
private JLabel messageLabel;
/** Construeert een UitslagJFrame die een gegeven uitslag observeert. */
public ResultJFrame(VoteGUIView view) {
// Initialisatie grafische componenten
super("Result");
Container cc = getContentPane();
cc.setLayout(new FlowLayout());
messageLabel = new JLabel("Votes:");
cc.add(messageLabel);
resultField = new JTextArea("", 10, 20);
resultField.setEditable(false);
cc.add(resultField);
setSize(250, 255);
}
/** Zet de uitslag op het tekstveld, met 1 regel per partij. */
public void update(Map<String,Integer> votes) {
resultField.setText("");
for(Map.Entry<String,Integer> entry: votes.entrySet()){
resultField.append(entry.getKey() + ": " + entry.getValue() + "\n");
}
}
}
| GerjanWielink/software-systems | ss/src/main/java/ss/week6/voteMachine/gui/ResultJFrame.java | 415 | /**
* P2 prac wk3.
* UitslagJFrame: GUI voor een Uitslag.
* @author Arend Rensink en Theo Ruys
* @version 2005.02.15
*/ | block_comment | nl | package ss.week6.voteMachine.gui;
import java.awt.Container;
import java.awt.FlowLayout;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
/**
* P2 prac wk3.<SUF>*/
public class ResultJFrame extends JFrame {
// Grafische componenten
private JTextArea resultField;
private JLabel messageLabel;
/** Construeert een UitslagJFrame die een gegeven uitslag observeert. */
public ResultJFrame(VoteGUIView view) {
// Initialisatie grafische componenten
super("Result");
Container cc = getContentPane();
cc.setLayout(new FlowLayout());
messageLabel = new JLabel("Votes:");
cc.add(messageLabel);
resultField = new JTextArea("", 10, 20);
resultField.setEditable(false);
cc.add(resultField);
setSize(250, 255);
}
/** Zet de uitslag op het tekstveld, met 1 regel per partij. */
public void update(Map<String,Integer> votes) {
resultField.setText("");
for(Map.Entry<String,Integer> entry: votes.entrySet()){
resultField.append(entry.getKey() + ": " + entry.getValue() + "\n");
}
}
}
| False | 315 | 52 | 397 | 59 | 369 | 53 | 397 | 59 | 438 | 57 | false | false | false | false | false | true |
957 | 190590_3 | package nl.fontys.smpt42_1.fontysswipe.controller;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import nl.fontys.smpt42_1.fontysswipe.domain.Route;
import nl.fontys.smpt42_1.fontysswipe.domain.Teacher;
import nl.fontys.smpt42_1.fontysswipe.domain.interfaces.CompareAlgo;
import nl.fontys.smpt42_1.fontysswipe.util.FindRouteUtilKt;
/**
* @author SMPT42-1
*/
class CompareController {
private static CompareController instance;
private CompareController() {
// Marked private because the CompareController should never be instantianted outside this class.
}
public static CompareController getInstance() {
return instance == null ? instance = new CompareController() : instance;
}
/**
* Compare teacher methode compared alle docenten met 1 student en kijkt voor alle docenten welke docenten de beste match is.
*
* @param userPoints een hashmap met de studie profielen en het aantal punten dat de gebruiker daarbij heeft.
* @param comparables all comparable objects.
* @return een gesorteerde map van docenten met het aantal procenten dat matcht.
*/
List<Teacher> compareTeachers(List<Route> userPoints, List<Teacher> comparables) {
HashMap<String, Double> differenceMap = new HashMap<>();
HashMap<CompareAlgo, Double> resultMap = new HashMap<>();
List<Route> correctUserPoints = getCorrectUserPoints(userPoints);
for (CompareAlgo comparable : comparables) {
double result = 0;
Map<String, Integer> teachersMap = comparable.getPoints();
for (final Map.Entry<String, Integer> teacherEntry : teachersMap.entrySet()) {
Route route = FindRouteUtilKt.findRoute(teacherEntry.getKey(), correctUserPoints);
double difference = Math.abs(route.getUserPoints() - teacherEntry.getValue());
differenceMap.put(teacherEntry.getKey(), difference);
result = result + (differenceMap.get(route.getAbbreviation()) * (route.getUserPoints() * 0.1));
}
resultMap.put(comparable, result);
}
return new ArrayList(sortByValue(resultMap).keySet());
}
/**
* Compare teacher methode compared alle docenten met 1 student en kijkt voor alle docenten welke docenten de beste match is.
*
* @param userPoints een hashmap met de studie profielen en het aantal punten dat de gebruiker daarbij heeft.
* @param comparables all comparable objects.
* @return een gesorteerde map van docenten met het aantal procenten dat matcht.
*/
List<nl.fontys.smpt42_1.fontysswipe.domain.Activity> compareWorkshops(List<Route> userPoints, List<nl.fontys.smpt42_1.fontysswipe.domain.Activity> comparables) {
HashMap<String, Double> differenceMap = new HashMap<>();
HashMap<CompareAlgo, Double> resultMap = new HashMap<>();
List<Route> correctUserPoints = getCorrectUserPoints(userPoints);
for (CompareAlgo comparable : comparables) {
double result = 0;
Map<String, Integer> workshopsMap = comparable.getPoints();
for (final Map.Entry<String, Integer> teacherEntry : workshopsMap.entrySet()) {
Route route = FindRouteUtilKt.findRoute(teacherEntry.getKey(), correctUserPoints);
double difference = Math.abs(route.getUserPoints() - teacherEntry.getValue());
differenceMap.put(teacherEntry.getKey(), difference);
result = result + (differenceMap.get(route.getAbbreviation()) * (route.getUserPoints() * 0.1));
}
resultMap.put(comparable, result);
}
return new ArrayList(sortByValue(resultMap).keySet());
}
private List<Route> getCorrectUserPoints(List<Route> userPoints) {
List<Route> correctUserPoints = new ArrayList<Route>();
for (Route route : userPoints) {
route.setUserPoints(route.getUserPoints() / (route.getMaxPoints() / 10));
correctUserPoints.add(route);
}
return correctUserPoints;
}
private static Map<CompareAlgo, Double> sortByValue(Map<CompareAlgo, Double> unsortMap) {
List<Map.Entry<CompareAlgo, Double>> list = new LinkedList<Map.Entry<CompareAlgo, Double>>(unsortMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<CompareAlgo, Double>>() {
public int compare(Map.Entry<CompareAlgo, Double> o1,
Map.Entry<CompareAlgo, Double> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
Map<CompareAlgo, Double> sortedMap = new LinkedHashMap<CompareAlgo, Double>();
for (Map.Entry<CompareAlgo, Double> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
for (Map.Entry<CompareAlgo, Double> entry : sortedMap.entrySet()) {
System.out.println("Key : " + entry.getKey().getName()
+ " Value : " + entry.getValue());
}
return sortedMap;
}
}
| Laugslander/fontys-swipe | app/src/main/java/nl/fontys/smpt42_1/fontysswipe/controller/CompareController.java | 1,492 | /**
* Compare teacher methode compared alle docenten met 1 student en kijkt voor alle docenten welke docenten de beste match is.
*
* @param userPoints een hashmap met de studie profielen en het aantal punten dat de gebruiker daarbij heeft.
* @param comparables all comparable objects.
* @return een gesorteerde map van docenten met het aantal procenten dat matcht.
*/ | block_comment | nl | package nl.fontys.smpt42_1.fontysswipe.controller;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import nl.fontys.smpt42_1.fontysswipe.domain.Route;
import nl.fontys.smpt42_1.fontysswipe.domain.Teacher;
import nl.fontys.smpt42_1.fontysswipe.domain.interfaces.CompareAlgo;
import nl.fontys.smpt42_1.fontysswipe.util.FindRouteUtilKt;
/**
* @author SMPT42-1
*/
class CompareController {
private static CompareController instance;
private CompareController() {
// Marked private because the CompareController should never be instantianted outside this class.
}
public static CompareController getInstance() {
return instance == null ? instance = new CompareController() : instance;
}
/**
* Compare teacher methode compared alle docenten met 1 student en kijkt voor alle docenten welke docenten de beste match is.
*
* @param userPoints een hashmap met de studie profielen en het aantal punten dat de gebruiker daarbij heeft.
* @param comparables all comparable objects.
* @return een gesorteerde map van docenten met het aantal procenten dat matcht.
*/
List<Teacher> compareTeachers(List<Route> userPoints, List<Teacher> comparables) {
HashMap<String, Double> differenceMap = new HashMap<>();
HashMap<CompareAlgo, Double> resultMap = new HashMap<>();
List<Route> correctUserPoints = getCorrectUserPoints(userPoints);
for (CompareAlgo comparable : comparables) {
double result = 0;
Map<String, Integer> teachersMap = comparable.getPoints();
for (final Map.Entry<String, Integer> teacherEntry : teachersMap.entrySet()) {
Route route = FindRouteUtilKt.findRoute(teacherEntry.getKey(), correctUserPoints);
double difference = Math.abs(route.getUserPoints() - teacherEntry.getValue());
differenceMap.put(teacherEntry.getKey(), difference);
result = result + (differenceMap.get(route.getAbbreviation()) * (route.getUserPoints() * 0.1));
}
resultMap.put(comparable, result);
}
return new ArrayList(sortByValue(resultMap).keySet());
}
/**
* Compare teacher methode<SUF>*/
List<nl.fontys.smpt42_1.fontysswipe.domain.Activity> compareWorkshops(List<Route> userPoints, List<nl.fontys.smpt42_1.fontysswipe.domain.Activity> comparables) {
HashMap<String, Double> differenceMap = new HashMap<>();
HashMap<CompareAlgo, Double> resultMap = new HashMap<>();
List<Route> correctUserPoints = getCorrectUserPoints(userPoints);
for (CompareAlgo comparable : comparables) {
double result = 0;
Map<String, Integer> workshopsMap = comparable.getPoints();
for (final Map.Entry<String, Integer> teacherEntry : workshopsMap.entrySet()) {
Route route = FindRouteUtilKt.findRoute(teacherEntry.getKey(), correctUserPoints);
double difference = Math.abs(route.getUserPoints() - teacherEntry.getValue());
differenceMap.put(teacherEntry.getKey(), difference);
result = result + (differenceMap.get(route.getAbbreviation()) * (route.getUserPoints() * 0.1));
}
resultMap.put(comparable, result);
}
return new ArrayList(sortByValue(resultMap).keySet());
}
private List<Route> getCorrectUserPoints(List<Route> userPoints) {
List<Route> correctUserPoints = new ArrayList<Route>();
for (Route route : userPoints) {
route.setUserPoints(route.getUserPoints() / (route.getMaxPoints() / 10));
correctUserPoints.add(route);
}
return correctUserPoints;
}
private static Map<CompareAlgo, Double> sortByValue(Map<CompareAlgo, Double> unsortMap) {
List<Map.Entry<CompareAlgo, Double>> list = new LinkedList<Map.Entry<CompareAlgo, Double>>(unsortMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<CompareAlgo, Double>>() {
public int compare(Map.Entry<CompareAlgo, Double> o1,
Map.Entry<CompareAlgo, Double> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
Map<CompareAlgo, Double> sortedMap = new LinkedHashMap<CompareAlgo, Double>();
for (Map.Entry<CompareAlgo, Double> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
for (Map.Entry<CompareAlgo, Double> entry : sortedMap.entrySet()) {
System.out.println("Key : " + entry.getKey().getName()
+ " Value : " + entry.getValue());
}
return sortedMap;
}
}
| True | 1,160 | 101 | 1,334 | 110 | 1,341 | 96 | 1,334 | 110 | 1,534 | 107 | false | false | false | false | false | true |
745 | 14017_0 | package alphareversi.commands.receive;
import alphareversi.commands.CommandParser;
import alphareversi.commands.RecvCommand;
import java.util.HashMap;
/**
* Created by Joost van Berkel on 3/24/2016.
* Resultaat van een zet ontvangen, bericht naar beide spelers.
* S: SVR GAME MOVE {PLAYER: "--speler--", DETAILS: "--reactie spel op zet--", MOVE:"--zet--"}
* Er is een zet gedaan, dit bericht geeft aan wie deze gezet heeft,
* wat de reactie van het spel erop is
*/
public class RecvGameMoveCommand extends RecvCommand {
private String player;
private String details;
private String move;
/**
* Parse string to create a filled RecvGamelistCommand.
* @param command string containing server message
*/
public RecvGameMoveCommand(String command) {
String[] parts = command.split(" ", 4);
this.setType(parts[0]);
this.setMethod(parts[1]);
this.setAction(parts[2]);
HashMap objects = CommandParser.parseObjectMap(parts[3]);
this.setPlayer((String) objects.get("PLAYER"));
this.setDetails((String) objects.get("DETAILS"));
this.setMove((String) objects.get("MOVE"));
}
public String getPlayer() {
return player;
}
public void setPlayer(String player) {
this.player = player;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getMove() {
return move;
}
public void setMove(String move) {
this.move = move;
}
}
| IcyPalm/AlphaReversi | src/alphareversi/commands/receive/RecvGameMoveCommand.java | 480 | /**
* Created by Joost van Berkel on 3/24/2016.
* Resultaat van een zet ontvangen, bericht naar beide spelers.
* S: SVR GAME MOVE {PLAYER: "--speler--", DETAILS: "--reactie spel op zet--", MOVE:"--zet--"}
* Er is een zet gedaan, dit bericht geeft aan wie deze gezet heeft,
* wat de reactie van het spel erop is
*/ | block_comment | nl | package alphareversi.commands.receive;
import alphareversi.commands.CommandParser;
import alphareversi.commands.RecvCommand;
import java.util.HashMap;
/**
* Created by Joost<SUF>*/
public class RecvGameMoveCommand extends RecvCommand {
private String player;
private String details;
private String move;
/**
* Parse string to create a filled RecvGamelistCommand.
* @param command string containing server message
*/
public RecvGameMoveCommand(String command) {
String[] parts = command.split(" ", 4);
this.setType(parts[0]);
this.setMethod(parts[1]);
this.setAction(parts[2]);
HashMap objects = CommandParser.parseObjectMap(parts[3]);
this.setPlayer((String) objects.get("PLAYER"));
this.setDetails((String) objects.get("DETAILS"));
this.setMove((String) objects.get("MOVE"));
}
public String getPlayer() {
return player;
}
public void setPlayer(String player) {
this.player = player;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getMove() {
return move;
}
public void setMove(String move) {
this.move = move;
}
}
| True | 379 | 105 | 435 | 120 | 438 | 98 | 435 | 120 | 494 | 124 | false | false | false | false | false | true |
1,993 | 108485_13 |
import java.util.Scanner;
import java.text.DecimalFormat;
public class Freizeitpark {
public static Scanner scan = new Scanner(System.in);
public static int vergangeneZeit = 0;
public static int dauerImPark = 0;
public static void main(String[] args) {
// TODO Automatisch generierter Methodenstub
willkommen();
eintrittBezahlen();
durchDenParkSchlendern();
/*eisEssen();
achterbahnFahren();
wcBenutzen();
sichBetrinken();
parkVerlassen(); */
}
public static void willkommen() {
System.out.println("Willkommen in unserem Freizeitpark!");
}
public static void eintrittBezahlen() {
int preisFuerErwachsene = 20;
int preisFuerKinderu14 = 0;
double preisFuerKinder14u18 = preisFuerErwachsene * 0.75;
double preisFuerStudenten = preisFuerErwachsene * 0.75;
/* System.out.println("Ist der Besucher erwachsen, Student, Kind zwischen 14 und 18 oder Kind unter 14?");
String antwortDesBenutzers = scan.next();
if (antwortDesBenutzers.equalsIgnoreCase("erwachsen")) {
System.out.println("Sie muessen " + preisFuerErwachsene + " bezahlen.");
} else if (antwortDesBenutzers.equalsIgnoreCase("Kind unter 14 Jahre")) {
System.out.println("Fuer Kinder unter 14 Jahren ist der Eintritt kostenlos.");
} else if (antwortDesBenutzers.equalsIgnoreCase("Kind zwischen 14 und 18 Jahren")) {
System.out.println("Fuer Kinder zwischen 14 und 18 Jahren muessen Sie " + preisFuerKinder14u18 + "bezahlen.");
} else if (antwortDesBenutzers.equalsIgnoreCase("Student")){
System.out.println("Sie muessen " + preisFuerStudenten + " bezahlen.");
} */
System.out.println("Wie viele Eintrittskarten fuer Erwachsene moechten Sie kaufen?");
int anzahlErwachsene = scan.nextInt();
int gesamtpreisErwachsene = anzahlErwachsene * preisFuerErwachsene;
System.out.println("Fuer wie viele Kinder zwischen 14 und 18 Jahren moechten Sie Eintrittskarten kaufen?");
int anzahlKinder14u18 = scan.nextInt();
double gesamtpreisKinder14u18 = anzahlKinder14u18 * preisFuerKinder14u18;
System.out.println("Wie viele Eintrittskarten fuer Studenten moechten Sie kaufen?");
int anzahlStudenten = scan.nextInt();
double gesamtpreisStudenten = anzahlStudenten * preisFuerStudenten;
System.out.println("Fuer wie viele Kinder unter 14 Jahren moechten Sie Eintrittskarte haben?");
int anzahlKinderu14 = scan.nextInt();
int gesamtpreisKinderu14 = preisFuerKinderu14 * anzahlKinderu14;
double gesamtpreis = gesamtpreisErwachsene + gesamtpreisKinder14u18 + gesamtpreisStudenten + gesamtpreisKinderu14;
// Runden auf zwei Dezimalstellen
DecimalFormat df = new DecimalFormat("#.##");
String gerundeterGesamtpreis = df.format(gesamtpreis);
System.out.println("Gesamtpreis fuer die Eintrittskarten: " + gerundeterGesamtpreis + " Euro.");
System.out.println();
scan.nextLine();
}
public static void eisEssen() {
/*System.out.println("Wollen Sie Eis essen?");
String eisEssen = scan.next();
if (eisEssen.equalsIgnoreCase("ja")) { */
System.out.println("Wie viele Kugeln moechten Sie?");
int anzahlDerKugeln = scan.nextInt();
double preisProKugel = 1.20;
double endpreisFuerEis = anzahlDerKugeln * preisProKugel;
// Runden auf zwei Dezimalstellen
DecimalFormat df = new DecimalFormat("#.##");
String gerundeterBetragEis = df.format(endpreisFuerEis);
System.out.println("Sie muessen insgesamt " + gerundeterBetragEis + " Euro fuer das Eis bezahlen.");
//}
scan.nextLine();
}
// Zeiterfassung
public static void durchDenParkSchlendern() {
System.out.println("Wie lange moechten Sie durch den Park schlendern (in Minuten)?");
int dauerImPark = scan.nextInt();
int vergangeneZeit = 0;
System.out.println("Sie beginnen Ihren Spaziergang/Aufenthalt in unserem Park.");
// minutengenaue Erfassung der vergangenen Zeit
while (vergangeneZeit < dauerImPark) {
// Aktivitaeten im Park
System.out.println();
System.out.println("Was moechten Sie tun? Waehlen Sie eine von den 6 Optionen: ");
System.out.println("1. Eis kaufen");
System.out.println("2. Achterbahn fahren");
System.out.println("3. WC benutzen");
System.out.println("4. Sich betrinken");
System.out.println("5. Weiter durch den Park schlendern");
System.out.println("6. Park verlassen");
System.out.println();
int aktivitaet = scan.nextInt();
switch (aktivitaet) {
case 1:
eisEssen();
vergangeneZeit += 5;
break;
case 2:
achterbahnFahren();
vergangeneZeit += 10;
break;
case 3:
wcBenutzen();
vergangeneZeit += 5;
break;
case 4:
sichBetrinken();
vergangeneZeit += 20;
break;
case 5:
durchDenParkSchlendern();
vergangeneZeit += 10;
break;
case 6:
parkVerlassen();
vergangeneZeit += 10;
break;
default:
System.out.println("Ungueltige Benutzereingabe. Bitte waehlen Sie eine der 6 Optionen.");
}
// vergangeneZeit++;
System.out.println("Vergangene Zeit: " + vergangeneZeit + "Minuten von " + dauerImPark + " Minuten.");
}
// nach abgelaufener Zeit
System.out.println();
System.out.println("Sie haben keine Zeit mehr.");
parkVerlassen();
}
public static void achterbahnFahren() {
/* System.out.println("Wollen Sie Achterbahn fahren?");
String achterbahnFahren = scan.next();
if (achterbahnFahren.equalsIgnoreCase("ja")) { */
System.out.println("Wie viele wollen Achterbahn fahren?");
int anzahlDerAchterbahnfahrenden = scan.nextInt();
double preisProFahrenden = 2.80;
double endpreisFuerAchterbahn = anzahlDerAchterbahnfahrenden * preisProFahrenden;
// Runden auf zwei Dezimalstellen
DecimalFormat df = new DecimalFormat("#.##");
String gerundeterBetragAchterbahn = df.format(endpreisFuerAchterbahn);
System.out.println("Sie muessen insgesamt " + gerundeterBetragAchterbahn + " Euro bezahlen.");
//}
scan.nextLine();
}
public static void wcBenutzen() {
/* System.out.println("Wollen Sie das WC benutzen?");
String wcBenutzen = scan.next();
if (wcBenutzen.equalsIgnoreCase("ja")) { */
System.out.println("Wie viele wollen das WC benutzen?");
int anzahlWCBenutzenden = scan.nextInt();
double preisWC = 0.70;
double endpreisFuerWC = anzahlWCBenutzenden * preisWC;
DecimalFormat df = new DecimalFormat("#.##");
String gerundeterBetragWC = df.format(endpreisFuerWC);
System.out.println("Sie muessen insgesamt " + gerundeterBetragWC + " Euro zahlen.");
// }
}
public static void sichBetrinken() {
/*System.out.println("Wollen Sie sich betrinken?");
String sichBetrinken = scan.next();
if (sichBetrinken.equalsIgnoreCase("ja")) { */
System.out.println("Sind Sie volljaehrig?");
String volljaehrigBetrinken = scan.next();
if (volljaehrigBetrinken.equalsIgnoreCase("ja")) {
String weiterTrinken;
do {
System.out.println("Wie viele wollen Sie sich betrinken?");
int anzahlSichBetrinkenden = scan.nextInt();
int preisAlkohol = 21;
int endpreisFuerAlkohol = anzahlSichBetrinkenden * preisAlkohol;
System.out.println("Sie muessen insgesamt " + endpreisFuerAlkohol + " Euro bezahlen.");
System.out.println("Wollen Sie noch etwas trinken?");
weiterTrinken = scan.next();
} while (weiterTrinken.equalsIgnoreCase("ja"));
}
//}
}
public static void parkVerlassen() {
/*System.out.println("Wollen Sie den Park verlassen?");
String parkVerlassen = scan.next();
if (parkVerlassen.equalsIgnoreCase("ja")) { */
System.out.println("Vielen Dank fuer Ihren Besuch in unserem Freizeitpark! Wir hoffen, Sie hatten eine tolle Zeit und freuen uns darauf, Sie bald wieder bei uns begruessen zu duerfen. Auf Wiedersehen!");
// }
}
}
| akkorismeglesz/Freizeitpark | Freizeitpark.java | 2,829 | /*System.out.println("Wollen Sie den Park verlassen?");
String parkVerlassen = scan.next();
if (parkVerlassen.equalsIgnoreCase("ja")) { */ | block_comment | nl |
import java.util.Scanner;
import java.text.DecimalFormat;
public class Freizeitpark {
public static Scanner scan = new Scanner(System.in);
public static int vergangeneZeit = 0;
public static int dauerImPark = 0;
public static void main(String[] args) {
// TODO Automatisch generierter Methodenstub
willkommen();
eintrittBezahlen();
durchDenParkSchlendern();
/*eisEssen();
achterbahnFahren();
wcBenutzen();
sichBetrinken();
parkVerlassen(); */
}
public static void willkommen() {
System.out.println("Willkommen in unserem Freizeitpark!");
}
public static void eintrittBezahlen() {
int preisFuerErwachsene = 20;
int preisFuerKinderu14 = 0;
double preisFuerKinder14u18 = preisFuerErwachsene * 0.75;
double preisFuerStudenten = preisFuerErwachsene * 0.75;
/* System.out.println("Ist der Besucher erwachsen, Student, Kind zwischen 14 und 18 oder Kind unter 14?");
String antwortDesBenutzers = scan.next();
if (antwortDesBenutzers.equalsIgnoreCase("erwachsen")) {
System.out.println("Sie muessen " + preisFuerErwachsene + " bezahlen.");
} else if (antwortDesBenutzers.equalsIgnoreCase("Kind unter 14 Jahre")) {
System.out.println("Fuer Kinder unter 14 Jahren ist der Eintritt kostenlos.");
} else if (antwortDesBenutzers.equalsIgnoreCase("Kind zwischen 14 und 18 Jahren")) {
System.out.println("Fuer Kinder zwischen 14 und 18 Jahren muessen Sie " + preisFuerKinder14u18 + "bezahlen.");
} else if (antwortDesBenutzers.equalsIgnoreCase("Student")){
System.out.println("Sie muessen " + preisFuerStudenten + " bezahlen.");
} */
System.out.println("Wie viele Eintrittskarten fuer Erwachsene moechten Sie kaufen?");
int anzahlErwachsene = scan.nextInt();
int gesamtpreisErwachsene = anzahlErwachsene * preisFuerErwachsene;
System.out.println("Fuer wie viele Kinder zwischen 14 und 18 Jahren moechten Sie Eintrittskarten kaufen?");
int anzahlKinder14u18 = scan.nextInt();
double gesamtpreisKinder14u18 = anzahlKinder14u18 * preisFuerKinder14u18;
System.out.println("Wie viele Eintrittskarten fuer Studenten moechten Sie kaufen?");
int anzahlStudenten = scan.nextInt();
double gesamtpreisStudenten = anzahlStudenten * preisFuerStudenten;
System.out.println("Fuer wie viele Kinder unter 14 Jahren moechten Sie Eintrittskarte haben?");
int anzahlKinderu14 = scan.nextInt();
int gesamtpreisKinderu14 = preisFuerKinderu14 * anzahlKinderu14;
double gesamtpreis = gesamtpreisErwachsene + gesamtpreisKinder14u18 + gesamtpreisStudenten + gesamtpreisKinderu14;
// Runden auf zwei Dezimalstellen
DecimalFormat df = new DecimalFormat("#.##");
String gerundeterGesamtpreis = df.format(gesamtpreis);
System.out.println("Gesamtpreis fuer die Eintrittskarten: " + gerundeterGesamtpreis + " Euro.");
System.out.println();
scan.nextLine();
}
public static void eisEssen() {
/*System.out.println("Wollen Sie Eis essen?");
String eisEssen = scan.next();
if (eisEssen.equalsIgnoreCase("ja")) { */
System.out.println("Wie viele Kugeln moechten Sie?");
int anzahlDerKugeln = scan.nextInt();
double preisProKugel = 1.20;
double endpreisFuerEis = anzahlDerKugeln * preisProKugel;
// Runden auf zwei Dezimalstellen
DecimalFormat df = new DecimalFormat("#.##");
String gerundeterBetragEis = df.format(endpreisFuerEis);
System.out.println("Sie muessen insgesamt " + gerundeterBetragEis + " Euro fuer das Eis bezahlen.");
//}
scan.nextLine();
}
// Zeiterfassung
public static void durchDenParkSchlendern() {
System.out.println("Wie lange moechten Sie durch den Park schlendern (in Minuten)?");
int dauerImPark = scan.nextInt();
int vergangeneZeit = 0;
System.out.println("Sie beginnen Ihren Spaziergang/Aufenthalt in unserem Park.");
// minutengenaue Erfassung der vergangenen Zeit
while (vergangeneZeit < dauerImPark) {
// Aktivitaeten im Park
System.out.println();
System.out.println("Was moechten Sie tun? Waehlen Sie eine von den 6 Optionen: ");
System.out.println("1. Eis kaufen");
System.out.println("2. Achterbahn fahren");
System.out.println("3. WC benutzen");
System.out.println("4. Sich betrinken");
System.out.println("5. Weiter durch den Park schlendern");
System.out.println("6. Park verlassen");
System.out.println();
int aktivitaet = scan.nextInt();
switch (aktivitaet) {
case 1:
eisEssen();
vergangeneZeit += 5;
break;
case 2:
achterbahnFahren();
vergangeneZeit += 10;
break;
case 3:
wcBenutzen();
vergangeneZeit += 5;
break;
case 4:
sichBetrinken();
vergangeneZeit += 20;
break;
case 5:
durchDenParkSchlendern();
vergangeneZeit += 10;
break;
case 6:
parkVerlassen();
vergangeneZeit += 10;
break;
default:
System.out.println("Ungueltige Benutzereingabe. Bitte waehlen Sie eine der 6 Optionen.");
}
// vergangeneZeit++;
System.out.println("Vergangene Zeit: " + vergangeneZeit + "Minuten von " + dauerImPark + " Minuten.");
}
// nach abgelaufener Zeit
System.out.println();
System.out.println("Sie haben keine Zeit mehr.");
parkVerlassen();
}
public static void achterbahnFahren() {
/* System.out.println("Wollen Sie Achterbahn fahren?");
String achterbahnFahren = scan.next();
if (achterbahnFahren.equalsIgnoreCase("ja")) { */
System.out.println("Wie viele wollen Achterbahn fahren?");
int anzahlDerAchterbahnfahrenden = scan.nextInt();
double preisProFahrenden = 2.80;
double endpreisFuerAchterbahn = anzahlDerAchterbahnfahrenden * preisProFahrenden;
// Runden auf zwei Dezimalstellen
DecimalFormat df = new DecimalFormat("#.##");
String gerundeterBetragAchterbahn = df.format(endpreisFuerAchterbahn);
System.out.println("Sie muessen insgesamt " + gerundeterBetragAchterbahn + " Euro bezahlen.");
//}
scan.nextLine();
}
public static void wcBenutzen() {
/* System.out.println("Wollen Sie das WC benutzen?");
String wcBenutzen = scan.next();
if (wcBenutzen.equalsIgnoreCase("ja")) { */
System.out.println("Wie viele wollen das WC benutzen?");
int anzahlWCBenutzenden = scan.nextInt();
double preisWC = 0.70;
double endpreisFuerWC = anzahlWCBenutzenden * preisWC;
DecimalFormat df = new DecimalFormat("#.##");
String gerundeterBetragWC = df.format(endpreisFuerWC);
System.out.println("Sie muessen insgesamt " + gerundeterBetragWC + " Euro zahlen.");
// }
}
public static void sichBetrinken() {
/*System.out.println("Wollen Sie sich betrinken?");
String sichBetrinken = scan.next();
if (sichBetrinken.equalsIgnoreCase("ja")) { */
System.out.println("Sind Sie volljaehrig?");
String volljaehrigBetrinken = scan.next();
if (volljaehrigBetrinken.equalsIgnoreCase("ja")) {
String weiterTrinken;
do {
System.out.println("Wie viele wollen Sie sich betrinken?");
int anzahlSichBetrinkenden = scan.nextInt();
int preisAlkohol = 21;
int endpreisFuerAlkohol = anzahlSichBetrinkenden * preisAlkohol;
System.out.println("Sie muessen insgesamt " + endpreisFuerAlkohol + " Euro bezahlen.");
System.out.println("Wollen Sie noch etwas trinken?");
weiterTrinken = scan.next();
} while (weiterTrinken.equalsIgnoreCase("ja"));
}
//}
}
public static void parkVerlassen() {
/*System.out.println("Wollen Sie den<SUF>*/
System.out.println("Vielen Dank fuer Ihren Besuch in unserem Freizeitpark! Wir hoffen, Sie hatten eine tolle Zeit und freuen uns darauf, Sie bald wieder bei uns begruessen zu duerfen. Auf Wiedersehen!");
// }
}
}
| False | 2,390 | 35 | 2,843 | 45 | 2,419 | 41 | 2,842 | 45 | 3,150 | 49 | false | false | false | false | false | true |
4,438 | 111029_1 | /*
* Syncany, www.syncany.org
* Copyright (C) 2011-2015 Philipp C. Heckel <philipp.heckel@gmail.com>
*
* 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.syncany.operations.up;
/**
* @author Jesse Donkervliet
*
*/
public class BlockingTransfersException extends Exception {
/**
*
*/
private static final long serialVersionUID = -7635231951027588892L;
}
| syncany/syncany-plugin-s3 | core/syncany-lib/src/main/java/org/syncany/operations/up/BlockingTransfersException.java | 290 | /**
* @author Jesse Donkervliet
*
*/ | block_comment | nl | /*
* Syncany, www.syncany.org
* Copyright (C) 2011-2015 Philipp C. Heckel <philipp.heckel@gmail.com>
*
* 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.syncany.operations.up;
/**
* @author Jesse Donkervliet<SUF>*/
public class BlockingTransfersException extends Exception {
/**
*
*/
private static final long serialVersionUID = -7635231951027588892L;
}
| False | 247 | 13 | 281 | 16 | 278 | 14 | 281 | 16 | 322 | 16 | false | false | false | false | false | true |
428 | 111105_4 | import javax.swing.plaf.nimbus.State;
import javax.xml.transform.Result;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ReizigerOracleDaoImpl extends OracleBaseDao implements ReizigerDao {
/**
* Returned alle reizigers.
* @return ArrayList<Reiziger>
*/
public List<Reiziger> findAll() {
try {
Statement stmt = getConnection().createStatement();
String query = "SELECT REIZIGERID, VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM FROM REIZIGER";
ResultSet rs = stmt.executeQuery(query);
ArrayList<Reiziger> reizigers = new ArrayList<Reiziger>();
while(rs.next()) {
reizigers.add(buildreizigerobject(rs));
}
return reizigers;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public Reiziger findById(int id) {
try {
String query = "SELECT REIZIGERID, VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM " +
"FROM REIZIGER " +
"WHERE REIZIGERID = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setInt(1, id);
ResultSet rs = stmt.executeQuery();
while(rs.next()) {
return buildreizigerobject(rs);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Returned alle reizigers met specifieke geboortedatum.
* @param GBdatum
* @return ArrayList<Reiziger>
*/
public List<Reiziger> findByGBdatum(Date GBdatum) {
try {
String query = "SELECT REIZIGERID, VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM " +
"FROM REIZIGER WHERE GEBOORTEDATUM = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setDate(1, GBdatum);
ResultSet rs = stmt.executeQuery();
ArrayList<Reiziger> reizigers = new ArrayList<Reiziger>();
while (rs.next()) {
reizigers.add(buildreizigerobject(rs));
}
return reizigers;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* Slaat een reiziger op.
* @param reiziger
* @return
*/
public Reiziger save(Reiziger reiziger) {
try {
String query = "INSERT INTO REIZIGER" +
"(VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM) VALUES " +
"(?, ?, ?, ?)";
String generatedColumns[] = { "REIZIGERID" };
PreparedStatement stmt = getConnection().prepareStatement(query, generatedColumns);
stmt.setString(1, reiziger.getVoorletters());
stmt.setString(2, reiziger.getTussenveogsel());
stmt.setString(3, reiziger.getAchternaam());
stmt.setDate(4, reiziger.getGeboortedatum());
stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
if(rs.next()) {
return findById(rs.getInt(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* Past een opgeslagen reiziger aan.
* @param reiziger
* @return Reiziger
*/
public Reiziger update(Reiziger reiziger) {
try {
String query =
"UPDATE REIZIGER SET " +
"VOORLETTERS = ?, TUSSENVOEGSEL = ?, ACHTERNAAM = ?, GEBOORTEDATUM = ? " +
"WHERE REIZIGERID = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setString(1, reiziger.getVoorletters());
stmt.setString(2, reiziger.getTussenveogsel());
stmt.setString(3, reiziger.getAchternaam());
stmt.setDate(4, reiziger.getGeboortedatum());
stmt.setInt(5, reiziger.getId());
ResultSet rs = stmt.executeQuery();
if (rs.rowUpdated()) {
return findById(reiziger.getId());
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* Verwijder een reiziger.
* @param reiziger
* @return boolean
*/
public boolean delete(Reiziger reiziger) {
try {
String query = "DELETE FROM REIZIGER WHERE REIZIGERID = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setInt(1, reiziger.getId());
int rs = stmt.executeUpdate();
return rs > 0;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
private Reiziger buildreizigerobject(ResultSet rs) throws SQLException {
int id = rs.getInt("REIZIGERID");
Reiziger reiziger = new Reiziger();
reiziger.setId(id);
reiziger.setVoorletters(rs.getString("VOORLETTERS"));
reiziger.setTussenveogsel(rs.getString("TUSSENVOEGSEL"));
reiziger.setAchternaam(rs.getString("ACHTERNAAM"));
reiziger.setGeboortedatum(rs.getDate("GEBOORTEDATUM"));
OVChipkaartDaoImpl ovdao = new OVChipkaartDaoImpl();
reiziger.setKaarten(ovdao.findByReiziger(id));
AdresDaoImpl adao = new AdresDaoImpl();
reiziger.setAdressen(adao.findByReiziger(id));
return reiziger;
}
}
| Donneh/ovcasus | src/ReizigerOracleDaoImpl.java | 1,772 | /**
* Verwijder een reiziger.
* @param reiziger
* @return boolean
*/ | block_comment | nl | import javax.swing.plaf.nimbus.State;
import javax.xml.transform.Result;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ReizigerOracleDaoImpl extends OracleBaseDao implements ReizigerDao {
/**
* Returned alle reizigers.
* @return ArrayList<Reiziger>
*/
public List<Reiziger> findAll() {
try {
Statement stmt = getConnection().createStatement();
String query = "SELECT REIZIGERID, VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM FROM REIZIGER";
ResultSet rs = stmt.executeQuery(query);
ArrayList<Reiziger> reizigers = new ArrayList<Reiziger>();
while(rs.next()) {
reizigers.add(buildreizigerobject(rs));
}
return reizigers;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public Reiziger findById(int id) {
try {
String query = "SELECT REIZIGERID, VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM " +
"FROM REIZIGER " +
"WHERE REIZIGERID = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setInt(1, id);
ResultSet rs = stmt.executeQuery();
while(rs.next()) {
return buildreizigerobject(rs);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Returned alle reizigers met specifieke geboortedatum.
* @param GBdatum
* @return ArrayList<Reiziger>
*/
public List<Reiziger> findByGBdatum(Date GBdatum) {
try {
String query = "SELECT REIZIGERID, VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM " +
"FROM REIZIGER WHERE GEBOORTEDATUM = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setDate(1, GBdatum);
ResultSet rs = stmt.executeQuery();
ArrayList<Reiziger> reizigers = new ArrayList<Reiziger>();
while (rs.next()) {
reizigers.add(buildreizigerobject(rs));
}
return reizigers;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* Slaat een reiziger op.
* @param reiziger
* @return
*/
public Reiziger save(Reiziger reiziger) {
try {
String query = "INSERT INTO REIZIGER" +
"(VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM) VALUES " +
"(?, ?, ?, ?)";
String generatedColumns[] = { "REIZIGERID" };
PreparedStatement stmt = getConnection().prepareStatement(query, generatedColumns);
stmt.setString(1, reiziger.getVoorletters());
stmt.setString(2, reiziger.getTussenveogsel());
stmt.setString(3, reiziger.getAchternaam());
stmt.setDate(4, reiziger.getGeboortedatum());
stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
if(rs.next()) {
return findById(rs.getInt(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* Past een opgeslagen reiziger aan.
* @param reiziger
* @return Reiziger
*/
public Reiziger update(Reiziger reiziger) {
try {
String query =
"UPDATE REIZIGER SET " +
"VOORLETTERS = ?, TUSSENVOEGSEL = ?, ACHTERNAAM = ?, GEBOORTEDATUM = ? " +
"WHERE REIZIGERID = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setString(1, reiziger.getVoorletters());
stmt.setString(2, reiziger.getTussenveogsel());
stmt.setString(3, reiziger.getAchternaam());
stmt.setDate(4, reiziger.getGeboortedatum());
stmt.setInt(5, reiziger.getId());
ResultSet rs = stmt.executeQuery();
if (rs.rowUpdated()) {
return findById(reiziger.getId());
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* Verwijder een reiziger.<SUF>*/
public boolean delete(Reiziger reiziger) {
try {
String query = "DELETE FROM REIZIGER WHERE REIZIGERID = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setInt(1, reiziger.getId());
int rs = stmt.executeUpdate();
return rs > 0;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
private Reiziger buildreizigerobject(ResultSet rs) throws SQLException {
int id = rs.getInt("REIZIGERID");
Reiziger reiziger = new Reiziger();
reiziger.setId(id);
reiziger.setVoorletters(rs.getString("VOORLETTERS"));
reiziger.setTussenveogsel(rs.getString("TUSSENVOEGSEL"));
reiziger.setAchternaam(rs.getString("ACHTERNAAM"));
reiziger.setGeboortedatum(rs.getDate("GEBOORTEDATUM"));
OVChipkaartDaoImpl ovdao = new OVChipkaartDaoImpl();
reiziger.setKaarten(ovdao.findByReiziger(id));
AdresDaoImpl adao = new AdresDaoImpl();
reiziger.setAdressen(adao.findByReiziger(id));
return reiziger;
}
}
| True | 1,325 | 27 | 1,460 | 26 | 1,457 | 27 | 1,456 | 26 | 1,768 | 29 | false | false | false | false | false | true |
3,923 | 140953_15 | package de.andlabs.teleporter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Handler;
import android.os.Parcelable;
import android.util.Log;
import de.andlabs.teleporter.plugin.ITeleporterPlugIn;
public class QueryMultiplexer {
private static final String TAG = "Multiplexer";
private Place orig;
private Place dest;
public ArrayList<Ride> rides;
public ArrayList<ITeleporterPlugIn> plugIns;
private ArrayList<Ride> nextRides;
private Map<String, Integer> priorities;
private long mLastSearchTimestamp;
private BroadcastReceiver mPluginResponseReceiver;
private final Context ctx;
private Handler mUpdateHandler;
private Thread worker;
public QueryMultiplexer(Context ctx, Place o, Place d) {
this.ctx = ctx;
orig = o;
dest = d;
nextRides = new ArrayList<Ride>();
rides = new ArrayList<Ride>() {
@Override
public boolean add(Ride object) {
if(!contains(object))
return super.add(object);
else
return false;
}
@Override
public boolean addAll(Collection<? extends Ride> collection) {
for(Ride r : collection)
if(!contains(r))
super.add(r);
return true;
}
@Override
public void add(int index, Ride object) {
if(!contains(object))
super.add(index, object);
}
};
plugIns = new ArrayList<ITeleporterPlugIn>();
SharedPreferences plugInSettings = ctx.getSharedPreferences("plugIns", ctx.MODE_PRIVATE);
try {
for (String p : plugInSettings.getAll().keySet()) {
Log.d(TAG, "plugin "+p);
if (plugInSettings.getBoolean(p, false)){
Log.d(TAG, "add plugin "+p);
plugIns.add((ITeleporterPlugIn) Class.forName("de.andlabs.teleporter.plugin."+p).newInstance());
}
}
} catch (Exception e) {
Log.e(TAG, "Schade!");
e.printStackTrace();
}
priorities = (Map<String, Integer>) ctx.getSharedPreferences("priorities", ctx.MODE_PRIVATE).getAll();
this.mUpdateHandler = new Handler();
this.mPluginResponseReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Plugin Response Received.");
final int duration = intent.getIntExtra("dur", -1);
final Ride ride = new Ride();
ride.duration = duration;
ride.orig = orig;
ride.dest = dest;
ride.mode = Ride.MODE_DRIVE;
ride.fun = 1;
ride.eco = 1;
ride.fast = 5;
ride.social = 1;
ride.green = 1;
mUpdateHandler.post(new Runnable() {
@Override
public void run() {
nextRides.add(ride);
}
});
}
};
this.ctx.registerReceiver(this.mPluginResponseReceiver, new IntentFilter("org.teleporter.intent.action.RECEIVE_RESPONSE"));
}
public boolean searchLater() {
// TODO just query just plugins that ...
// TODO use ThreadPoolExecutor ...
if (worker != null && worker.isAlive())
return false;
worker = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for (ITeleporterPlugIn p : plugIns) {
Log.d(TAG, "query plugin "+p);
final long requestTimestamp;
if(mLastSearchTimestamp == 0 ) {
requestTimestamp = System.currentTimeMillis();
} else {
requestTimestamp = mLastSearchTimestamp + 300000; // 5 Minutes
}
nextRides.addAll(p.find(orig, dest, new Date(requestTimestamp)));
mLastSearchTimestamp = requestTimestamp;
mUpdateHandler.post(new Runnable() {
@Override
public void run() {
rides.addAll(nextRides);
nextRides.clear();
((RidesActivity)ctx).datasetChanged();
}
});
}
Intent requestIntent = new Intent("org.teleporter.intent.action.RECEIVE_REQUEST");
requestIntent.putExtra("origLatitude", orig.lat);
requestIntent.putExtra("origLongitude", orig.lon);
requestIntent.putExtra("destLatitude", dest.lat);
requestIntent.putExtra("destLongitude", dest.lon);
ctx.sendBroadcast(requestIntent);
}
});
worker.start();
return true;
}
public void sort() {
priorities = (Map<String, Integer>) ctx.getSharedPreferences("priorities", ctx.MODE_PRIVATE).getAll();
// Collections.sort(rides, new Comparator<Ride>() {
//
// @Override
// public int compare(Ride r1, Ride r2) {
// // TODO Neue Faktor für Score: "Quickness" (Abfahrtszeit minus Jetzt)
// // TODO Faktoren normalisieren
// int score1= r1.fun * priorities.get("fun") +
// r1.eco * priorities.get("eco") +
// r1.fast * priorities.get("fast") +
// r1.green * priorities.get("green") +
// r1.social * priorities.get("social");
// int score2= r2.fun * priorities.get("fun") +
// r2.eco * priorities.get("eco") +
// r2.fast * priorities.get("fast") +
// r2.green * priorities.get("green") +
// r2.social * priorities.get("social");
// // Log.d("aha", "score1: "+score1 + ", score2: "+score2);
// if (score1 < score2)
// return 1;
// else if (score1 > score2)
// return -1;
// else {
// if (r1.dep.after(r2.dep))
// return 1;
// if (r1.dep.before(r2.dep))
// return -1;
// return 0;
// }
// }
// });
}
}
| orangeman/teleportr | src/de/andlabs/teleporter/QueryMultiplexer.java | 1,965 | // r2.green * priorities.get("green") + | line_comment | nl | package de.andlabs.teleporter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Handler;
import android.os.Parcelable;
import android.util.Log;
import de.andlabs.teleporter.plugin.ITeleporterPlugIn;
public class QueryMultiplexer {
private static final String TAG = "Multiplexer";
private Place orig;
private Place dest;
public ArrayList<Ride> rides;
public ArrayList<ITeleporterPlugIn> plugIns;
private ArrayList<Ride> nextRides;
private Map<String, Integer> priorities;
private long mLastSearchTimestamp;
private BroadcastReceiver mPluginResponseReceiver;
private final Context ctx;
private Handler mUpdateHandler;
private Thread worker;
public QueryMultiplexer(Context ctx, Place o, Place d) {
this.ctx = ctx;
orig = o;
dest = d;
nextRides = new ArrayList<Ride>();
rides = new ArrayList<Ride>() {
@Override
public boolean add(Ride object) {
if(!contains(object))
return super.add(object);
else
return false;
}
@Override
public boolean addAll(Collection<? extends Ride> collection) {
for(Ride r : collection)
if(!contains(r))
super.add(r);
return true;
}
@Override
public void add(int index, Ride object) {
if(!contains(object))
super.add(index, object);
}
};
plugIns = new ArrayList<ITeleporterPlugIn>();
SharedPreferences plugInSettings = ctx.getSharedPreferences("plugIns", ctx.MODE_PRIVATE);
try {
for (String p : plugInSettings.getAll().keySet()) {
Log.d(TAG, "plugin "+p);
if (plugInSettings.getBoolean(p, false)){
Log.d(TAG, "add plugin "+p);
plugIns.add((ITeleporterPlugIn) Class.forName("de.andlabs.teleporter.plugin."+p).newInstance());
}
}
} catch (Exception e) {
Log.e(TAG, "Schade!");
e.printStackTrace();
}
priorities = (Map<String, Integer>) ctx.getSharedPreferences("priorities", ctx.MODE_PRIVATE).getAll();
this.mUpdateHandler = new Handler();
this.mPluginResponseReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Plugin Response Received.");
final int duration = intent.getIntExtra("dur", -1);
final Ride ride = new Ride();
ride.duration = duration;
ride.orig = orig;
ride.dest = dest;
ride.mode = Ride.MODE_DRIVE;
ride.fun = 1;
ride.eco = 1;
ride.fast = 5;
ride.social = 1;
ride.green = 1;
mUpdateHandler.post(new Runnable() {
@Override
public void run() {
nextRides.add(ride);
}
});
}
};
this.ctx.registerReceiver(this.mPluginResponseReceiver, new IntentFilter("org.teleporter.intent.action.RECEIVE_RESPONSE"));
}
public boolean searchLater() {
// TODO just query just plugins that ...
// TODO use ThreadPoolExecutor ...
if (worker != null && worker.isAlive())
return false;
worker = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for (ITeleporterPlugIn p : plugIns) {
Log.d(TAG, "query plugin "+p);
final long requestTimestamp;
if(mLastSearchTimestamp == 0 ) {
requestTimestamp = System.currentTimeMillis();
} else {
requestTimestamp = mLastSearchTimestamp + 300000; // 5 Minutes
}
nextRides.addAll(p.find(orig, dest, new Date(requestTimestamp)));
mLastSearchTimestamp = requestTimestamp;
mUpdateHandler.post(new Runnable() {
@Override
public void run() {
rides.addAll(nextRides);
nextRides.clear();
((RidesActivity)ctx).datasetChanged();
}
});
}
Intent requestIntent = new Intent("org.teleporter.intent.action.RECEIVE_REQUEST");
requestIntent.putExtra("origLatitude", orig.lat);
requestIntent.putExtra("origLongitude", orig.lon);
requestIntent.putExtra("destLatitude", dest.lat);
requestIntent.putExtra("destLongitude", dest.lon);
ctx.sendBroadcast(requestIntent);
}
});
worker.start();
return true;
}
public void sort() {
priorities = (Map<String, Integer>) ctx.getSharedPreferences("priorities", ctx.MODE_PRIVATE).getAll();
// Collections.sort(rides, new Comparator<Ride>() {
//
// @Override
// public int compare(Ride r1, Ride r2) {
// // TODO Neue Faktor für Score: "Quickness" (Abfahrtszeit minus Jetzt)
// // TODO Faktoren normalisieren
// int score1= r1.fun * priorities.get("fun") +
// r1.eco * priorities.get("eco") +
// r1.fast * priorities.get("fast") +
// r1.green * priorities.get("green") +
// r1.social * priorities.get("social");
// int score2= r2.fun * priorities.get("fun") +
// r2.eco * priorities.get("eco") +
// r2.fast * priorities.get("fast") +
// r2.green *<SUF>
// r2.social * priorities.get("social");
// // Log.d("aha", "score1: "+score1 + ", score2: "+score2);
// if (score1 < score2)
// return 1;
// else if (score1 > score2)
// return -1;
// else {
// if (r1.dep.after(r2.dep))
// return 1;
// if (r1.dep.before(r2.dep))
// return -1;
// return 0;
// }
// }
// });
}
}
| False | 1,382 | 12 | 1,645 | 15 | 1,732 | 14 | 1,645 | 15 | 1,913 | 15 | false | false | false | false | false | true |
4,290 | 209699_18 | /*
* Static methods dealing with the Atmosphere
* =====================================================================
* This file is part of JSatTrak.
*
* Copyright 2007-2013 Shawn E. Gano
*
* 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 name.gano.astro;
import name.gano.astro.bodies.Sun;
/**
*
* @author sgano
*/
public class Atmosphere
{
/**
* Computes the acceleration due to the atmospheric drag.
* (uses modified Harris-Priester model)
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r Satellite position vector in the inertial system [m]
* @param v Satellite velocity vector in the inertial system [m/s]
* @param T Transformation matrix to true-of-date inertial system
* @param Area Cross-section [m^2]
* @param mass Spacecraft mass [kg]
* @param CD Drag coefficient
* @return Acceleration (a=d^2r/dt^2) [m/s^2]
*/
public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v,
final double[][] T, double Area, double mass, double CD)
{
// Constants
// Earth angular velocity vector [rad/s]
final double[] omega = {0.0, 0.0, 7.29212e-5};
// Variables
double v_abs, dens;
double[] r_tod = new double[3];
double[] v_tod = new double[3];
double[] v_rel = new double[3];
double[] a_tod = new double[3];
double[][] T_trp = new double[3][3];
// Transformation matrix to ICRF/EME2000 system
T_trp = MathUtils.transpose(T);
// Position and velocity in true-of-date system
r_tod = MathUtils.mult(T, r);
v_tod = MathUtils.mult(T, v);
// Velocity relative to the Earth's atmosphere
v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod));
v_abs = MathUtils.norm(v_rel);
// Atmospheric density due to modified Harris-Priester model
dens = Density_HP(Mjd_TT, r_tod);
// Acceleration
a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs);
return MathUtils.mult(T_trp, a_tod);
} // accellDrag
/**
* Computes the atmospheric density for the modified Harris-Priester model.
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r_tod Satellite position vector in the inertial system [m]
* @return Density [kg/m^3]
*/
public static double Density_HP(double Mjd_TT, final double[] r_tod)
{
// Constants
final double upper_limit = 1000.0; // Upper height limit [km]
final double lower_limit = 100.0; // Lower height limit [km]
final double ra_lag = 0.523599; // Right ascension lag [rad]
final int n_prm = 3; // Harris-Priester parameter
// 2(6) low(high) inclination
// Harris-Priester atmospheric density model parameters
// Height [km], minimum density, maximum density [gm/km^3]
final int N_Coef = 50;
final double[] h = {
100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0,
210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0,
320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0,
520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0,
720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0
};
final double[] c_min = {
4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03,
8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02,
9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01,
2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00,
2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01,
2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02,
4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02,
1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03,
1.560e-03, 1.150e-03
};
final double[] c_max = {
4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03,
8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02,
1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01,
4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00,
7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00,
1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01,
4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01,
1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02,
2.360e-02, 1.810e-02
};
// Variables
int i, ih; // Height section variables
double height; // Earth flattening
double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc.
double c_psi2; // Harris-Priester modification
double density, h_min, h_max, d_min, d_max;// Height, density parameters
double[] r_Sun = new double[3]; // Sun position
double[] u = new double[3]; // Apex of diurnal bulge
// Satellite height (in km)
height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km]
// Exit with zero density outside height model limits
if (height >= upper_limit || height <= lower_limit)
{
return 0.0;
}
// Sun right ascension, declination
r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT);
ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]);
dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2)));
// Unit vector u towards the apex of the diurnal bulge
// in inertial geocentric coordinates
c_dec = Math.cos(dec_Sun);
u[0] = c_dec * Math.cos(ra_Sun + ra_lag);
u[1] = c_dec * Math.sin(ra_Sun + ra_lag);
u[2] = Math.sin(dec_Sun);
// Cosine of half angle between satellite position vector and
// apex of diurnal bulge
c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod);
// Height index search and exponential density interpolation
ih = 0; // section index reset
for (i = 0; i < N_Coef - 1; i++) // loop over N_Coef height regimes
{
if (height >= h[i] && height < h[i + 1])
{
ih = i; // ih identifies height section
break;
}
}
h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]);
h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]);
d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min);
d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max);
// Density computation
density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm);
return density * 1.0e-12; // [kg/m^3]
} // Density_HP
}
| sgano/JSatTrak | src/name/gano/astro/Atmosphere.java | 3,164 | // Height, density parameters | line_comment | nl | /*
* Static methods dealing with the Atmosphere
* =====================================================================
* This file is part of JSatTrak.
*
* Copyright 2007-2013 Shawn E. Gano
*
* 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 name.gano.astro;
import name.gano.astro.bodies.Sun;
/**
*
* @author sgano
*/
public class Atmosphere
{
/**
* Computes the acceleration due to the atmospheric drag.
* (uses modified Harris-Priester model)
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r Satellite position vector in the inertial system [m]
* @param v Satellite velocity vector in the inertial system [m/s]
* @param T Transformation matrix to true-of-date inertial system
* @param Area Cross-section [m^2]
* @param mass Spacecraft mass [kg]
* @param CD Drag coefficient
* @return Acceleration (a=d^2r/dt^2) [m/s^2]
*/
public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v,
final double[][] T, double Area, double mass, double CD)
{
// Constants
// Earth angular velocity vector [rad/s]
final double[] omega = {0.0, 0.0, 7.29212e-5};
// Variables
double v_abs, dens;
double[] r_tod = new double[3];
double[] v_tod = new double[3];
double[] v_rel = new double[3];
double[] a_tod = new double[3];
double[][] T_trp = new double[3][3];
// Transformation matrix to ICRF/EME2000 system
T_trp = MathUtils.transpose(T);
// Position and velocity in true-of-date system
r_tod = MathUtils.mult(T, r);
v_tod = MathUtils.mult(T, v);
// Velocity relative to the Earth's atmosphere
v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod));
v_abs = MathUtils.norm(v_rel);
// Atmospheric density due to modified Harris-Priester model
dens = Density_HP(Mjd_TT, r_tod);
// Acceleration
a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs);
return MathUtils.mult(T_trp, a_tod);
} // accellDrag
/**
* Computes the atmospheric density for the modified Harris-Priester model.
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r_tod Satellite position vector in the inertial system [m]
* @return Density [kg/m^3]
*/
public static double Density_HP(double Mjd_TT, final double[] r_tod)
{
// Constants
final double upper_limit = 1000.0; // Upper height limit [km]
final double lower_limit = 100.0; // Lower height limit [km]
final double ra_lag = 0.523599; // Right ascension lag [rad]
final int n_prm = 3; // Harris-Priester parameter
// 2(6) low(high) inclination
// Harris-Priester atmospheric density model parameters
// Height [km], minimum density, maximum density [gm/km^3]
final int N_Coef = 50;
final double[] h = {
100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0,
210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0,
320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0,
520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0,
720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0
};
final double[] c_min = {
4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03,
8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02,
9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01,
2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00,
2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01,
2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02,
4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02,
1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03,
1.560e-03, 1.150e-03
};
final double[] c_max = {
4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03,
8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02,
1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01,
4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00,
7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00,
1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01,
4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01,
1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02,
2.360e-02, 1.810e-02
};
// Variables
int i, ih; // Height section variables
double height; // Earth flattening
double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc.
double c_psi2; // Harris-Priester modification
double density, h_min, h_max, d_min, d_max;// Height, density<SUF>
double[] r_Sun = new double[3]; // Sun position
double[] u = new double[3]; // Apex of diurnal bulge
// Satellite height (in km)
height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km]
// Exit with zero density outside height model limits
if (height >= upper_limit || height <= lower_limit)
{
return 0.0;
}
// Sun right ascension, declination
r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT);
ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]);
dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2)));
// Unit vector u towards the apex of the diurnal bulge
// in inertial geocentric coordinates
c_dec = Math.cos(dec_Sun);
u[0] = c_dec * Math.cos(ra_Sun + ra_lag);
u[1] = c_dec * Math.sin(ra_Sun + ra_lag);
u[2] = Math.sin(dec_Sun);
// Cosine of half angle between satellite position vector and
// apex of diurnal bulge
c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod);
// Height index search and exponential density interpolation
ih = 0; // section index reset
for (i = 0; i < N_Coef - 1; i++) // loop over N_Coef height regimes
{
if (height >= h[i] && height < h[i + 1])
{
ih = i; // ih identifies height section
break;
}
}
h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]);
h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]);
d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min);
d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max);
// Density computation
density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm);
return density * 1.0e-12; // [kg/m^3]
} // Density_HP
}
| False | 3,144 | 5 | 3,267 | 5 | 3,349 | 5 | 3,267 | 5 | 3,549 | 5 | false | false | false | false | false | true |
3,812 | 76776_3 | package org.color;
import org.liberty.android.fantastischmemo.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Resources;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.BlurMaskFilter.Blur;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.os.SystemClock;
import android.util.Log;
import android.util.StateSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class ColorDialog extends AlertDialog implements OnSeekBarChangeListener, OnClickListener {
public interface OnClickListener {
public void onClick(View view, int color);
}
private SeekBar mHue;
private SeekBar mSaturation;
private SeekBar mValue;
private ColorDialog.OnClickListener mListener;
private int mColor;
private View mView;
private GradientDrawable mPreviewDrawable;
public ColorDialog(Context context, View view, int color, OnClickListener listener) {
super(context);
mView = view;
mListener = listener;
Resources res = context.getResources();
setTitle(res.getText(R.string.color_dialog_title));
setButton(BUTTON_POSITIVE, res.getText(android.R.string.yes), this);
setButton(BUTTON_NEGATIVE, res.getText(android.R.string.cancel), this);
View root = LayoutInflater.from(context).inflate(R.layout.color_picker, null);
setView(root);
View preview = root.findViewById(R.id.preview);
mPreviewDrawable = new GradientDrawable();
// 2 pix more than color_picker_frame's radius
mPreviewDrawable.setCornerRadius(7);
Drawable[] layers = {
mPreviewDrawable,
res.getDrawable(R.drawable.color_picker_frame),
};
preview.setBackgroundDrawable(new LayerDrawable(layers));
mHue = (SeekBar) root.findViewById(R.id.hue);
mSaturation = (SeekBar) root.findViewById(R.id.saturation);
mValue = (SeekBar) root.findViewById(R.id.value);
mColor = color;
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
int h = (int) (hsv[0] * mHue.getMax() / 360);
int s = (int) (hsv[1] * mSaturation.getMax());
int v = (int) (hsv[2] * mValue.getMax());
setupSeekBar(mHue, R.string.color_h, h, res);
setupSeekBar(mSaturation, R.string.color_s, s, res);
setupSeekBar(mValue, R.string.color_v, v, res);
updatePreview(color);
}
private void setupSeekBar(SeekBar seekBar, int id, int value, Resources res) {
seekBar.setProgressDrawable(new TextSeekBarDrawable(res, id, value < seekBar.getMax() / 2));
seekBar.setProgress(value);
seekBar.setOnSeekBarChangeListener(this);
}
private void update() {
float[] hsv = {
360 * mHue.getProgress() / (float) mHue.getMax(),
mSaturation.getProgress() / (float) mSaturation.getMax(),
mValue.getProgress() / (float) mValue.getMax(),
};
mColor = Color.HSVToColor(hsv);
updatePreview(mColor);
}
private void updatePreview(int color) {
mPreviewDrawable.setColor(color);
mPreviewDrawable.invalidateSelf();
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
update();
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
mListener.onClick(mView, mColor);
}
dismiss();
}
static final int[] STATE_FOCUSED = {android.R.attr.state_focused};
static final int[] STATE_PRESSED = {android.R.attr.state_pressed};
class TextSeekBarDrawable extends Drawable implements Runnable {
private static final String TAG = "TextSeekBarDrawable";
private static final long DELAY = 25;
private String mText;
private Drawable mProgress;
private Paint mPaint;
private Paint mOutlinePaint;
private float mTextWidth;
private boolean mActive;
private float mTextX;
private float mDelta;
public TextSeekBarDrawable(Resources res, int id, boolean labelOnRight) {
mText = res.getString(id);
mProgress = res.getDrawable(android.R.drawable.progress_horizontal);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setTypeface(Typeface.DEFAULT_BOLD);
mPaint.setTextSize(16);
mPaint.setColor(0xff000000);
mOutlinePaint = new Paint(mPaint);
mOutlinePaint.setStyle(Style.STROKE);
mOutlinePaint.setStrokeWidth(3);
mOutlinePaint.setColor(0xbbffc300);
mOutlinePaint.setMaskFilter(new BlurMaskFilter(1, Blur.NORMAL));
mTextWidth = mOutlinePaint.measureText(mText);
mTextX = labelOnRight? 1 : 0;
}
@Override
protected void onBoundsChange(Rect bounds) {
mProgress.setBounds(bounds);
}
@Override
protected boolean onStateChange(int[] state) {
mActive = StateSet.stateSetMatches(STATE_FOCUSED, state) | StateSet.stateSetMatches(STATE_PRESSED, state);
invalidateSelf();
return false;
}
@Override
public boolean isStateful() {
return true;
}
@Override
protected boolean onLevelChange(int level) {
// Log.d(TAG, "onLevelChange " + level);
if (level < 4000 && mDelta <= 0) {
mDelta = 0.05f;
// Log.d(TAG, "onLevelChange scheduleSelf ++");
scheduleSelf(this, SystemClock.uptimeMillis() + DELAY);
} else
if (level > 6000 && mDelta >= 0) {
// Log.d(TAG, "onLevelChange scheduleSelf --");
mDelta = -0.05f;
scheduleSelf(this, SystemClock.uptimeMillis() + DELAY);
}
return mProgress.setLevel(level);
}
@Override
public void draw(Canvas canvas) {
mProgress.draw(canvas);
Rect bounds = getBounds();
float x = 6 + mTextX * (bounds.width() - mTextWidth - 6 - 6);
float y = (bounds.height() + mPaint.getTextSize()) / 2;
mOutlinePaint.setAlpha(mActive? 255 : 255 / 2);
mPaint.setAlpha(mActive? 255 : 255 / 2);
canvas.drawText(mText, x, y, mOutlinePaint);
canvas.drawText(mText, x, y, mPaint);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter cf) {
}
public void run() {
mTextX += mDelta;
if (mTextX >= 1) {
mTextX = 1;
mDelta = 0;
} else
if (mTextX <= 0) {
mTextX = 0;
mDelta = 0;
} else {
scheduleSelf(this, SystemClock.uptimeMillis() + DELAY);
}
invalidateSelf();
// Log.d(TAG, "run " + mTextX + " " + SystemClock.uptimeMillis());
}
}
}
| nicolas-raoul/AnyMemo | src/org/color/ColorDialog.java | 2,476 | // Log.d(TAG, "onLevelChange scheduleSelf --"); | line_comment | nl | package org.color;
import org.liberty.android.fantastischmemo.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Resources;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.BlurMaskFilter.Blur;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.os.SystemClock;
import android.util.Log;
import android.util.StateSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class ColorDialog extends AlertDialog implements OnSeekBarChangeListener, OnClickListener {
public interface OnClickListener {
public void onClick(View view, int color);
}
private SeekBar mHue;
private SeekBar mSaturation;
private SeekBar mValue;
private ColorDialog.OnClickListener mListener;
private int mColor;
private View mView;
private GradientDrawable mPreviewDrawable;
public ColorDialog(Context context, View view, int color, OnClickListener listener) {
super(context);
mView = view;
mListener = listener;
Resources res = context.getResources();
setTitle(res.getText(R.string.color_dialog_title));
setButton(BUTTON_POSITIVE, res.getText(android.R.string.yes), this);
setButton(BUTTON_NEGATIVE, res.getText(android.R.string.cancel), this);
View root = LayoutInflater.from(context).inflate(R.layout.color_picker, null);
setView(root);
View preview = root.findViewById(R.id.preview);
mPreviewDrawable = new GradientDrawable();
// 2 pix more than color_picker_frame's radius
mPreviewDrawable.setCornerRadius(7);
Drawable[] layers = {
mPreviewDrawable,
res.getDrawable(R.drawable.color_picker_frame),
};
preview.setBackgroundDrawable(new LayerDrawable(layers));
mHue = (SeekBar) root.findViewById(R.id.hue);
mSaturation = (SeekBar) root.findViewById(R.id.saturation);
mValue = (SeekBar) root.findViewById(R.id.value);
mColor = color;
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
int h = (int) (hsv[0] * mHue.getMax() / 360);
int s = (int) (hsv[1] * mSaturation.getMax());
int v = (int) (hsv[2] * mValue.getMax());
setupSeekBar(mHue, R.string.color_h, h, res);
setupSeekBar(mSaturation, R.string.color_s, s, res);
setupSeekBar(mValue, R.string.color_v, v, res);
updatePreview(color);
}
private void setupSeekBar(SeekBar seekBar, int id, int value, Resources res) {
seekBar.setProgressDrawable(new TextSeekBarDrawable(res, id, value < seekBar.getMax() / 2));
seekBar.setProgress(value);
seekBar.setOnSeekBarChangeListener(this);
}
private void update() {
float[] hsv = {
360 * mHue.getProgress() / (float) mHue.getMax(),
mSaturation.getProgress() / (float) mSaturation.getMax(),
mValue.getProgress() / (float) mValue.getMax(),
};
mColor = Color.HSVToColor(hsv);
updatePreview(mColor);
}
private void updatePreview(int color) {
mPreviewDrawable.setColor(color);
mPreviewDrawable.invalidateSelf();
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
update();
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
mListener.onClick(mView, mColor);
}
dismiss();
}
static final int[] STATE_FOCUSED = {android.R.attr.state_focused};
static final int[] STATE_PRESSED = {android.R.attr.state_pressed};
class TextSeekBarDrawable extends Drawable implements Runnable {
private static final String TAG = "TextSeekBarDrawable";
private static final long DELAY = 25;
private String mText;
private Drawable mProgress;
private Paint mPaint;
private Paint mOutlinePaint;
private float mTextWidth;
private boolean mActive;
private float mTextX;
private float mDelta;
public TextSeekBarDrawable(Resources res, int id, boolean labelOnRight) {
mText = res.getString(id);
mProgress = res.getDrawable(android.R.drawable.progress_horizontal);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setTypeface(Typeface.DEFAULT_BOLD);
mPaint.setTextSize(16);
mPaint.setColor(0xff000000);
mOutlinePaint = new Paint(mPaint);
mOutlinePaint.setStyle(Style.STROKE);
mOutlinePaint.setStrokeWidth(3);
mOutlinePaint.setColor(0xbbffc300);
mOutlinePaint.setMaskFilter(new BlurMaskFilter(1, Blur.NORMAL));
mTextWidth = mOutlinePaint.measureText(mText);
mTextX = labelOnRight? 1 : 0;
}
@Override
protected void onBoundsChange(Rect bounds) {
mProgress.setBounds(bounds);
}
@Override
protected boolean onStateChange(int[] state) {
mActive = StateSet.stateSetMatches(STATE_FOCUSED, state) | StateSet.stateSetMatches(STATE_PRESSED, state);
invalidateSelf();
return false;
}
@Override
public boolean isStateful() {
return true;
}
@Override
protected boolean onLevelChange(int level) {
// Log.d(TAG, "onLevelChange " + level);
if (level < 4000 && mDelta <= 0) {
mDelta = 0.05f;
// Log.d(TAG, "onLevelChange scheduleSelf ++");
scheduleSelf(this, SystemClock.uptimeMillis() + DELAY);
} else
if (level > 6000 && mDelta >= 0) {
// Log.d(TAG, "onLevelChange<SUF>
mDelta = -0.05f;
scheduleSelf(this, SystemClock.uptimeMillis() + DELAY);
}
return mProgress.setLevel(level);
}
@Override
public void draw(Canvas canvas) {
mProgress.draw(canvas);
Rect bounds = getBounds();
float x = 6 + mTextX * (bounds.width() - mTextWidth - 6 - 6);
float y = (bounds.height() + mPaint.getTextSize()) / 2;
mOutlinePaint.setAlpha(mActive? 255 : 255 / 2);
mPaint.setAlpha(mActive? 255 : 255 / 2);
canvas.drawText(mText, x, y, mOutlinePaint);
canvas.drawText(mText, x, y, mPaint);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter cf) {
}
public void run() {
mTextX += mDelta;
if (mTextX >= 1) {
mTextX = 1;
mDelta = 0;
} else
if (mTextX <= 0) {
mTextX = 0;
mDelta = 0;
} else {
scheduleSelf(this, SystemClock.uptimeMillis() + DELAY);
}
invalidateSelf();
// Log.d(TAG, "run " + mTextX + " " + SystemClock.uptimeMillis());
}
}
}
| False | 1,758 | 14 | 2,178 | 17 | 2,118 | 16 | 2,178 | 17 | 2,615 | 19 | false | false | false | false | false | true |
2,068 | 99697_1 | package nl.antonsteenvoorden.ikpmd.ui;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import nl.antonsteenvoorden.ikpmd.R;
import nl.antonsteenvoorden.ikpmd.adapter.VakkenAdapter;
import nl.antonsteenvoorden.ikpmd.model.Module;
public class StandVanZakenFragment extends Fragment {
View rootView;
Context context;
ListView listAandacht;
VakkenAdapter vakkenAdapter;
private PieChart standVanZakenChart;
private int maxECTS;
ArrayList<Entry> yValues;
ArrayList<String> xValues;
List<Module> modules;
List<Module> vakkenAandacht;
public StandVanZakenFragment() {
yValues = new ArrayList<>();
xValues = new ArrayList<>();
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static StandVanZakenFragment newInstance() {
StandVanZakenFragment fragment = new StandVanZakenFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_stand_van_zaken, container, false);
listAandacht = (ListView) rootView.findViewById(R.id.stand_van_zaken_list);
vakkenAandacht = new ArrayList<>();
modules = new ArrayList<>();
modules = Module.getAll();
context = rootView.getContext();
calculateECTS();
initChart();
getData();
vakkenAdapter = new VakkenAdapter(context, R.layout.vakken_list_item, vakkenAandacht);
listAandacht.setAdapter(vakkenAdapter);
ButterKnife.bind(this, rootView);
return rootView;
}
@Override
public void onResume() {
super.onResume();
getData();
standVanZakenChart.animateY(1500);
}
public void initChart() {
standVanZakenChart = (PieChart) rootView.findViewById(R.id.chart);
standVanZakenChart.setDescription("");
standVanZakenChart.setTouchEnabled(false);
standVanZakenChart.setDrawSliceText(true);
standVanZakenChart.setDrawHoleEnabled(true);
standVanZakenChart.setHoleColorTransparent(true);
standVanZakenChart.setHoleRadius(85);
standVanZakenChart.setCenterTextColor(Color.rgb(0,188,186));
standVanZakenChart.setCenterText("0/0 \n Studiepunten behaald");
standVanZakenChart.setCenterTextSize(20);
standVanZakenChart.getLegend().setEnabled(false);
standVanZakenChart.animateY(1500);
}
public void calculateECTS() {
modules.clear();
modules = Module.getAll();
for(Module module : modules) {
this.maxECTS += module.getEcts();
}
}
public void getData() {
int tmpEcts = 0;
modules.clear();
vakkenAandacht.clear();
modules = Module.getAll();
for(Module module : modules) {
double tmpGrade = module.getGrade();
if(tmpGrade >= 5.5) {
tmpEcts += module.getEcts();
}
else if(module.isGradeSet() == 1 && tmpGrade <= 5.4){
vakkenAandacht.add(module);
}
}
setData(tmpEcts);
}
private void setData(int aantal) {
String label = (String) getString(R.string.stand_van_zaken_data);
standVanZakenChart.setCenterText(aantal + " / 60 \n"+ label );
if(xValues.size() >= 2 && yValues.size() >= 2) {
yValues.set(0, new Entry(aantal, 0));
yValues.set(1, new Entry(maxECTS-aantal, 1));
} else {
yValues.add(new Entry(aantal, 0));
yValues.add(new Entry(maxECTS - aantal, 1));
xValues.add("Behaalde ECTS");
xValues.add("Resterende ECTS");
}
ArrayList<Integer> colors = new ArrayList<>();
colors.add(Color.rgb(0 ,188,186)); // blue
colors.add(Color.rgb(35 ,10,78)); // deep purple
PieDataSet dataSet = new PieDataSet(yValues, "ECTS");
dataSet.setColors(colors);
dataSet.setDrawValues(false);
PieData data = new PieData(xValues, dataSet);
data.setDrawValues(false);
data.setValueTextSize(0.0f);
standVanZakenChart.setData(data); // bind dataset aan chart.
standVanZakenChart.invalidate(); // Aanroepen van een redraw
//redraw list view
listAandacht.invalidate();
Log.d("aantal ects ", Integer.toString(aantal));
}
}
| antonsteenvoorden/Studie-status | app/src/main/java/nl/antonsteenvoorden/ikpmd/ui/StandVanZakenFragment.java | 1,599 | // bind dataset aan chart. | line_comment | nl | package nl.antonsteenvoorden.ikpmd.ui;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import nl.antonsteenvoorden.ikpmd.R;
import nl.antonsteenvoorden.ikpmd.adapter.VakkenAdapter;
import nl.antonsteenvoorden.ikpmd.model.Module;
public class StandVanZakenFragment extends Fragment {
View rootView;
Context context;
ListView listAandacht;
VakkenAdapter vakkenAdapter;
private PieChart standVanZakenChart;
private int maxECTS;
ArrayList<Entry> yValues;
ArrayList<String> xValues;
List<Module> modules;
List<Module> vakkenAandacht;
public StandVanZakenFragment() {
yValues = new ArrayList<>();
xValues = new ArrayList<>();
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static StandVanZakenFragment newInstance() {
StandVanZakenFragment fragment = new StandVanZakenFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_stand_van_zaken, container, false);
listAandacht = (ListView) rootView.findViewById(R.id.stand_van_zaken_list);
vakkenAandacht = new ArrayList<>();
modules = new ArrayList<>();
modules = Module.getAll();
context = rootView.getContext();
calculateECTS();
initChart();
getData();
vakkenAdapter = new VakkenAdapter(context, R.layout.vakken_list_item, vakkenAandacht);
listAandacht.setAdapter(vakkenAdapter);
ButterKnife.bind(this, rootView);
return rootView;
}
@Override
public void onResume() {
super.onResume();
getData();
standVanZakenChart.animateY(1500);
}
public void initChart() {
standVanZakenChart = (PieChart) rootView.findViewById(R.id.chart);
standVanZakenChart.setDescription("");
standVanZakenChart.setTouchEnabled(false);
standVanZakenChart.setDrawSliceText(true);
standVanZakenChart.setDrawHoleEnabled(true);
standVanZakenChart.setHoleColorTransparent(true);
standVanZakenChart.setHoleRadius(85);
standVanZakenChart.setCenterTextColor(Color.rgb(0,188,186));
standVanZakenChart.setCenterText("0/0 \n Studiepunten behaald");
standVanZakenChart.setCenterTextSize(20);
standVanZakenChart.getLegend().setEnabled(false);
standVanZakenChart.animateY(1500);
}
public void calculateECTS() {
modules.clear();
modules = Module.getAll();
for(Module module : modules) {
this.maxECTS += module.getEcts();
}
}
public void getData() {
int tmpEcts = 0;
modules.clear();
vakkenAandacht.clear();
modules = Module.getAll();
for(Module module : modules) {
double tmpGrade = module.getGrade();
if(tmpGrade >= 5.5) {
tmpEcts += module.getEcts();
}
else if(module.isGradeSet() == 1 && tmpGrade <= 5.4){
vakkenAandacht.add(module);
}
}
setData(tmpEcts);
}
private void setData(int aantal) {
String label = (String) getString(R.string.stand_van_zaken_data);
standVanZakenChart.setCenterText(aantal + " / 60 \n"+ label );
if(xValues.size() >= 2 && yValues.size() >= 2) {
yValues.set(0, new Entry(aantal, 0));
yValues.set(1, new Entry(maxECTS-aantal, 1));
} else {
yValues.add(new Entry(aantal, 0));
yValues.add(new Entry(maxECTS - aantal, 1));
xValues.add("Behaalde ECTS");
xValues.add("Resterende ECTS");
}
ArrayList<Integer> colors = new ArrayList<>();
colors.add(Color.rgb(0 ,188,186)); // blue
colors.add(Color.rgb(35 ,10,78)); // deep purple
PieDataSet dataSet = new PieDataSet(yValues, "ECTS");
dataSet.setColors(colors);
dataSet.setDrawValues(false);
PieData data = new PieData(xValues, dataSet);
data.setDrawValues(false);
data.setValueTextSize(0.0f);
standVanZakenChart.setData(data); // bind dataset<SUF>
standVanZakenChart.invalidate(); // Aanroepen van een redraw
//redraw list view
listAandacht.invalidate();
Log.d("aantal ects ", Integer.toString(aantal));
}
}
| True | 1,193 | 6 | 1,405 | 6 | 1,439 | 6 | 1,405 | 6 | 1,617 | 6 | false | false | false | false | false | true |
4,451 | 209434_1 | package basic;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class GetParameterValues
*/
@WebServlet("/GetParameterValues")
public class GetParameterValues extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public GetParameterValues() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String[] whisky = request.getParameterValues("qualification");
for(int i=0; i<whisky.length; i++){
pw.println("<br>whisky : " + whisky[i]);}
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| tbarua1/uy | ServletTest/src/basic/GetParameterValues.java | 417 | /**
* @see HttpServlet#HttpServlet()
*/ | block_comment | nl | package basic;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class GetParameterValues
*/
@WebServlet("/GetParameterValues")
public class GetParameterValues extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
<SUF>*/
public GetParameterValues() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String[] whisky = request.getParameterValues("qualification");
for(int i=0; i<whisky.length; i++){
pw.println("<br>whisky : " + whisky[i]);}
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| False | 277 | 12 | 355 | 11 | 363 | 13 | 355 | 11 | 425 | 15 | false | false | false | false | false | true |
3,200 | 85648_5 | package nl.han.ica.spookrijder;
import nl.han.ica.OOPDProcessingEngineHAN.Objects.Sprite;
import nl.han.ica.OOPDProcessingEngineHAN.Objects.SpriteObject;
import nl.han.ica.OOPDProcessingEngineHAN.Sound.Sound;
public abstract class VerzamelObject extends SpriteObject {
private Spookrijder spookrijder;
private boolean aangeraakt = false;
private int breedte;
private int hoogte;
protected String geluidsnaam; // naam van geluidsbestand
public VerzamelObject(Spookrijder spookrijder, Sprite sprite) {
super(sprite);
this.spookrijder = spookrijder;
setxSpeed(-3);
}
/**
* Update
*
* Zet aangeraakt status en zichtbaarheid op basis van x positie.
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
@Override
public void update() {
if (this.getX() < (0 - this.getWidth())) {
this.setX(spookrijder.getWidth() + this.getWidth());
this.setAangeraakt(false);
this.setVisible(true);
}
}
/**
* Zet aangeraakt
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
public void setAangeraakt(boolean aangeraakt) {
this.aangeraakt = aangeraakt;
}
/**
* Verkrijg aangeraakt
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @return Aangeraakt-status van het object.
* @version 1.0
*/
public boolean getAangeraakt() {
return this.aangeraakt;
}
/**
* Verkrijg hoogte
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @return De hoogte van het object.
* @since 11-05-2018
* @version 1.0
*/
public float getHeight() {
return this.hoogte;
}
/**
* Verkrijg breedte
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @return De breedte van het object.
* @since 11-05-2018
* @version 1.0
*/
public float getWidth() {
return this.breedte;
}
/**
* Zet hoogte
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
public void setHeight(int hoogte) {
this.hoogte = hoogte;
}
/**
* Zet breedte
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
public void setWidth(int breedte) {
this.breedte = breedte;
}
/**
* Doe Geluid
*
* Initialiseert een geluidsobject en speelt deze af.
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
public void doeGeluid() {
Sound geluid = new Sound(spookrijder,
"src/main/java/nl/han/ica/spookrijder/media/" + this.geluidsnaam + ".mp3");
geluid.play();
}
}
| jeffreyvr/spookrijder | src/main/java/nl/han/ica/spookrijder/VerzamelObject.java | 1,032 | /**
* Verkrijg breedte
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @return De breedte van het object.
* @since 11-05-2018
* @version 1.0
*/ | block_comment | nl | package nl.han.ica.spookrijder;
import nl.han.ica.OOPDProcessingEngineHAN.Objects.Sprite;
import nl.han.ica.OOPDProcessingEngineHAN.Objects.SpriteObject;
import nl.han.ica.OOPDProcessingEngineHAN.Sound.Sound;
public abstract class VerzamelObject extends SpriteObject {
private Spookrijder spookrijder;
private boolean aangeraakt = false;
private int breedte;
private int hoogte;
protected String geluidsnaam; // naam van geluidsbestand
public VerzamelObject(Spookrijder spookrijder, Sprite sprite) {
super(sprite);
this.spookrijder = spookrijder;
setxSpeed(-3);
}
/**
* Update
*
* Zet aangeraakt status en zichtbaarheid op basis van x positie.
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
@Override
public void update() {
if (this.getX() < (0 - this.getWidth())) {
this.setX(spookrijder.getWidth() + this.getWidth());
this.setAangeraakt(false);
this.setVisible(true);
}
}
/**
* Zet aangeraakt
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
public void setAangeraakt(boolean aangeraakt) {
this.aangeraakt = aangeraakt;
}
/**
* Verkrijg aangeraakt
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @return Aangeraakt-status van het object.
* @version 1.0
*/
public boolean getAangeraakt() {
return this.aangeraakt;
}
/**
* Verkrijg hoogte
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @return De hoogte van het object.
* @since 11-05-2018
* @version 1.0
*/
public float getHeight() {
return this.hoogte;
}
/**
* Verkrijg breedte
<SUF>*/
public float getWidth() {
return this.breedte;
}
/**
* Zet hoogte
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
public void setHeight(int hoogte) {
this.hoogte = hoogte;
}
/**
* Zet breedte
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
public void setWidth(int breedte) {
this.breedte = breedte;
}
/**
* Doe Geluid
*
* Initialiseert een geluidsobject en speelt deze af.
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
public void doeGeluid() {
Sound geluid = new Sound(spookrijder,
"src/main/java/nl/han/ica/spookrijder/media/" + this.geluidsnaam + ".mp3");
geluid.play();
}
}
| True | 905 | 66 | 1,026 | 67 | 984 | 67 | 1,026 | 67 | 1,109 | 72 | false | false | false | false | false | true |
2,873 | 202578_22 | /*
* Copyright 2023 The original 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 dev.morling.onebrc;
import jdk.incubator.vector.*;
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.TreeMap;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import static java.lang.Double.doubleToRawLongBits;
import static java.lang.Double.longBitsToDouble;
import static java.lang.foreign.ValueLayout.*;
/**
* Broad experiments in this implementation:
* - Memory-Map the file with new MemorySegments
* - Use SIMD/vectorized search for the semicolon and new line feeds
* - Use SIMD/vectorized comparison for the 'key'
* <p>
* Absolute stupid things / performance left on the table
* - Single Threaded! Multi threading planned.
* - The hash map/table is super basic.
* - Hash table implementation / hashing has no resizing and is quite basic
* - Zero time spend on profiling =)
* <p>
* <p>
* Cheats used:
* - Only works with Unix line feed \n
* - double parsing is only accepting XX.X and X.X
* - HashMap has no resizing, check, horrible hash etc.
* - Used the double parsing from yemreinci
*/
public class CalculateAverage_gamlerhart {
private static final String FILE = "./measurements.txt";
final static VectorSpecies<Byte> byteVec = ByteVector.SPECIES_PREFERRED;
final static Vector<Byte> zero = byteVec.zero();
final static int vecLen = byteVec.length();
final static Vector<Byte> semiColon = byteVec.broadcast(';');
final static VectorMask<Byte> allTrue = byteVec.maskAll(true);
final static ValueLayout.OfInt INT_UNALIGNED_BIG_ENDIAN = ValueLayout.JAVA_INT_UNALIGNED.withOrder(ByteOrder.BIG_ENDIAN);
public static void main(String[] args) throws Exception {
try (var arena = Arena.ofShared();
FileChannel fc = FileChannel.open(Path.of(FILE))) {
long fileSize = fc.size();
MemorySegment fileContent = fc.map(FileChannel.MapMode.READ_ONLY, 0, fileSize, arena);
ArrayList<Section> sections = splitFileIntoSections(fileSize, fileContent);
var loopBound = byteVec.loopBound(fileSize) - vecLen;
var result = sections.stream()
.parallel()
.map(s -> {
return parseSection(s.start, s.end, loopBound, fileContent);
});
var measurements = new TreeMap<String, ResultRow>();
result.forEachOrdered(m -> {
m.fillMerge(fileContent, measurements);
});
System.out.println(measurements);
}
}
private static PrivateHashMap parseSection(long start, long end, long loopBound, MemorySegment fileContent) {
var map = new PrivateHashMap();
for (long i = start; i < end;) {
long nameStart = i;
int simdSearchEnd = 0;
int nameLen = 0;
// Vectorized Search
if (i < loopBound) {
do {
var vec = byteVec.fromMemorySegment(fileContent, i, ByteOrder.BIG_ENDIAN);
var hasSemi = vec.eq(semiColon);
simdSearchEnd = hasSemi.firstTrue();
i += simdSearchEnd;
nameLen += simdSearchEnd;
} while (simdSearchEnd == vecLen && i < loopBound);
}
// Left-over search
while (loopBound <= i && fileContent.get(JAVA_BYTE, i) != ';') {
nameLen++;
i++;
}
i++; // Consume ;
// Copied from yemreinci. I mostly wanted to experiment the vector math, not with parsing =)
double val;
{
boolean negative = false;
if ((fileContent.get(JAVA_BYTE, i)) == '-') {
negative = true;
i++;
}
byte b;
double temp;
if ((b = fileContent.get(JAVA_BYTE, i + 1)) == '.') { // temperature is in either XX.X or X.X form
temp = (fileContent.get(JAVA_BYTE, i) - '0') + (fileContent.get(JAVA_BYTE, i + 2) - '0') / 10.0;
i += 3;
}
else {
temp = (fileContent.get(JAVA_BYTE, i) - '0') * 10 + (b - '0')
+ (fileContent.get(JAVA_BYTE, i + 3) - '0') / 10.0;
i += 4;
}
val = (negative ? -temp : temp);
}
i++; // Consume \n
map.add(fileContent, nameStart, nameLen, val);
}
return map;
}
private static ArrayList<Section> splitFileIntoSections(long fileSize, MemorySegment fileContent) {
var cpuCount = Runtime.getRuntime().availableProcessors();
var roughChunkSize = fileSize / cpuCount;
ArrayList<Section> sections = new ArrayList<>(cpuCount);
for (long sStart = 0; sStart < fileSize;) {
var endGuess = Math.min(sStart + roughChunkSize, fileSize);
for (; endGuess < fileSize && fileContent.get(JAVA_BYTE, endGuess) != '\n'; endGuess++) {
}
sections.add(new Section(sStart, endGuess));
sStart = endGuess + 1;
}
return sections;
}
private static class PrivateHashMap {
private static final int SIZE_SHIFT = 14;
public static final int SIZE = 1 << SIZE_SHIFT;
public static int MASK = 0xFFFFFFFF >>> (32 - SIZE_SHIFT);
public static long SHIFT_POS = 16;
public static long MASK_POS = 0xFFFFFFFFFFFF0000L;
public static long MASK_LEN = 0x000000000000FFFFL;
// Encoding:
// - Key: long
// - 48 bits index, 16 bits length
final long[] keys = new long[SIZE];
final Value[] values = new Value[SIZE];
private class Value {
public Value(double min, double max, double sum, long count) {
this.min = min;
this.max = max;
this.sum = sum;
this.count = count;
}
public double min;
public double max;
public double sum;
public long count;
}
// int debug_size = 0;
// int debug_reprobeMax = 0;
public PrivateHashMap() {
}
public void add(MemorySegment file, long pos, int len, double val) {
int hashCode = calculateHash(file, pos, len);
doAdd(file, hashCode, pos, len, val);
}
private static int calculateHash(MemorySegment file, long pos, int len) {
if (len > 4) {
return file.get(INT_UNALIGNED_BIG_ENDIAN, pos) + 31 * len;
}
else {
int hashCode = len;
int i = 0;
for (; i < len; i++) {
int v = file.get(JAVA_BYTE, pos + i);
hashCode = 31 * hashCode + v;
}
return hashCode;
}
}
private void doAdd(MemorySegment file, int hash, long pos, int len, double val) {
int slot = hash & MASK;
for (var probe = 0; probe < 20000; probe++) {
var iSl = ((slot + probe) & MASK);
var slotEntry = keys[iSl];
var emtpy = slotEntry == 0;
if (emtpy) {
long keyInfo = pos << SHIFT_POS | len;
keys[iSl] = keyInfo;
values[iSl] = new Value(val, val, val, 1);
// debug_size++;
return;
}
else if (isSameEntry(file, slotEntry, pos, len)) {
var vE = values[iSl];
vE.min = Math.min(vE.min, val);
vE.max = Math.max(vE.max, val);
vE.sum = vE.sum + val;
vE.count++;
return;
}
else {
// long keyPos = (slotEntry & MASK_POS) >> SHIFT_POS;
// int keyLen = (int) (slotEntry & MASK_LEN);
// System.out.println("Colliding " + new String(file.asSlice(pos,len).toArray(ValueLayout.JAVA_BYTE)) +
// " with key" + new String(file.asSlice(keyPos,keyLen).toArray(ValueLayout.JAVA_BYTE)) +
// " hash " + hash + " slot " + slot + "+" + probe + " at " + iSl);
// debug_reprobeMax = Math.max(debug_reprobeMax, probe);
}
}
throw new IllegalStateException("More than 20000 reprobes");
// throw new IllegalStateException("More than 100 reprobes: At " + debug_size + "");
}
private boolean isSameEntry(MemorySegment file, long slotEntry, long pos, int len) {
long keyPos = (slotEntry & MASK_POS) >> SHIFT_POS;
int keyLen = (int) (slotEntry & MASK_LEN);
var isSame = len == keyLen && isSame(file, keyPos, pos, len);
return isSame;
}
private static boolean isSame(MemorySegment file, long i1, long i2, int len) {
int i = 0;
var i1len = i1 + vecLen;
var i2len = i2 + vecLen;
if (len < vecLen && i1len <= file.byteSize() && i2len <= file.byteSize()) {
var v1 = byteVec.fromMemorySegment(file, i1, ByteOrder.nativeOrder());
var v2 = byteVec.fromMemorySegment(file, i2, ByteOrder.nativeOrder());
var isTrue = v1.compare(VectorOperators.EQ, v2, allTrue.indexInRange(0, len));
return isTrue.trueCount() == len;
}
while (8 < (len - i)) {
var v1 = file.get(JAVA_LONG_UNALIGNED, i1 + i);
var v2 = file.get(JAVA_LONG_UNALIGNED, i2 + i);
if (v1 != v2) {
return false;
}
i += 8;
}
while (i < len) {
var v1 = file.get(JAVA_BYTE, i1 + i);
var v2 = file.get(JAVA_BYTE, i2 + i);
if (v1 != v2) {
return false;
}
i++;
}
return true;
}
public void fillMerge(MemorySegment file, TreeMap<String, ResultRow> treeMap) {
for (int i = 0; i < keys.length; i++) {
var ji = i;
long keyE = keys[ji];
if (keyE != 0) {
long keyPos = (keyE & MASK_POS) >> SHIFT_POS;
int keyLen = (int) (keyE & MASK_LEN);
byte[] keyBytes = new byte[keyLen];
MemorySegment.copy(file, JAVA_BYTE, keyPos, keyBytes, 0, keyLen);
var key = new String(keyBytes);
var vE = values[ji];
var min = vE.min;
var max = vE.max;
var sum = vE.sum;
var count = vE.count;
treeMap.compute(key, (k, e) -> {
if (e == null) {
return new ResultRow(min, max, sum, count);
}
else {
return new ResultRow(Math.min(e.min, min), Math.max(e.max, max), e.sum + sum, e.count + count);
}
});
}
}
}
// public String debugPrint(MemorySegment file) {
// StringBuilder b = new StringBuilder();
// for (int i = 0; i < keyValues.length / 5; i++) {
// var ji = i * 5;
// long keyE = keyValues[ji];
// if (keyE != 0) {
// long keyPos = (keyE & MASK_POS) >> SHIFT_POS;
// int keyLen = (int) (keyE & MASK_LEN);
// byte[] keyBytes = new byte[keyLen];
// MemorySegment.copy(file, JAVA_BYTE, keyPos, keyBytes, 0, keyLen);
// var key = new String(keyBytes);
// var min = longBitsToDouble(keyValues[ji + 1]);
// var max = longBitsToDouble(keyValues[ji + 2]);
// var sum = longBitsToDouble(keyValues[ji + 3]);
// var count = keyValues[ji + 4];
// b.append("{").append(key).append("@").append(ji)
// .append(",").append(min)
// .append(",").append(max)
// .append(",").append(sum)
// .append(",").append(count).append("},");
// }
// }
// return b.toString();
// }
}
record Section(long start, long end) {
}
private static record ResultRow(double min, double max, double sum, long count) {
public String toString() {
return round(min) + "/" + round(((Math.round(sum * 10.0) / 10.0) / count)) + "/" + round(max);
}
private double round(double value) {
return Math.round(value * 10.0) / 10.0;
}
}
;
}
| gunnarmorling/1brc | src/main/java/dev/morling/onebrc/CalculateAverage_gamlerhart.java | 4,059 | // int keyLen = (int) (keyE & MASK_LEN); | line_comment | nl | /*
* Copyright 2023 The original 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 dev.morling.onebrc;
import jdk.incubator.vector.*;
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.TreeMap;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import static java.lang.Double.doubleToRawLongBits;
import static java.lang.Double.longBitsToDouble;
import static java.lang.foreign.ValueLayout.*;
/**
* Broad experiments in this implementation:
* - Memory-Map the file with new MemorySegments
* - Use SIMD/vectorized search for the semicolon and new line feeds
* - Use SIMD/vectorized comparison for the 'key'
* <p>
* Absolute stupid things / performance left on the table
* - Single Threaded! Multi threading planned.
* - The hash map/table is super basic.
* - Hash table implementation / hashing has no resizing and is quite basic
* - Zero time spend on profiling =)
* <p>
* <p>
* Cheats used:
* - Only works with Unix line feed \n
* - double parsing is only accepting XX.X and X.X
* - HashMap has no resizing, check, horrible hash etc.
* - Used the double parsing from yemreinci
*/
public class CalculateAverage_gamlerhart {
private static final String FILE = "./measurements.txt";
final static VectorSpecies<Byte> byteVec = ByteVector.SPECIES_PREFERRED;
final static Vector<Byte> zero = byteVec.zero();
final static int vecLen = byteVec.length();
final static Vector<Byte> semiColon = byteVec.broadcast(';');
final static VectorMask<Byte> allTrue = byteVec.maskAll(true);
final static ValueLayout.OfInt INT_UNALIGNED_BIG_ENDIAN = ValueLayout.JAVA_INT_UNALIGNED.withOrder(ByteOrder.BIG_ENDIAN);
public static void main(String[] args) throws Exception {
try (var arena = Arena.ofShared();
FileChannel fc = FileChannel.open(Path.of(FILE))) {
long fileSize = fc.size();
MemorySegment fileContent = fc.map(FileChannel.MapMode.READ_ONLY, 0, fileSize, arena);
ArrayList<Section> sections = splitFileIntoSections(fileSize, fileContent);
var loopBound = byteVec.loopBound(fileSize) - vecLen;
var result = sections.stream()
.parallel()
.map(s -> {
return parseSection(s.start, s.end, loopBound, fileContent);
});
var measurements = new TreeMap<String, ResultRow>();
result.forEachOrdered(m -> {
m.fillMerge(fileContent, measurements);
});
System.out.println(measurements);
}
}
private static PrivateHashMap parseSection(long start, long end, long loopBound, MemorySegment fileContent) {
var map = new PrivateHashMap();
for (long i = start; i < end;) {
long nameStart = i;
int simdSearchEnd = 0;
int nameLen = 0;
// Vectorized Search
if (i < loopBound) {
do {
var vec = byteVec.fromMemorySegment(fileContent, i, ByteOrder.BIG_ENDIAN);
var hasSemi = vec.eq(semiColon);
simdSearchEnd = hasSemi.firstTrue();
i += simdSearchEnd;
nameLen += simdSearchEnd;
} while (simdSearchEnd == vecLen && i < loopBound);
}
// Left-over search
while (loopBound <= i && fileContent.get(JAVA_BYTE, i) != ';') {
nameLen++;
i++;
}
i++; // Consume ;
// Copied from yemreinci. I mostly wanted to experiment the vector math, not with parsing =)
double val;
{
boolean negative = false;
if ((fileContent.get(JAVA_BYTE, i)) == '-') {
negative = true;
i++;
}
byte b;
double temp;
if ((b = fileContent.get(JAVA_BYTE, i + 1)) == '.') { // temperature is in either XX.X or X.X form
temp = (fileContent.get(JAVA_BYTE, i) - '0') + (fileContent.get(JAVA_BYTE, i + 2) - '0') / 10.0;
i += 3;
}
else {
temp = (fileContent.get(JAVA_BYTE, i) - '0') * 10 + (b - '0')
+ (fileContent.get(JAVA_BYTE, i + 3) - '0') / 10.0;
i += 4;
}
val = (negative ? -temp : temp);
}
i++; // Consume \n
map.add(fileContent, nameStart, nameLen, val);
}
return map;
}
private static ArrayList<Section> splitFileIntoSections(long fileSize, MemorySegment fileContent) {
var cpuCount = Runtime.getRuntime().availableProcessors();
var roughChunkSize = fileSize / cpuCount;
ArrayList<Section> sections = new ArrayList<>(cpuCount);
for (long sStart = 0; sStart < fileSize;) {
var endGuess = Math.min(sStart + roughChunkSize, fileSize);
for (; endGuess < fileSize && fileContent.get(JAVA_BYTE, endGuess) != '\n'; endGuess++) {
}
sections.add(new Section(sStart, endGuess));
sStart = endGuess + 1;
}
return sections;
}
private static class PrivateHashMap {
private static final int SIZE_SHIFT = 14;
public static final int SIZE = 1 << SIZE_SHIFT;
public static int MASK = 0xFFFFFFFF >>> (32 - SIZE_SHIFT);
public static long SHIFT_POS = 16;
public static long MASK_POS = 0xFFFFFFFFFFFF0000L;
public static long MASK_LEN = 0x000000000000FFFFL;
// Encoding:
// - Key: long
// - 48 bits index, 16 bits length
final long[] keys = new long[SIZE];
final Value[] values = new Value[SIZE];
private class Value {
public Value(double min, double max, double sum, long count) {
this.min = min;
this.max = max;
this.sum = sum;
this.count = count;
}
public double min;
public double max;
public double sum;
public long count;
}
// int debug_size = 0;
// int debug_reprobeMax = 0;
public PrivateHashMap() {
}
public void add(MemorySegment file, long pos, int len, double val) {
int hashCode = calculateHash(file, pos, len);
doAdd(file, hashCode, pos, len, val);
}
private static int calculateHash(MemorySegment file, long pos, int len) {
if (len > 4) {
return file.get(INT_UNALIGNED_BIG_ENDIAN, pos) + 31 * len;
}
else {
int hashCode = len;
int i = 0;
for (; i < len; i++) {
int v = file.get(JAVA_BYTE, pos + i);
hashCode = 31 * hashCode + v;
}
return hashCode;
}
}
private void doAdd(MemorySegment file, int hash, long pos, int len, double val) {
int slot = hash & MASK;
for (var probe = 0; probe < 20000; probe++) {
var iSl = ((slot + probe) & MASK);
var slotEntry = keys[iSl];
var emtpy = slotEntry == 0;
if (emtpy) {
long keyInfo = pos << SHIFT_POS | len;
keys[iSl] = keyInfo;
values[iSl] = new Value(val, val, val, 1);
// debug_size++;
return;
}
else if (isSameEntry(file, slotEntry, pos, len)) {
var vE = values[iSl];
vE.min = Math.min(vE.min, val);
vE.max = Math.max(vE.max, val);
vE.sum = vE.sum + val;
vE.count++;
return;
}
else {
// long keyPos = (slotEntry & MASK_POS) >> SHIFT_POS;
// int keyLen = (int) (slotEntry & MASK_LEN);
// System.out.println("Colliding " + new String(file.asSlice(pos,len).toArray(ValueLayout.JAVA_BYTE)) +
// " with key" + new String(file.asSlice(keyPos,keyLen).toArray(ValueLayout.JAVA_BYTE)) +
// " hash " + hash + " slot " + slot + "+" + probe + " at " + iSl);
// debug_reprobeMax = Math.max(debug_reprobeMax, probe);
}
}
throw new IllegalStateException("More than 20000 reprobes");
// throw new IllegalStateException("More than 100 reprobes: At " + debug_size + "");
}
private boolean isSameEntry(MemorySegment file, long slotEntry, long pos, int len) {
long keyPos = (slotEntry & MASK_POS) >> SHIFT_POS;
int keyLen = (int) (slotEntry & MASK_LEN);
var isSame = len == keyLen && isSame(file, keyPos, pos, len);
return isSame;
}
private static boolean isSame(MemorySegment file, long i1, long i2, int len) {
int i = 0;
var i1len = i1 + vecLen;
var i2len = i2 + vecLen;
if (len < vecLen && i1len <= file.byteSize() && i2len <= file.byteSize()) {
var v1 = byteVec.fromMemorySegment(file, i1, ByteOrder.nativeOrder());
var v2 = byteVec.fromMemorySegment(file, i2, ByteOrder.nativeOrder());
var isTrue = v1.compare(VectorOperators.EQ, v2, allTrue.indexInRange(0, len));
return isTrue.trueCount() == len;
}
while (8 < (len - i)) {
var v1 = file.get(JAVA_LONG_UNALIGNED, i1 + i);
var v2 = file.get(JAVA_LONG_UNALIGNED, i2 + i);
if (v1 != v2) {
return false;
}
i += 8;
}
while (i < len) {
var v1 = file.get(JAVA_BYTE, i1 + i);
var v2 = file.get(JAVA_BYTE, i2 + i);
if (v1 != v2) {
return false;
}
i++;
}
return true;
}
public void fillMerge(MemorySegment file, TreeMap<String, ResultRow> treeMap) {
for (int i = 0; i < keys.length; i++) {
var ji = i;
long keyE = keys[ji];
if (keyE != 0) {
long keyPos = (keyE & MASK_POS) >> SHIFT_POS;
int keyLen = (int) (keyE & MASK_LEN);
byte[] keyBytes = new byte[keyLen];
MemorySegment.copy(file, JAVA_BYTE, keyPos, keyBytes, 0, keyLen);
var key = new String(keyBytes);
var vE = values[ji];
var min = vE.min;
var max = vE.max;
var sum = vE.sum;
var count = vE.count;
treeMap.compute(key, (k, e) -> {
if (e == null) {
return new ResultRow(min, max, sum, count);
}
else {
return new ResultRow(Math.min(e.min, min), Math.max(e.max, max), e.sum + sum, e.count + count);
}
});
}
}
}
// public String debugPrint(MemorySegment file) {
// StringBuilder b = new StringBuilder();
// for (int i = 0; i < keyValues.length / 5; i++) {
// var ji = i * 5;
// long keyE = keyValues[ji];
// if (keyE != 0) {
// long keyPos = (keyE & MASK_POS) >> SHIFT_POS;
// int keyLen<SUF>
// byte[] keyBytes = new byte[keyLen];
// MemorySegment.copy(file, JAVA_BYTE, keyPos, keyBytes, 0, keyLen);
// var key = new String(keyBytes);
// var min = longBitsToDouble(keyValues[ji + 1]);
// var max = longBitsToDouble(keyValues[ji + 2]);
// var sum = longBitsToDouble(keyValues[ji + 3]);
// var count = keyValues[ji + 4];
// b.append("{").append(key).append("@").append(ji)
// .append(",").append(min)
// .append(",").append(max)
// .append(",").append(sum)
// .append(",").append(count).append("},");
// }
// }
// return b.toString();
// }
}
record Section(long start, long end) {
}
private static record ResultRow(double min, double max, double sum, long count) {
public String toString() {
return round(min) + "/" + round(((Math.round(sum * 10.0) / 10.0) / count)) + "/" + round(max);
}
private double round(double value) {
return Math.round(value * 10.0) / 10.0;
}
}
;
}
| False | 3,159 | 15 | 3,464 | 16 | 3,703 | 16 | 3,464 | 16 | 4,084 | 19 | false | false | false | false | false | true |
4,492 | 129008_21 | /**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.common.utils;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.lang3.time.DateFormatUtils;
/**
* 日期工具类, 继承org.apache.commons.lang.time.DateUtils类
* @author ThinkGem
* @version 2014-4-15
*/
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
private static String[] parsePatterns = {
"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
"yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
/**
* 得到当前日期字符串 格式(yyyy-MM-dd)
*/
public static String getDate() {
return getDate("yyyy-MM-dd");
}
/**
* 得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public static String getDate(String pattern) {
return DateFormatUtils.format(new Date(), pattern);
}
/**
* 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public static String formatDate(Date date, Object... pattern) {
String formatDate = null;
if (pattern != null && pattern.length > 0) {
formatDate = DateFormatUtils.format(date, pattern[0].toString());
} else {
formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
}
return formatDate;
}
/**
* 得到日期时间字符串,转换格式(yyyy-MM-dd HH:mm:ss)
*/
public static String formatDateTime(Date date) {
return formatDate(date, "yyyy-MM-dd HH:mm:ss");
}
/**
* 得到当前时间字符串 格式(HH:mm:ss)
*/
public static String getTime() {
return formatDate(new Date(), "HH:mm:ss");
}
/**
* 得到当前日期和时间字符串 格式(yyyy-MM-dd HH:mm:ss)
*/
public static String getDateTime() {
return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
}
/**
* 得到当前年份字符串 格式(yyyy)
*/
public static String getYear() {
return formatDate(new Date(), "yyyy");
}
/**
* 得到当前月份字符串 格式(MM)
*/
public static String getMonth() {
return formatDate(new Date(), "MM");
}
/**
* 得到当天字符串 格式(dd)
*/
public static String getDay() {
return formatDate(new Date(), "dd");
}
/**
* 得到当前星期字符串 格式(E)星期几
*/
public static String getWeek() {
return formatDate(new Date(), "E");
}
/**
* 日期型字符串转化为日期 格式
* { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
* "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm",
* "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" }
*/
public static Date parseDate(Object str) {
if (str == null){
return null;
}
try {
return parseDate(str.toString(), parsePatterns);
} catch (ParseException e) {
return null;
}
}
/**
* 获取过去的天数
* @param date
* @return
*/
public static long pastDays(Date date) {
long t = new Date().getTime()-date.getTime();
return t/(24*60*60*1000);
}
/**
* 获取过去的小时
* @param date
* @return
*/
public static long pastHour(Date date) {
long t = new Date().getTime()-date.getTime();
return t/(60*60*1000);
}
/**
* 获取过去的分钟
* @param date
* @return
*/
public static long pastMinutes(Date date) {
long t = new Date().getTime()-date.getTime();
return t/(60*1000);
}
/**
* 转换为时间(天,时:分:秒.毫秒)
* @param timeMillis
* @return
*/
public static String formatDateTime(long timeMillis){
long day = timeMillis/(24*60*60*1000);
long hour = (timeMillis/(60*60*1000)-day*24);
long min = ((timeMillis/(60*1000))-day*24*60-hour*60);
long s = (timeMillis/1000-day*24*60*60-hour*60*60-min*60);
long sss = (timeMillis-day*24*60*60*1000-hour*60*60*1000-min*60*1000-s*1000);
return (day>0?day+",":"")+hour+":"+min+":"+s+"."+sss;
}
/**
* 获取两个日期之间的天数
*
* @param before
* @param after
* @return
*/
public static double getDistanceOfTwoDate(Date before, Date after) {
long beforeTime = before.getTime();
long afterTime = after.getTime();
return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
}
/**
* 获取过去第几天的日期
*
* @param past
* @return
*/
public static String getPastDate(int past) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
Date today = calendar.getTime();
String result = formatDate(today, "yyyyMMdd") ;
return result;
}
/**
* 获取未来 第 past 天的日期
* @param past
* @return
*/
public static String getFetureDate(int past) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
Date today = calendar.getTime();
String result = formatDate(today, "yyyyMMdd") ;
return result;
}
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
// System.out.println(formatDate(parseDate("2010/3/6")));
// System.out.println(getDate("yyyy年MM月dd日 E"));
// long time = new Date().getTime()-parseDate("2012-11-19").getTime();
// System.out.println(time/(24*60*60*1000));
}
}
| thinkgem/jeesite | src/main/java/com/thinkgem/jeesite/common/utils/DateUtils.java | 2,060 | // long time = new Date().getTime()-parseDate("2012-11-19").getTime(); | line_comment | nl | /**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.common.utils;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.lang3.time.DateFormatUtils;
/**
* 日期工具类, 继承org.apache.commons.lang.time.DateUtils类
* @author ThinkGem
* @version 2014-4-15
*/
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
private static String[] parsePatterns = {
"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
"yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
/**
* 得到当前日期字符串 格式(yyyy-MM-dd)
*/
public static String getDate() {
return getDate("yyyy-MM-dd");
}
/**
* 得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public static String getDate(String pattern) {
return DateFormatUtils.format(new Date(), pattern);
}
/**
* 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public static String formatDate(Date date, Object... pattern) {
String formatDate = null;
if (pattern != null && pattern.length > 0) {
formatDate = DateFormatUtils.format(date, pattern[0].toString());
} else {
formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
}
return formatDate;
}
/**
* 得到日期时间字符串,转换格式(yyyy-MM-dd HH:mm:ss)
*/
public static String formatDateTime(Date date) {
return formatDate(date, "yyyy-MM-dd HH:mm:ss");
}
/**
* 得到当前时间字符串 格式(HH:mm:ss)
*/
public static String getTime() {
return formatDate(new Date(), "HH:mm:ss");
}
/**
* 得到当前日期和时间字符串 格式(yyyy-MM-dd HH:mm:ss)
*/
public static String getDateTime() {
return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
}
/**
* 得到当前年份字符串 格式(yyyy)
*/
public static String getYear() {
return formatDate(new Date(), "yyyy");
}
/**
* 得到当前月份字符串 格式(MM)
*/
public static String getMonth() {
return formatDate(new Date(), "MM");
}
/**
* 得到当天字符串 格式(dd)
*/
public static String getDay() {
return formatDate(new Date(), "dd");
}
/**
* 得到当前星期字符串 格式(E)星期几
*/
public static String getWeek() {
return formatDate(new Date(), "E");
}
/**
* 日期型字符串转化为日期 格式
* { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
* "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm",
* "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" }
*/
public static Date parseDate(Object str) {
if (str == null){
return null;
}
try {
return parseDate(str.toString(), parsePatterns);
} catch (ParseException e) {
return null;
}
}
/**
* 获取过去的天数
* @param date
* @return
*/
public static long pastDays(Date date) {
long t = new Date().getTime()-date.getTime();
return t/(24*60*60*1000);
}
/**
* 获取过去的小时
* @param date
* @return
*/
public static long pastHour(Date date) {
long t = new Date().getTime()-date.getTime();
return t/(60*60*1000);
}
/**
* 获取过去的分钟
* @param date
* @return
*/
public static long pastMinutes(Date date) {
long t = new Date().getTime()-date.getTime();
return t/(60*1000);
}
/**
* 转换为时间(天,时:分:秒.毫秒)
* @param timeMillis
* @return
*/
public static String formatDateTime(long timeMillis){
long day = timeMillis/(24*60*60*1000);
long hour = (timeMillis/(60*60*1000)-day*24);
long min = ((timeMillis/(60*1000))-day*24*60-hour*60);
long s = (timeMillis/1000-day*24*60*60-hour*60*60-min*60);
long sss = (timeMillis-day*24*60*60*1000-hour*60*60*1000-min*60*1000-s*1000);
return (day>0?day+",":"")+hour+":"+min+":"+s+"."+sss;
}
/**
* 获取两个日期之间的天数
*
* @param before
* @param after
* @return
*/
public static double getDistanceOfTwoDate(Date before, Date after) {
long beforeTime = before.getTime();
long afterTime = after.getTime();
return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
}
/**
* 获取过去第几天的日期
*
* @param past
* @return
*/
public static String getPastDate(int past) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
Date today = calendar.getTime();
String result = formatDate(today, "yyyyMMdd") ;
return result;
}
/**
* 获取未来 第 past 天的日期
* @param past
* @return
*/
public static String getFetureDate(int past) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
Date today = calendar.getTime();
String result = formatDate(today, "yyyyMMdd") ;
return result;
}
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
// System.out.println(formatDate(parseDate("2010/3/6")));
// System.out.println(getDate("yyyy年MM月dd日 E"));
// long time<SUF>
// System.out.println(time/(24*60*60*1000));
}
}
| False | 1,639 | 26 | 1,960 | 27 | 1,973 | 26 | 1,960 | 27 | 2,282 | 30 | false | false | false | false | false | true |
4,800 | 195998_8 | /**
* Copyright (c) 2012, 2013 SURFnet BV
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the SURFnet BV nor the names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package nl.surfnet.bod.search;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import java.util.List;
import nl.surfnet.bod.domain.UniPort;
import org.apache.lucene.queryParser.ParseException;
import org.junit.Test;
public class PhysicalPortIndexAndSearchTest extends AbstractIndexAndSearch<UniPort> {
public PhysicalPortIndexAndSearchTest() {
super(UniPort.class);
}
@Test
public void testIndexAndSearch() throws Exception {
List<UniPort> physicalPorts = searchFor("gamma");
// (N.A.)
assertThat(physicalPorts, hasSize(0));
physicalPorts = searchFor("ut");
// (UT One, UT Two)
assertThat(physicalPorts, hasSize(2));
physicalPorts = searchFor("Ut");
// (UT One, UT Two)
assertThat(physicalPorts, hasSize(2));
physicalPorts = searchFor("Mock");
// (All available (4) PP's)
assertThat(physicalPorts, hasSize(4));
physicalPorts = searchFor("ETH-1-13-4");
// (Noc label 4)
assertThat(physicalPorts, hasSize(1));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Noc 4 label"));
physicalPorts = searchFor("OME");
// (Mock_Ut002A_OME01_ETH-1-2-4, Mock_Ut001A_OME01_ETH-1-2-1)
assertThat(physicalPorts, hasSize(2));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Mock_Ut002A_OME01_ETH-1-2-1"));
assertThat(physicalPorts.get(1).getNocLabel(), equalTo("Mock_Ut001A_OME01_ETH-1-2-2"));
physicalPorts = searchFor("ETH-1-");
// (All available (4) PP's)
assertThat(physicalPorts, hasSize(4));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Mock_Ut002A_OME01_ETH-1-2-1"));
assertThat(physicalPorts.get(1).getNocLabel(), equalTo("Mock_Ut001A_OME01_ETH-1-2-2"));
assertThat(physicalPorts.get(2).getNocLabel(), equalTo("Noc 3 label"));
assertThat(physicalPorts.get(3).getNocLabel(), equalTo("Noc 4 label"));
physicalPorts = searchFor("1");
// (All available (4) PP's)
assertThat(physicalPorts, hasSize(4));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Mock_Ut002A_OME01_ETH-1-2-1"));
assertThat(physicalPorts.get(1).getNocLabel(), equalTo("Mock_Ut001A_OME01_ETH-1-2-2"));
assertThat(physicalPorts.get(2).getNocLabel(), equalTo("Noc 3 label"));
assertThat(physicalPorts.get(3).getNocLabel(), equalTo("Noc 4 label"));
physicalPorts = searchFor("1de");
// Mock_port 1de verdieping toren1a
assertThat(physicalPorts, hasSize(1));
assertThat(physicalPorts.get(0).getBodPortId(), equalTo("Mock_port 1de verdieping toren1a"));
physicalPorts = searchFor("2de");
// Mock_port 2de verdieping toren1b
assertThat(physicalPorts, hasSize(1));
assertThat(physicalPorts.get(0).getBodPortId(), equalTo("Mock_port 2de verdieping toren1b"));
}
@Test
public void shouldNotCrashOnColon() throws ParseException {
List<UniPort> physicalPorts = searchFor("nocLabel:\"Noc 3 label\"");
assertThat(physicalPorts, hasSize(1));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Noc 3 label"));
}
} | zanetworker/bandwidth-on-demand | src/test/java/nl/surfnet/bod/search/PhysicalPortIndexAndSearchTest.java | 1,581 | // Mock_port 2de verdieping toren1b | line_comment | nl | /**
* Copyright (c) 2012, 2013 SURFnet BV
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the SURFnet BV nor the names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package nl.surfnet.bod.search;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import java.util.List;
import nl.surfnet.bod.domain.UniPort;
import org.apache.lucene.queryParser.ParseException;
import org.junit.Test;
public class PhysicalPortIndexAndSearchTest extends AbstractIndexAndSearch<UniPort> {
public PhysicalPortIndexAndSearchTest() {
super(UniPort.class);
}
@Test
public void testIndexAndSearch() throws Exception {
List<UniPort> physicalPorts = searchFor("gamma");
// (N.A.)
assertThat(physicalPorts, hasSize(0));
physicalPorts = searchFor("ut");
// (UT One, UT Two)
assertThat(physicalPorts, hasSize(2));
physicalPorts = searchFor("Ut");
// (UT One, UT Two)
assertThat(physicalPorts, hasSize(2));
physicalPorts = searchFor("Mock");
// (All available (4) PP's)
assertThat(physicalPorts, hasSize(4));
physicalPorts = searchFor("ETH-1-13-4");
// (Noc label 4)
assertThat(physicalPorts, hasSize(1));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Noc 4 label"));
physicalPorts = searchFor("OME");
// (Mock_Ut002A_OME01_ETH-1-2-4, Mock_Ut001A_OME01_ETH-1-2-1)
assertThat(physicalPorts, hasSize(2));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Mock_Ut002A_OME01_ETH-1-2-1"));
assertThat(physicalPorts.get(1).getNocLabel(), equalTo("Mock_Ut001A_OME01_ETH-1-2-2"));
physicalPorts = searchFor("ETH-1-");
// (All available (4) PP's)
assertThat(physicalPorts, hasSize(4));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Mock_Ut002A_OME01_ETH-1-2-1"));
assertThat(physicalPorts.get(1).getNocLabel(), equalTo("Mock_Ut001A_OME01_ETH-1-2-2"));
assertThat(physicalPorts.get(2).getNocLabel(), equalTo("Noc 3 label"));
assertThat(physicalPorts.get(3).getNocLabel(), equalTo("Noc 4 label"));
physicalPorts = searchFor("1");
// (All available (4) PP's)
assertThat(physicalPorts, hasSize(4));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Mock_Ut002A_OME01_ETH-1-2-1"));
assertThat(physicalPorts.get(1).getNocLabel(), equalTo("Mock_Ut001A_OME01_ETH-1-2-2"));
assertThat(physicalPorts.get(2).getNocLabel(), equalTo("Noc 3 label"));
assertThat(physicalPorts.get(3).getNocLabel(), equalTo("Noc 4 label"));
physicalPorts = searchFor("1de");
// Mock_port 1de verdieping toren1a
assertThat(physicalPorts, hasSize(1));
assertThat(physicalPorts.get(0).getBodPortId(), equalTo("Mock_port 1de verdieping toren1a"));
physicalPorts = searchFor("2de");
// Mock_port 2de<SUF>
assertThat(physicalPorts, hasSize(1));
assertThat(physicalPorts.get(0).getBodPortId(), equalTo("Mock_port 2de verdieping toren1b"));
}
@Test
public void shouldNotCrashOnColon() throws ParseException {
List<UniPort> physicalPorts = searchFor("nocLabel:\"Noc 3 label\"");
assertThat(physicalPorts, hasSize(1));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Noc 3 label"));
}
} | True | 1,237 | 13 | 1,311 | 15 | 1,358 | 12 | 1,311 | 15 | 1,742 | 14 | false | false | false | false | false | true |
2,312 | 161599_23 | /*******************************************************************************_x000D_
* Copyright (c) 2008, 2018 SWTChart project._x000D_
*_x000D_
* All rights reserved. This program and the accompanying materials_x000D_
* are made available under the terms of the Eclipse Public License v1.0_x000D_
* which accompanies this distribution, and is available at_x000D_
* http://www.eclipse.org/legal/epl-v10.html_x000D_
* _x000D_
* Contributors:_x000D_
* yoshitaka - initial API and implementation_x000D_
*******************************************************************************/_x000D_
package org.eclipse.swtchart.internal.axis;_x000D_
_x000D_
import java.text.Format;_x000D_
import java.util.List;_x000D_
_x000D_
import org.eclipse.swt.SWT;_x000D_
import org.eclipse.swt.graphics.Color;_x000D_
import org.eclipse.swt.graphics.Font;_x000D_
import org.eclipse.swt.graphics.Rectangle;_x000D_
import org.eclipse.swtchart.Chart;_x000D_
import org.eclipse.swtchart.IAxis.Position;_x000D_
import org.eclipse.swtchart.IAxisTick;_x000D_
_x000D_
/**_x000D_
* An axis tick._x000D_
*/_x000D_
public class AxisTick implements IAxisTick {_x000D_
_x000D_
/** the chart */_x000D_
private Chart chart;_x000D_
/** the axis */_x000D_
private Axis axis;_x000D_
/** the axis tick labels */_x000D_
private AxisTickLabels axisTickLabels;_x000D_
/** the axis tick marks */_x000D_
private AxisTickMarks axisTickMarks;_x000D_
/** true if tick is visible */_x000D_
private boolean isVisible;_x000D_
/** the tick mark step hint */_x000D_
private int tickMarkStepHint;_x000D_
/** the tick label angle in degree */_x000D_
private int tickLabelAngle;_x000D_
/** the default tick mark step hint */_x000D_
private static final int DEFAULT_TICK_MARK_STEP_HINT = 64;_x000D_
_x000D_
/**_x000D_
* Constructor._x000D_
*_x000D_
* @param chart_x000D_
* the chart_x000D_
* @param axis_x000D_
* the axis_x000D_
*/_x000D_
protected AxisTick(Chart chart, Axis axis) {_x000D_
this.chart = chart;_x000D_
this.axis = axis;_x000D_
axisTickLabels = new AxisTickLabels(chart, axis);_x000D_
axisTickMarks = new AxisTickMarks(chart, axis);_x000D_
isVisible = true;_x000D_
tickLabelAngle = 0;_x000D_
tickMarkStepHint = DEFAULT_TICK_MARK_STEP_HINT;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Gets the axis tick marks._x000D_
*_x000D_
* @return the axis tick marks_x000D_
*/_x000D_
public AxisTickMarks getAxisTickMarks() {_x000D_
_x000D_
return axisTickMarks;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Gets the axis tick labels._x000D_
*_x000D_
* @return the axis tick labels_x000D_
*/_x000D_
public AxisTickLabels getAxisTickLabels() {_x000D_
_x000D_
return axisTickLabels;_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#setForeground(Color)_x000D_
*/_x000D_
public void setForeground(Color color) {_x000D_
_x000D_
if(color != null && color.isDisposed()) {_x000D_
SWT.error(SWT.ERROR_INVALID_ARGUMENT);_x000D_
}_x000D_
axisTickMarks.setForeground(color);_x000D_
axisTickLabels.setForeground(color);_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getForeground()_x000D_
*/_x000D_
public Color getForeground() {_x000D_
_x000D_
return axisTickMarks.getForeground();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#setFont(Font)_x000D_
*/_x000D_
public void setFont(Font font) {_x000D_
_x000D_
if(font != null && font.isDisposed()) {_x000D_
SWT.error(SWT.ERROR_INVALID_ARGUMENT);_x000D_
}_x000D_
axisTickLabels.setFont(font);_x000D_
chart.updateLayout();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getFont()_x000D_
*/_x000D_
public Font getFont() {_x000D_
_x000D_
return axisTickLabels.getFont();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#isVisible()_x000D_
*/_x000D_
public boolean isVisible() {_x000D_
_x000D_
return isVisible;_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#setVisible(boolean)_x000D_
*/_x000D_
public void setVisible(boolean isVisible) {_x000D_
_x000D_
this.isVisible = isVisible;_x000D_
chart.updateLayout();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getTickMarkStepHint()_x000D_
*/_x000D_
public int getTickMarkStepHint() {_x000D_
_x000D_
return tickMarkStepHint;_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#setTickMarkStepHint(int)_x000D_
*/_x000D_
public void setTickMarkStepHint(int tickMarkStepHint) {_x000D_
_x000D_
if(tickMarkStepHint < MIN_GRID_STEP_HINT) {_x000D_
this.tickMarkStepHint = DEFAULT_TICK_MARK_STEP_HINT;_x000D_
} else {_x000D_
this.tickMarkStepHint = tickMarkStepHint;_x000D_
}_x000D_
chart.updateLayout();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getTickLabelAngle()_x000D_
*/_x000D_
public int getTickLabelAngle() {_x000D_
_x000D_
return tickLabelAngle;_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#setTickLabelAngle(int)_x000D_
*/_x000D_
public void setTickLabelAngle(int angle) {_x000D_
_x000D_
if(angle < 0 || 90 < angle) {_x000D_
SWT.error(SWT.ERROR_INVALID_ARGUMENT);_x000D_
}_x000D_
if(tickLabelAngle != angle) {_x000D_
tickLabelAngle = angle;_x000D_
chart.updateLayout();_x000D_
}_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#setFormat(Format)_x000D_
*/_x000D_
public void setFormat(Format format) {_x000D_
_x000D_
axisTickLabels.setFormat(format);_x000D_
chart.updateLayout();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getFormat()_x000D_
*/_x000D_
public Format getFormat() {_x000D_
_x000D_
return axisTickLabels.getFormat();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getBounds()_x000D_
*/_x000D_
public Rectangle getBounds() {_x000D_
_x000D_
Rectangle r1 = axisTickMarks.getBounds();_x000D_
Rectangle r2 = axisTickLabels.getBounds();_x000D_
Position position = axis.getPosition();_x000D_
if(position == Position.Primary && axis.isHorizontalAxis()) {_x000D_
return new Rectangle(r1.x, r1.y, r1.width, r1.height + r2.height);_x000D_
} else if(position == Position.Secondary && axis.isHorizontalAxis()) {_x000D_
return new Rectangle(r1.x, r2.y, r1.width, r1.height + r2.height);_x000D_
} else if(position == Position.Primary && !axis.isHorizontalAxis()) {_x000D_
return new Rectangle(r2.x, r1.y, r1.width + r2.width, r1.height);_x000D_
} else if(position == Position.Secondary && !axis.isHorizontalAxis()) {_x000D_
return new Rectangle(r1.x, r1.y, r1.width + r2.width, r1.height);_x000D_
} else {_x000D_
throw new IllegalStateException("unknown axis position");_x000D_
}_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getTickLabelValues()_x000D_
*/_x000D_
public double[] getTickLabelValues() {_x000D_
_x000D_
List<Double> list = axisTickLabels.getTickLabelValues();_x000D_
double[] values = new double[list.size()];_x000D_
for(int i = 0; i < values.length; i++) {_x000D_
values[i] = list.get(i);_x000D_
}_x000D_
return values;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Updates the tick around per 64 pixel._x000D_
*_x000D_
* @param length_x000D_
* the axis length_x000D_
*/_x000D_
public void updateTick(int length) {_x000D_
_x000D_
if(length <= 0) {_x000D_
axisTickLabels.update(1);_x000D_
} else {_x000D_
axisTickLabels.update(length);_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* Updates the tick layout._x000D_
*/_x000D_
protected void updateLayoutData() {_x000D_
_x000D_
axisTickLabels.updateLayoutData();_x000D_
axisTickMarks.updateLayoutData();_x000D_
}_x000D_
}_x000D_
| buchen/swtchart | org.eclipse.swtchart/src/org/eclipse/swtchart/internal/axis/AxisTick.java | 2,198 | /*_x000D_
* @see IAxisTick#getBounds()_x000D_
*/ | block_comment | nl | /*******************************************************************************_x000D_
* Copyright (c) 2008, 2018 SWTChart project._x000D_
*_x000D_
* All rights reserved. This program and the accompanying materials_x000D_
* are made available under the terms of the Eclipse Public License v1.0_x000D_
* which accompanies this distribution, and is available at_x000D_
* http://www.eclipse.org/legal/epl-v10.html_x000D_
* _x000D_
* Contributors:_x000D_
* yoshitaka - initial API and implementation_x000D_
*******************************************************************************/_x000D_
package org.eclipse.swtchart.internal.axis;_x000D_
_x000D_
import java.text.Format;_x000D_
import java.util.List;_x000D_
_x000D_
import org.eclipse.swt.SWT;_x000D_
import org.eclipse.swt.graphics.Color;_x000D_
import org.eclipse.swt.graphics.Font;_x000D_
import org.eclipse.swt.graphics.Rectangle;_x000D_
import org.eclipse.swtchart.Chart;_x000D_
import org.eclipse.swtchart.IAxis.Position;_x000D_
import org.eclipse.swtchart.IAxisTick;_x000D_
_x000D_
/**_x000D_
* An axis tick._x000D_
*/_x000D_
public class AxisTick implements IAxisTick {_x000D_
_x000D_
/** the chart */_x000D_
private Chart chart;_x000D_
/** the axis */_x000D_
private Axis axis;_x000D_
/** the axis tick labels */_x000D_
private AxisTickLabels axisTickLabels;_x000D_
/** the axis tick marks */_x000D_
private AxisTickMarks axisTickMarks;_x000D_
/** true if tick is visible */_x000D_
private boolean isVisible;_x000D_
/** the tick mark step hint */_x000D_
private int tickMarkStepHint;_x000D_
/** the tick label angle in degree */_x000D_
private int tickLabelAngle;_x000D_
/** the default tick mark step hint */_x000D_
private static final int DEFAULT_TICK_MARK_STEP_HINT = 64;_x000D_
_x000D_
/**_x000D_
* Constructor._x000D_
*_x000D_
* @param chart_x000D_
* the chart_x000D_
* @param axis_x000D_
* the axis_x000D_
*/_x000D_
protected AxisTick(Chart chart, Axis axis) {_x000D_
this.chart = chart;_x000D_
this.axis = axis;_x000D_
axisTickLabels = new AxisTickLabels(chart, axis);_x000D_
axisTickMarks = new AxisTickMarks(chart, axis);_x000D_
isVisible = true;_x000D_
tickLabelAngle = 0;_x000D_
tickMarkStepHint = DEFAULT_TICK_MARK_STEP_HINT;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Gets the axis tick marks._x000D_
*_x000D_
* @return the axis tick marks_x000D_
*/_x000D_
public AxisTickMarks getAxisTickMarks() {_x000D_
_x000D_
return axisTickMarks;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Gets the axis tick labels._x000D_
*_x000D_
* @return the axis tick labels_x000D_
*/_x000D_
public AxisTickLabels getAxisTickLabels() {_x000D_
_x000D_
return axisTickLabels;_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#setForeground(Color)_x000D_
*/_x000D_
public void setForeground(Color color) {_x000D_
_x000D_
if(color != null && color.isDisposed()) {_x000D_
SWT.error(SWT.ERROR_INVALID_ARGUMENT);_x000D_
}_x000D_
axisTickMarks.setForeground(color);_x000D_
axisTickLabels.setForeground(color);_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getForeground()_x000D_
*/_x000D_
public Color getForeground() {_x000D_
_x000D_
return axisTickMarks.getForeground();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#setFont(Font)_x000D_
*/_x000D_
public void setFont(Font font) {_x000D_
_x000D_
if(font != null && font.isDisposed()) {_x000D_
SWT.error(SWT.ERROR_INVALID_ARGUMENT);_x000D_
}_x000D_
axisTickLabels.setFont(font);_x000D_
chart.updateLayout();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getFont()_x000D_
*/_x000D_
public Font getFont() {_x000D_
_x000D_
return axisTickLabels.getFont();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#isVisible()_x000D_
*/_x000D_
public boolean isVisible() {_x000D_
_x000D_
return isVisible;_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#setVisible(boolean)_x000D_
*/_x000D_
public void setVisible(boolean isVisible) {_x000D_
_x000D_
this.isVisible = isVisible;_x000D_
chart.updateLayout();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getTickMarkStepHint()_x000D_
*/_x000D_
public int getTickMarkStepHint() {_x000D_
_x000D_
return tickMarkStepHint;_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#setTickMarkStepHint(int)_x000D_
*/_x000D_
public void setTickMarkStepHint(int tickMarkStepHint) {_x000D_
_x000D_
if(tickMarkStepHint < MIN_GRID_STEP_HINT) {_x000D_
this.tickMarkStepHint = DEFAULT_TICK_MARK_STEP_HINT;_x000D_
} else {_x000D_
this.tickMarkStepHint = tickMarkStepHint;_x000D_
}_x000D_
chart.updateLayout();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getTickLabelAngle()_x000D_
*/_x000D_
public int getTickLabelAngle() {_x000D_
_x000D_
return tickLabelAngle;_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#setTickLabelAngle(int)_x000D_
*/_x000D_
public void setTickLabelAngle(int angle) {_x000D_
_x000D_
if(angle < 0 || 90 < angle) {_x000D_
SWT.error(SWT.ERROR_INVALID_ARGUMENT);_x000D_
}_x000D_
if(tickLabelAngle != angle) {_x000D_
tickLabelAngle = angle;_x000D_
chart.updateLayout();_x000D_
}_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#setFormat(Format)_x000D_
*/_x000D_
public void setFormat(Format format) {_x000D_
_x000D_
axisTickLabels.setFormat(format);_x000D_
chart.updateLayout();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getFormat()_x000D_
*/_x000D_
public Format getFormat() {_x000D_
_x000D_
return axisTickLabels.getFormat();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getBounds()_x000D_
<SUF>*/_x000D_
public Rectangle getBounds() {_x000D_
_x000D_
Rectangle r1 = axisTickMarks.getBounds();_x000D_
Rectangle r2 = axisTickLabels.getBounds();_x000D_
Position position = axis.getPosition();_x000D_
if(position == Position.Primary && axis.isHorizontalAxis()) {_x000D_
return new Rectangle(r1.x, r1.y, r1.width, r1.height + r2.height);_x000D_
} else if(position == Position.Secondary && axis.isHorizontalAxis()) {_x000D_
return new Rectangle(r1.x, r2.y, r1.width, r1.height + r2.height);_x000D_
} else if(position == Position.Primary && !axis.isHorizontalAxis()) {_x000D_
return new Rectangle(r2.x, r1.y, r1.width + r2.width, r1.height);_x000D_
} else if(position == Position.Secondary && !axis.isHorizontalAxis()) {_x000D_
return new Rectangle(r1.x, r1.y, r1.width + r2.width, r1.height);_x000D_
} else {_x000D_
throw new IllegalStateException("unknown axis position");_x000D_
}_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getTickLabelValues()_x000D_
*/_x000D_
public double[] getTickLabelValues() {_x000D_
_x000D_
List<Double> list = axisTickLabels.getTickLabelValues();_x000D_
double[] values = new double[list.size()];_x000D_
for(int i = 0; i < values.length; i++) {_x000D_
values[i] = list.get(i);_x000D_
}_x000D_
return values;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Updates the tick around per 64 pixel._x000D_
*_x000D_
* @param length_x000D_
* the axis length_x000D_
*/_x000D_
public void updateTick(int length) {_x000D_
_x000D_
if(length <= 0) {_x000D_
axisTickLabels.update(1);_x000D_
} else {_x000D_
axisTickLabels.update(length);_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* Updates the tick layout._x000D_
*/_x000D_
protected void updateLayoutData() {_x000D_
_x000D_
axisTickLabels.updateLayoutData();_x000D_
axisTickMarks.updateLayoutData();_x000D_
}_x000D_
}_x000D_
| False | 3,144 | 27 | 3,537 | 28 | 3,620 | 29 | 3,537 | 28 | 3,941 | 31 | false | false | false | false | false | true |
3,910 | 189584_1 | package com.rs.utilities;
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;
}
}
| openrsx/open633-server | src/com/rs/utilities/MutableNumber.java | 1,978 | // pure lare code, echt ongelofelijk dit | line_comment | nl | package com.rs.utilities;
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;
}
}
| False | 1,609 | 12 | 1,801 | 14 | 1,914 | 11 | 1,801 | 14 | 2,059 | 13 | false | false | false | false | false | true |
1,669 | 30811_1 | package nl.sjoelclub.competitie.score;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional //Mag operaties op de database doen.
public class ScoreService {
@Autowired //Verbinding tussen repository en service. Zorgt ervoor dat je een object van Repository tot beschikking hebt (eigenlijk interface)
private ScoreRepository scoreRepository;
public Score save(Score score) {
return scoreRepository.save(score);
}
public Iterable<Score> findAll() { //Iterable is een verzameling op het hoogste niveau. Doorheenloopbaar.
Iterable<Score> result = scoreRepository.findAll();
return result;
}
}
| SweerenK/sjoelclub | src/main/java/nl/sjoelclub/competitie/score/ScoreService.java | 221 | //Verbinding tussen repository en service. Zorgt ervoor dat je een object van Repository tot beschikking hebt (eigenlijk interface) | line_comment | nl | package nl.sjoelclub.competitie.score;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional //Mag operaties op de database doen.
public class ScoreService {
@Autowired //Verbinding tussen<SUF>
private ScoreRepository scoreRepository;
public Score save(Score score) {
return scoreRepository.save(score);
}
public Iterable<Score> findAll() { //Iterable is een verzameling op het hoogste niveau. Doorheenloopbaar.
Iterable<Score> result = scoreRepository.findAll();
return result;
}
}
| True | 160 | 29 | 204 | 32 | 192 | 26 | 204 | 32 | 236 | 32 | false | false | false | false | false | true |
4,124 | 37735_6 | /*_x000D_
* To change this license header, choose License Headers in Project Properties._x000D_
* To change this template file, choose Tools | Templates_x000D_
* and open the template in the editor._x000D_
*/_x000D_
package gui;_x000D_
_x000D_
import domein.DomeinController;_x000D_
import javafx.event.ActionEvent;_x000D_
import javafx.event.EventHandler;_x000D_
import javafx.geometry.Insets;_x000D_
import javafx.geometry.Pos;_x000D_
import javafx.scene.Scene;_x000D_
import javafx.scene.control.Button;_x000D_
import javafx.scene.layout.BorderPane;_x000D_
import javafx.scene.layout.GridPane;_x000D_
import javafx.stage.Stage;_x000D_
_x000D_
_x000D_
/**_x000D_
*_x000D_
* @author bjorn_x000D_
*/_x000D_
public class Startscherm extends BorderPane {_x000D_
_x000D_
private final DomeinController dc;_x000D_
_x000D_
public Startscherm(DomeinController dc) {_x000D_
this.dc = dc;_x000D_
buildGui();_x000D_
}_x000D_
_x000D_
private void buildGui(){_x000D_
_x000D_
_x000D_
_x000D_
//Panes/Boxes/CSS ********************************************************************* _x000D_
getStylesheets().add("/css/startscherm.css");_x000D_
GridPane gpane = new GridPane();_x000D_
//setCancelDefault fzoiets vr via escape terug naar vorig scherm_x000D_
_x000D_
//Start button ************************************************************************ _x000D_
_x000D_
Button btnStart = new Button();_x000D_
btnStart.setOnAction(new EventHandler<ActionEvent>() {_x000D_
@Override_x000D_
public void handle(ActionEvent ae) {_x000D_
btnStartOnAction(ae);_x000D_
}_x000D_
});_x000D_
_x000D_
btnStart.setId("btnStart");_x000D_
btnStart.setPrefSize(200, 50);_x000D_
//btnStart.prefHeightProperty().bind(this.heightProperty().multiply(1));_x000D_
_x000D_
//Resume button ************************************************************************ _x000D_
// Enkel resume game als er al een game in het spel is!_x000D_
Button btnResume = new Button();_x000D_
btnResume.setOnAction(new EventHandler<ActionEvent>() {_x000D_
@Override_x000D_
public void handle(ActionEvent ae) {_x000D_
btnResumeOnAction(ae);_x000D_
}_x000D_
});_x000D_
_x000D_
btnResume.setDisable(true);_x000D_
btnResume.setId("btnResume");_x000D_
btnResume.setPrefSize(200, 50);_x000D_
//btnResume.prefHeightProperty().bind(this.heightProperty().multiply(1));_x000D_
_x000D_
//Highscores button ************************************************************************ _x000D_
Button btnHighScores = new Button();_x000D_
btnHighScores.setOnAction(new EventHandler<ActionEvent>() {_x000D_
@Override_x000D_
public void handle(ActionEvent ae) {_x000D_
btnHighscoresOnAction(ae);_x000D_
}_x000D_
});_x000D_
_x000D_
btnHighScores.setId("btnHighScores");_x000D_
btnHighScores.setPrefSize(200, 50);_x000D_
//btnHighscores.prefHeightProperty().bind(this.heightProperty().multiply(1));_x000D_
_x000D_
_x000D_
//Rules button ************************************************************************ _x000D_
Button btnGameRules = new Button();_x000D_
btnGameRules.setOnAction(new EventHandler<ActionEvent>() {_x000D_
@Override_x000D_
public void handle(ActionEvent ae) {_x000D_
btnGameRulesOnAction(ae);_x000D_
}_x000D_
});_x000D_
_x000D_
btnGameRules.setId("btnGameRules");_x000D_
btnGameRules.setPrefSize(200, 50);_x000D_
// btnHighscores.prefHeightProperty().bind(this.heightProperty().multiply(1));_x000D_
_x000D_
//Centering van de Gridpane ***************************************************************_x000D_
_x000D_
gpane.add(btnStart, 0, 0);_x000D_
gpane.add(btnResume, 0, 1);_x000D_
gpane.add(btnHighScores, 0, 2);_x000D_
gpane.add(btnGameRules, 0, 3);_x000D_
gpane.setAlignment(Pos.CENTER);_x000D_
gpane.setPadding(new Insets(50,5,5,5));_x000D_
gpane.setHgap(1);_x000D_
gpane.setVgap(1);_x000D_
setCenter(gpane);_x000D_
_x000D_
}_x000D_
_x000D_
private void btnStartOnAction(ActionEvent event)_x000D_
{_x000D_
//dc.deleteData() = mogelijke methode om nieuw spel te starten_x000D_
SpelersSettings ss = new SpelersSettings(this, dc);_x000D_
Scene scene = new Scene(ss, 1250, 700);_x000D_
Stage stage = (Stage) this.getScene().getWindow();_x000D_
stage.setScene(scene);_x000D_
stage.show(); _x000D_
_x000D_
}_x000D_
_x000D_
private void btnHighscoresOnAction(ActionEvent event)_x000D_
{_x000D_
HighscoreScherm hs = new HighscoreScherm(this, dc);_x000D_
Scene scene = new Scene(hs, 1250, 700);_x000D_
Stage stage = (Stage) this.getScene().getWindow();_x000D_
stage.setScene(scene);_x000D_
stage.show(); _x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
private void btnResumeOnAction(ActionEvent event)_x000D_
{/*_x000D_
// dc aanspreken + vullen met sepl dat laatste werd opgeslagen en onderbroken_x000D_
dc.vulDomein();_x000D_
OverzichtScherm overzichtscherm = new OverzichtScherm(dc,dc.geefSpelInfo()[1],1);_x000D_
Scene scene = new Scene(overzichtscherm,1250,700);_x000D_
Stage stage = (Stage) this.getScene().getWindow();_x000D_
stage.setScene(scene);_x000D_
stage.show(); _x000D_
*/_x000D_
}_x000D_
_x000D_
private void btnGameRulesOnAction(ActionEvent event)_x000D_
{_x000D_
GameRulesScherm grs = new GameRulesScherm(this, dc);_x000D_
Scene scene = new Scene(grs, 1250, 700);_x000D_
Stage stage = (Stage) this.getScene().getWindow();_x000D_
stage.setScene(scene);_x000D_
stage.show(); _x000D_
}_x000D_
}_x000D_
| rayzorg/regenworm | src/gui/Startscherm.java | 1,569 | // Enkel resume game als er al een game in het spel is!_x000D_ | line_comment | nl | /*_x000D_
* To change this license header, choose License Headers in Project Properties._x000D_
* To change this template file, choose Tools | Templates_x000D_
* and open the template in the editor._x000D_
*/_x000D_
package gui;_x000D_
_x000D_
import domein.DomeinController;_x000D_
import javafx.event.ActionEvent;_x000D_
import javafx.event.EventHandler;_x000D_
import javafx.geometry.Insets;_x000D_
import javafx.geometry.Pos;_x000D_
import javafx.scene.Scene;_x000D_
import javafx.scene.control.Button;_x000D_
import javafx.scene.layout.BorderPane;_x000D_
import javafx.scene.layout.GridPane;_x000D_
import javafx.stage.Stage;_x000D_
_x000D_
_x000D_
/**_x000D_
*_x000D_
* @author bjorn_x000D_
*/_x000D_
public class Startscherm extends BorderPane {_x000D_
_x000D_
private final DomeinController dc;_x000D_
_x000D_
public Startscherm(DomeinController dc) {_x000D_
this.dc = dc;_x000D_
buildGui();_x000D_
}_x000D_
_x000D_
private void buildGui(){_x000D_
_x000D_
_x000D_
_x000D_
//Panes/Boxes/CSS ********************************************************************* _x000D_
getStylesheets().add("/css/startscherm.css");_x000D_
GridPane gpane = new GridPane();_x000D_
//setCancelDefault fzoiets vr via escape terug naar vorig scherm_x000D_
_x000D_
//Start button ************************************************************************ _x000D_
_x000D_
Button btnStart = new Button();_x000D_
btnStart.setOnAction(new EventHandler<ActionEvent>() {_x000D_
@Override_x000D_
public void handle(ActionEvent ae) {_x000D_
btnStartOnAction(ae);_x000D_
}_x000D_
});_x000D_
_x000D_
btnStart.setId("btnStart");_x000D_
btnStart.setPrefSize(200, 50);_x000D_
//btnStart.prefHeightProperty().bind(this.heightProperty().multiply(1));_x000D_
_x000D_
//Resume button ************************************************************************ _x000D_
// Enkel resume<SUF>
Button btnResume = new Button();_x000D_
btnResume.setOnAction(new EventHandler<ActionEvent>() {_x000D_
@Override_x000D_
public void handle(ActionEvent ae) {_x000D_
btnResumeOnAction(ae);_x000D_
}_x000D_
});_x000D_
_x000D_
btnResume.setDisable(true);_x000D_
btnResume.setId("btnResume");_x000D_
btnResume.setPrefSize(200, 50);_x000D_
//btnResume.prefHeightProperty().bind(this.heightProperty().multiply(1));_x000D_
_x000D_
//Highscores button ************************************************************************ _x000D_
Button btnHighScores = new Button();_x000D_
btnHighScores.setOnAction(new EventHandler<ActionEvent>() {_x000D_
@Override_x000D_
public void handle(ActionEvent ae) {_x000D_
btnHighscoresOnAction(ae);_x000D_
}_x000D_
});_x000D_
_x000D_
btnHighScores.setId("btnHighScores");_x000D_
btnHighScores.setPrefSize(200, 50);_x000D_
//btnHighscores.prefHeightProperty().bind(this.heightProperty().multiply(1));_x000D_
_x000D_
_x000D_
//Rules button ************************************************************************ _x000D_
Button btnGameRules = new Button();_x000D_
btnGameRules.setOnAction(new EventHandler<ActionEvent>() {_x000D_
@Override_x000D_
public void handle(ActionEvent ae) {_x000D_
btnGameRulesOnAction(ae);_x000D_
}_x000D_
});_x000D_
_x000D_
btnGameRules.setId("btnGameRules");_x000D_
btnGameRules.setPrefSize(200, 50);_x000D_
// btnHighscores.prefHeightProperty().bind(this.heightProperty().multiply(1));_x000D_
_x000D_
//Centering van de Gridpane ***************************************************************_x000D_
_x000D_
gpane.add(btnStart, 0, 0);_x000D_
gpane.add(btnResume, 0, 1);_x000D_
gpane.add(btnHighScores, 0, 2);_x000D_
gpane.add(btnGameRules, 0, 3);_x000D_
gpane.setAlignment(Pos.CENTER);_x000D_
gpane.setPadding(new Insets(50,5,5,5));_x000D_
gpane.setHgap(1);_x000D_
gpane.setVgap(1);_x000D_
setCenter(gpane);_x000D_
_x000D_
}_x000D_
_x000D_
private void btnStartOnAction(ActionEvent event)_x000D_
{_x000D_
//dc.deleteData() = mogelijke methode om nieuw spel te starten_x000D_
SpelersSettings ss = new SpelersSettings(this, dc);_x000D_
Scene scene = new Scene(ss, 1250, 700);_x000D_
Stage stage = (Stage) this.getScene().getWindow();_x000D_
stage.setScene(scene);_x000D_
stage.show(); _x000D_
_x000D_
}_x000D_
_x000D_
private void btnHighscoresOnAction(ActionEvent event)_x000D_
{_x000D_
HighscoreScherm hs = new HighscoreScherm(this, dc);_x000D_
Scene scene = new Scene(hs, 1250, 700);_x000D_
Stage stage = (Stage) this.getScene().getWindow();_x000D_
stage.setScene(scene);_x000D_
stage.show(); _x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
private void btnResumeOnAction(ActionEvent event)_x000D_
{/*_x000D_
// dc aanspreken + vullen met sepl dat laatste werd opgeslagen en onderbroken_x000D_
dc.vulDomein();_x000D_
OverzichtScherm overzichtscherm = new OverzichtScherm(dc,dc.geefSpelInfo()[1],1);_x000D_
Scene scene = new Scene(overzichtscherm,1250,700);_x000D_
Stage stage = (Stage) this.getScene().getWindow();_x000D_
stage.setScene(scene);_x000D_
stage.show(); _x000D_
*/_x000D_
}_x000D_
_x000D_
private void btnGameRulesOnAction(ActionEvent event)_x000D_
{_x000D_
GameRulesScherm grs = new GameRulesScherm(this, dc);_x000D_
Scene scene = new Scene(grs, 1250, 700);_x000D_
Stage stage = (Stage) this.getScene().getWindow();_x000D_
stage.setScene(scene);_x000D_
stage.show(); _x000D_
}_x000D_
}_x000D_
| True | 2,131 | 22 | 2,293 | 23 | 2,394 | 21 | 2,293 | 23 | 2,589 | 23 | false | false | false | false | false | true |
4,778 | 109270_2 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.example.deals;
public final class R {
public static final class attr {
}
public static final class dimen {
public static final int Detail_horizontal_margin=0x7f050004;
public static final int Detail_vertical_margin=0x7f050005;
/**
Customize dimensions originally defined in res/values/dimens.xml (such as
screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here.
*/
public static final int activity_horizontal_margin=0x7f05000d;
public static final int coupon_horizontal_margin=0x7f050002;
public static final int coupon_vertical_margin=0x7f050003;
public static final int favor_vertical_margin=0x7f050007;
public static final int fbtwitter_horizontal_margin=0x7f050009;
public static final int fbtwitter_vertical_margin=0x7f05000a;
public static final int messagebox_horizontal_margin=0x7f05000b;
public static final int messagebox_vertical_margin=0x7f05000c;
public static final int redeem_text_vertical_margin=0x7f050008;
public static final int redeem_vertical_margin=0x7f050006;
/** Default screen margins, per the Android Design guidelines.
*/
public static final int tiles_horizontal_margin=0x7f050000;
public static final int tiles_vertical_margin=0x7f050001;
}
public static final class drawable {
public static final int back=0x7f020000;
public static final int background=0x7f020001;
public static final int box=0x7f020002;
public static final int box_signin_email=0x7f020003;
public static final int btn_fb=0x7f020004;
public static final int btn_fb_normal=0x7f020005;
public static final int btn_fb_pressed=0x7f020006;
public static final int couponcapitano=0x7f020007;
public static final int couponcastile=0x7f020008;
public static final int couponrexall=0x7f020009;
public static final int couponsushiworld=0x7f02000a;
public static final int coupontopsushi=0x7f02000b;
public static final int detailsbutton=0x7f02000c;
public static final int facebookbutton=0x7f02000d;
public static final int favicon=0x7f02000e;
public static final int favouritebutton=0x7f02000f;
public static final int fbiconoff=0x7f020010;
public static final int fbiconon=0x7f020011;
public static final int ic_launcher=0x7f020012;
public static final int logo=0x7f020013;
public static final int messageboxgray=0x7f020014;
public static final int navigationbar=0x7f020015;
public static final int redeembutton=0x7f020016;
public static final int redeemgreenicon=0x7f020017;
public static final int removefavbutton=0x7f020018;
public static final int search=0x7f020019;
public static final int splash=0x7f02001a;
public static final int takephotobutton=0x7f02001b;
public static final int textbox=0x7f02001c;
public static final int tile10=0x7f02001d;
public static final int twitterbutton=0x7f02001e;
public static final int twittericonoff=0x7f02001f;
public static final int twittericonon=0x7f020020;
}
public static final class id {
public static final int TextLayout=0x7f090005;
public static final int action_settings=0x7f090043;
public static final int bBack=0x7f090001;
public static final int bFavor=0x7f09000f;
public static final int bRedeem=0x7f09000a;
public static final int bSearch=0x7f09002b;
public static final int bStore=0x7f09000d;
public static final int bar=0x7f090000;
public static final int browser=0x7f090002;
public static final int btnFbSignIn=0x7f090011;
public static final int btnLoginTweet=0x7f090032;
public static final int btnSearch=0x7f090036;
public static final int btnTweet=0x7f090035;
public static final int buttonLayout=0x7f090008;
public static final int cbFacebook=0x7f090025;
public static final int cbFbAutoLogin=0x7f090012;
public static final int cbTwitter=0x7f090024;
public static final int detailFavorLayout=0x7f09000b;
public static final int detailLayout=0x7f09000c;
public static final int etEmail=0x7f090010;
public static final int etMessageBox=0x7f090028;
public static final int etSearch=0x7f090015;
public static final int etTweet=0x7f090034;
public static final int favorLayout=0x7f09000e;
public static final int highlight=0x7f09003a;
public static final int hyphen=0x7f09003d;
public static final int ivPhoto=0x7f090022;
public static final int ivRedeemButton=0x7f090023;
public static final int ivStore=0x7f090003;
public static final int ivTakePhoto=0x7f09002a;
public static final int ivTwitterUserImg=0x7f09003f;
public static final int ivc=0x7f090004;
public static final int layoutTwitter=0x7f090033;
public static final int lvEvents=0x7f090038;
public static final int lvTweets=0x7f090037;
public static final int redeemLayout=0x7f090009;
public static final int spDate=0x7f090013;
public static final int t1=0x7f090016;
public static final int t10=0x7f09001f;
public static final int t11=0x7f090020;
public static final int t12=0x7f090021;
public static final int t13=0x7f09002c;
public static final int t14=0x7f09002d;
public static final int t15=0x7f09002e;
public static final int t16=0x7f09002f;
public static final int t17=0x7f090030;
public static final int t18=0x7f090031;
public static final int t2=0x7f090017;
public static final int t3=0x7f090018;
public static final int t4=0x7f090019;
public static final int t5=0x7f09001a;
public static final int t6=0x7f09001b;
public static final int t7=0x7f09001c;
public static final int t8=0x7f09001d;
public static final int t9=0x7f09001e;
public static final int tvDetail=0x7f090007;
public static final int tvEndTime_event=0x7f09003e;
public static final int tvHeader_event=0x7f090039;
public static final int tvMainDis=0x7f090006;
public static final int tvRedeem=0x7f090026;
public static final int tvStartTime_event=0x7f09003c;
public static final int tvTitle_event=0x7f09003b;
public static final int tvTwitterDate=0x7f090041;
public static final int tvTwitterTweet=0x7f090042;
public static final int tvTwitterUser=0x7f090040;
public static final int tvUnderCamera=0x7f090027;
public static final int tvUnderMessageBox=0x7f090029;
public static final int viewPager=0x7f090014;
}
public static final class layout {
public static final int activity_browser=0x7f030000;
public static final int activity_coupon=0x7f030001;
public static final int activity_login=0x7f030002;
public static final int activity_scheduler=0x7f030003;
public static final int activity_search_favor=0x7f030004;
public static final int activity_share=0x7f030005;
public static final int activity_splash=0x7f030006;
public static final int activity_tiles=0x7f030007;
public static final int activity_twitterfeed=0x7f030008;
public static final int fragment_day=0x7f030009;
public static final int item_list_event=0x7f03000a;
public static final int item_list_tweet=0x7f03000b;
public static final int item_spinner=0x7f03000c;
}
public static final class menu {
public static final int splash=0x7f080000;
}
public static final class raw {
public static final int coupons=0x7f040000;
public static final int jsondealsfile=0x7f040001;
public static final int show=0x7f040002;
public static final int tiles=0x7f040003;
}
public static final class string {
public static final int Details=0x7f060004;
public static final int action_settings=0x7f060001;
public static final int app_id=0x7f060006;
public static final int app_name=0x7f060000;
public static final int hello_world=0x7f060002;
public static final int link=0x7f060003;
public static final int reedem_offer=0x7f060005;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
API 11 theme customizations can go here.
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
API 14 theme customizations can go here.
*/
public static final int AppBaseTheme=0x7f070000;
/** Application theme.
All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f070001;
}
}
| yixiu17/Dealshype | gen/com/example/deals/R.java | 3,004 | /** Default screen margins, per the Android Design guidelines.
*/ | block_comment | nl | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.example.deals;
public final class R {
public static final class attr {
}
public static final class dimen {
public static final int Detail_horizontal_margin=0x7f050004;
public static final int Detail_vertical_margin=0x7f050005;
/**
Customize dimensions originally defined in res/values/dimens.xml (such as
screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here.
*/
public static final int activity_horizontal_margin=0x7f05000d;
public static final int coupon_horizontal_margin=0x7f050002;
public static final int coupon_vertical_margin=0x7f050003;
public static final int favor_vertical_margin=0x7f050007;
public static final int fbtwitter_horizontal_margin=0x7f050009;
public static final int fbtwitter_vertical_margin=0x7f05000a;
public static final int messagebox_horizontal_margin=0x7f05000b;
public static final int messagebox_vertical_margin=0x7f05000c;
public static final int redeem_text_vertical_margin=0x7f050008;
public static final int redeem_vertical_margin=0x7f050006;
/** Default screen margins,<SUF>*/
public static final int tiles_horizontal_margin=0x7f050000;
public static final int tiles_vertical_margin=0x7f050001;
}
public static final class drawable {
public static final int back=0x7f020000;
public static final int background=0x7f020001;
public static final int box=0x7f020002;
public static final int box_signin_email=0x7f020003;
public static final int btn_fb=0x7f020004;
public static final int btn_fb_normal=0x7f020005;
public static final int btn_fb_pressed=0x7f020006;
public static final int couponcapitano=0x7f020007;
public static final int couponcastile=0x7f020008;
public static final int couponrexall=0x7f020009;
public static final int couponsushiworld=0x7f02000a;
public static final int coupontopsushi=0x7f02000b;
public static final int detailsbutton=0x7f02000c;
public static final int facebookbutton=0x7f02000d;
public static final int favicon=0x7f02000e;
public static final int favouritebutton=0x7f02000f;
public static final int fbiconoff=0x7f020010;
public static final int fbiconon=0x7f020011;
public static final int ic_launcher=0x7f020012;
public static final int logo=0x7f020013;
public static final int messageboxgray=0x7f020014;
public static final int navigationbar=0x7f020015;
public static final int redeembutton=0x7f020016;
public static final int redeemgreenicon=0x7f020017;
public static final int removefavbutton=0x7f020018;
public static final int search=0x7f020019;
public static final int splash=0x7f02001a;
public static final int takephotobutton=0x7f02001b;
public static final int textbox=0x7f02001c;
public static final int tile10=0x7f02001d;
public static final int twitterbutton=0x7f02001e;
public static final int twittericonoff=0x7f02001f;
public static final int twittericonon=0x7f020020;
}
public static final class id {
public static final int TextLayout=0x7f090005;
public static final int action_settings=0x7f090043;
public static final int bBack=0x7f090001;
public static final int bFavor=0x7f09000f;
public static final int bRedeem=0x7f09000a;
public static final int bSearch=0x7f09002b;
public static final int bStore=0x7f09000d;
public static final int bar=0x7f090000;
public static final int browser=0x7f090002;
public static final int btnFbSignIn=0x7f090011;
public static final int btnLoginTweet=0x7f090032;
public static final int btnSearch=0x7f090036;
public static final int btnTweet=0x7f090035;
public static final int buttonLayout=0x7f090008;
public static final int cbFacebook=0x7f090025;
public static final int cbFbAutoLogin=0x7f090012;
public static final int cbTwitter=0x7f090024;
public static final int detailFavorLayout=0x7f09000b;
public static final int detailLayout=0x7f09000c;
public static final int etEmail=0x7f090010;
public static final int etMessageBox=0x7f090028;
public static final int etSearch=0x7f090015;
public static final int etTweet=0x7f090034;
public static final int favorLayout=0x7f09000e;
public static final int highlight=0x7f09003a;
public static final int hyphen=0x7f09003d;
public static final int ivPhoto=0x7f090022;
public static final int ivRedeemButton=0x7f090023;
public static final int ivStore=0x7f090003;
public static final int ivTakePhoto=0x7f09002a;
public static final int ivTwitterUserImg=0x7f09003f;
public static final int ivc=0x7f090004;
public static final int layoutTwitter=0x7f090033;
public static final int lvEvents=0x7f090038;
public static final int lvTweets=0x7f090037;
public static final int redeemLayout=0x7f090009;
public static final int spDate=0x7f090013;
public static final int t1=0x7f090016;
public static final int t10=0x7f09001f;
public static final int t11=0x7f090020;
public static final int t12=0x7f090021;
public static final int t13=0x7f09002c;
public static final int t14=0x7f09002d;
public static final int t15=0x7f09002e;
public static final int t16=0x7f09002f;
public static final int t17=0x7f090030;
public static final int t18=0x7f090031;
public static final int t2=0x7f090017;
public static final int t3=0x7f090018;
public static final int t4=0x7f090019;
public static final int t5=0x7f09001a;
public static final int t6=0x7f09001b;
public static final int t7=0x7f09001c;
public static final int t8=0x7f09001d;
public static final int t9=0x7f09001e;
public static final int tvDetail=0x7f090007;
public static final int tvEndTime_event=0x7f09003e;
public static final int tvHeader_event=0x7f090039;
public static final int tvMainDis=0x7f090006;
public static final int tvRedeem=0x7f090026;
public static final int tvStartTime_event=0x7f09003c;
public static final int tvTitle_event=0x7f09003b;
public static final int tvTwitterDate=0x7f090041;
public static final int tvTwitterTweet=0x7f090042;
public static final int tvTwitterUser=0x7f090040;
public static final int tvUnderCamera=0x7f090027;
public static final int tvUnderMessageBox=0x7f090029;
public static final int viewPager=0x7f090014;
}
public static final class layout {
public static final int activity_browser=0x7f030000;
public static final int activity_coupon=0x7f030001;
public static final int activity_login=0x7f030002;
public static final int activity_scheduler=0x7f030003;
public static final int activity_search_favor=0x7f030004;
public static final int activity_share=0x7f030005;
public static final int activity_splash=0x7f030006;
public static final int activity_tiles=0x7f030007;
public static final int activity_twitterfeed=0x7f030008;
public static final int fragment_day=0x7f030009;
public static final int item_list_event=0x7f03000a;
public static final int item_list_tweet=0x7f03000b;
public static final int item_spinner=0x7f03000c;
}
public static final class menu {
public static final int splash=0x7f080000;
}
public static final class raw {
public static final int coupons=0x7f040000;
public static final int jsondealsfile=0x7f040001;
public static final int show=0x7f040002;
public static final int tiles=0x7f040003;
}
public static final class string {
public static final int Details=0x7f060004;
public static final int action_settings=0x7f060001;
public static final int app_id=0x7f060006;
public static final int app_name=0x7f060000;
public static final int hello_world=0x7f060002;
public static final int link=0x7f060003;
public static final int reedem_offer=0x7f060005;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
API 11 theme customizations can go here.
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
API 14 theme customizations can go here.
*/
public static final int AppBaseTheme=0x7f070000;
/** Application theme.
All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f070001;
}
}
| False | 3,169 | 15 | 3,262 | 14 | 3,426 | 16 | 3,262 | 14 | 3,538 | 19 | false | false | false | false | false | true |
3,536 | 136342_19 | import java.util.*;
public class IntStack {
int[] stack;
int top;
public IntStack(int size) {
top=0;
stack = new int[size];
}
public void print() {
for(int i=0; i<top; i++){
System.out.println(stack[(top-1)-i]);
}
}
boolean isEmpty() {
//top==0 returns true or false
return top==0;
}
void push(int num) {
//++ happens after (does at the end of the line)
stack[top++]=num;
}
int pop() {
//--happens before and changes top only if there is something left to pop
if(isEmpty()==false){
return stack[--top];
}
return -1;
}
//Alia
int depth(){
//returns the depth, same as top
int depth = top;
return depth;
}
//Alia
/* int[] popfrompoint(int popoint){
// pop all from point that is input
int i = 0;
int[] popped = new int[top- popoint];
while (top > popoint){
popped[i++] = stack[top--];
}
// print the array
for (int b = 1; b < popped.length; b++){
System.out.print(popped[b] + " ");
}
System.out.println();
return popped;
}
*/
int peek(){
return stack[top-1];
}
IntStack reverseStack(){
//make a newStack thats empty
IntStack newStack = new IntStack(stack.length);
while (! isEmpty()){ //repeat until isEmpty()
int p = pop(); //pop the top item and push that onto the newStack
newStack.push(p);
}
return newStack; //return newStack
}
IntStack sort() {
//create two new empty stacks
IntStack newStack1 = new IntStack(stack.length);
IntStack newStack2 = new IntStack(stack.length);
while (! isEmpty()){ //repeat until isEmpty()
int p = peek(); //peek top number of original stack
if(p<5){ //if its less than five, pop it and push it onto the first new stack
newStack1.push(p);
}
else { //if its greater than or equal to five, pop it and push it onto the second new stack
newStack2.push(p);
}
}
newStack1.push(newStack2.pop()); //pop the top number of the second new stack and push it onto the first new stack
return newStack1;
}
int[] popAll() {
//make array of size top, fill that with all items in stack, and then return the array
int[] popAll = new int[top];
for(int i = 0; !isEmpty(); i++)
{
popAll[i]= pop();
System.out.println(popAll[i]);
}
return popAll;
}
int[] ascend() {
int[] ascend = new int[top];
ascend = popAll();
Arrays.sort(ascend);
return ascend;
}
int[] descend() {
int[] descend = new int[top];
descend = popAll();
Arrays.sort(descend);
reverse(descend);
return descend;
}
//peak all the values in the stack
int[] peekAll() {
//fill new int array peakAll with length stack.length
int[] peekAll = new int[stack.length];
//fill peakAll with values of stack[], stopping before "top" of stack
for(int i=0; i<top; i++) {
peekAll[i] = stack[i];
}
//return created stack
return peekAll;
}
//peek certain value in stack
int peekAt(int position) {
//returns zero if you peek value that is at or above top
if(position>=top) return 0;
//return the position
return stack[position];
}
//taken from stackoverflow
public static void reverse(int[] data) {
for (int left = 0, right = data.length - 1; left < right; left++, right--) {
// swap the values at the left and right indices
int temp = data[left];
data[left] = data[right];
data[right] = temp;
}
}
public static void main(String[] args) {
IntStack is = new IntStack(10);
//push things in stack
is.push(4);
is.push(5);
is.push(8);
is.push(7);
is.push(8);
is.push(3);
is.push(4);
int k = is.pop();
System.out.println(k);
//Rachel -- reverse stack
IntStack is_rev = is.reverseStack();
int bottom = is_rev.pop();
System.out.println(bottom);
//Rachel -- sort
IntStack is_sort = is.sort();
is_sort.print();
//testing peek all method
int[] mm = is.peekAll();
System.out.println(Arrays.toString(mm));
//testing peek at position 2
int p = is.peekAt(2);
System.out.println(p);
// tests for depth:
int d = is.depth();
System.out.println(d);
//tests for pop from point: this pops all of them out of the array until there are only the number you choose left
//is.popfrompoint(2);
//peek all
int[] mmm = is.peekAll();
System.out.println(Arrays.toString(mmm));
//restoring stack
is.push(7);
is.push(5);
is.push(3);
is.push(2);
//peek all
int[] mmmm = is.peekAll();
System.out.println(Arrays.toString(mmmm));
//tests for popall:
is.push(4);
is.push(5);
is.push(6);
int[] j = is.popAll(); //i expect an array of size 3 with 6,5,4
System.out.println(Arrays.toString(j));
// test for ascend
is.push(4);
is.push(5);
is.push(6);
int[] l = is.ascend(); // i expect an array of size 3 with 4,5,6
System.out.println(Arrays.toString(l));
//test for descend
is.push(4);
is.push(5);
is.push(6);
int[] m = is.descend(); // i expect an array of size 3 with 6,5,4
System.out.println(Arrays.toString(m));
}
}
| maguerosinclair/stack | IntStack.java | 1,880 | //peek certain value in stack | line_comment | nl | import java.util.*;
public class IntStack {
int[] stack;
int top;
public IntStack(int size) {
top=0;
stack = new int[size];
}
public void print() {
for(int i=0; i<top; i++){
System.out.println(stack[(top-1)-i]);
}
}
boolean isEmpty() {
//top==0 returns true or false
return top==0;
}
void push(int num) {
//++ happens after (does at the end of the line)
stack[top++]=num;
}
int pop() {
//--happens before and changes top only if there is something left to pop
if(isEmpty()==false){
return stack[--top];
}
return -1;
}
//Alia
int depth(){
//returns the depth, same as top
int depth = top;
return depth;
}
//Alia
/* int[] popfrompoint(int popoint){
// pop all from point that is input
int i = 0;
int[] popped = new int[top- popoint];
while (top > popoint){
popped[i++] = stack[top--];
}
// print the array
for (int b = 1; b < popped.length; b++){
System.out.print(popped[b] + " ");
}
System.out.println();
return popped;
}
*/
int peek(){
return stack[top-1];
}
IntStack reverseStack(){
//make a newStack thats empty
IntStack newStack = new IntStack(stack.length);
while (! isEmpty()){ //repeat until isEmpty()
int p = pop(); //pop the top item and push that onto the newStack
newStack.push(p);
}
return newStack; //return newStack
}
IntStack sort() {
//create two new empty stacks
IntStack newStack1 = new IntStack(stack.length);
IntStack newStack2 = new IntStack(stack.length);
while (! isEmpty()){ //repeat until isEmpty()
int p = peek(); //peek top number of original stack
if(p<5){ //if its less than five, pop it and push it onto the first new stack
newStack1.push(p);
}
else { //if its greater than or equal to five, pop it and push it onto the second new stack
newStack2.push(p);
}
}
newStack1.push(newStack2.pop()); //pop the top number of the second new stack and push it onto the first new stack
return newStack1;
}
int[] popAll() {
//make array of size top, fill that with all items in stack, and then return the array
int[] popAll = new int[top];
for(int i = 0; !isEmpty(); i++)
{
popAll[i]= pop();
System.out.println(popAll[i]);
}
return popAll;
}
int[] ascend() {
int[] ascend = new int[top];
ascend = popAll();
Arrays.sort(ascend);
return ascend;
}
int[] descend() {
int[] descend = new int[top];
descend = popAll();
Arrays.sort(descend);
reverse(descend);
return descend;
}
//peak all the values in the stack
int[] peekAll() {
//fill new int array peakAll with length stack.length
int[] peekAll = new int[stack.length];
//fill peakAll with values of stack[], stopping before "top" of stack
for(int i=0; i<top; i++) {
peekAll[i] = stack[i];
}
//return created stack
return peekAll;
}
//peek certain<SUF>
int peekAt(int position) {
//returns zero if you peek value that is at or above top
if(position>=top) return 0;
//return the position
return stack[position];
}
//taken from stackoverflow
public static void reverse(int[] data) {
for (int left = 0, right = data.length - 1; left < right; left++, right--) {
// swap the values at the left and right indices
int temp = data[left];
data[left] = data[right];
data[right] = temp;
}
}
public static void main(String[] args) {
IntStack is = new IntStack(10);
//push things in stack
is.push(4);
is.push(5);
is.push(8);
is.push(7);
is.push(8);
is.push(3);
is.push(4);
int k = is.pop();
System.out.println(k);
//Rachel -- reverse stack
IntStack is_rev = is.reverseStack();
int bottom = is_rev.pop();
System.out.println(bottom);
//Rachel -- sort
IntStack is_sort = is.sort();
is_sort.print();
//testing peek all method
int[] mm = is.peekAll();
System.out.println(Arrays.toString(mm));
//testing peek at position 2
int p = is.peekAt(2);
System.out.println(p);
// tests for depth:
int d = is.depth();
System.out.println(d);
//tests for pop from point: this pops all of them out of the array until there are only the number you choose left
//is.popfrompoint(2);
//peek all
int[] mmm = is.peekAll();
System.out.println(Arrays.toString(mmm));
//restoring stack
is.push(7);
is.push(5);
is.push(3);
is.push(2);
//peek all
int[] mmmm = is.peekAll();
System.out.println(Arrays.toString(mmmm));
//tests for popall:
is.push(4);
is.push(5);
is.push(6);
int[] j = is.popAll(); //i expect an array of size 3 with 6,5,4
System.out.println(Arrays.toString(j));
// test for ascend
is.push(4);
is.push(5);
is.push(6);
int[] l = is.ascend(); // i expect an array of size 3 with 4,5,6
System.out.println(Arrays.toString(l));
//test for descend
is.push(4);
is.push(5);
is.push(6);
int[] m = is.descend(); // i expect an array of size 3 with 6,5,4
System.out.println(Arrays.toString(m));
}
}
| False | 1,411 | 6 | 1,724 | 6 | 1,813 | 6 | 1,724 | 6 | 1,901 | 7 | false | false | false | false | false | true |
3,191 | 107696_8 | package org.jcryptool.visual.aco.view;
import java.awt.Point;
import java.util.Vector;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.jcryptool.visual.aco.controller.AntColEventController;
import org.jcryptool.visual.aco.model.CommonModel;
public class AntColGraphComposite extends Composite {
private static final int KNOTRADIUS = 120;
private static final int ANTRADIUS = 90;
private CommonModel m;
private Canvas canv;
private int x; // Position Ameise
private int y;
private int x2; // Ziel Ameise
private int y2;
private boolean isAnimationRunning = false;
private final Color highlightColor = new Color(this.getDisplay(), 100, 190,
0);
private Color normalColor = new Color(this.getDisplay(), 50, 120, 50);
private Color antColor = new Color(this.getDisplay(), 139, 90, 40);
private Color eyeColor = new Color(this.getDisplay(), 255, 255, 255);
private AntColEventController controller;
/**
* Konstruktor erhaelt Model und Parent.
*
* @param model
* @param c
*/
public AntColGraphComposite(CommonModel model, Composite c) {
super(c, SWT.NONE);
this.m = model;
setLayout(new GridLayout(1, false));
redraw();
}
public void redraw() {
super.redraw();
// visualisierung nur zeigen, wenn die schlüssellänge zwischen 3 und 5
// ist.
if (canv != null) {
canv.dispose();
}
GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
data.widthHint = 365;
// data.heightHint = 365;
canv = new Canvas(this, SWT.NONE);
canv.setLayoutData(data);
// Listener, der festlegt was geschieht wenn redraw aufgerufen wird
canv.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
// Fall: Entschluesselung darstellen
drawKnots(e); // Graph zeichnen
if (m.getState() != 0) {
drawAllPropabilities(e);
drawTrail(e);
// if (m.isAnimateable()) // Ameise zeichnen
drawAnt(e, new Point(x, y), new Point(x2, y2));
}
}
});
setAnt();
layout();
}
public void animationStep() {
final Display d = this.getDisplay();
x2 = getAntCoord(m.getKnot())[0];
y2 = getAntCoord(m.getKnot())[1];
// Schrittweite
isAnimationRunning = true;
final int diffx = (int) (Math.abs(x - x2) / 15 + 0.5);
final int diffy = (int) (Math.abs(y - y2) / 15 + 0.5);
// Thread, der Bewegung uebernimmt
Runnable runnable = new Runnable() {
public void run() {
// Schritt
if (x - x2 > 0)
x -= diffx;
else
x += diffx;
if (y - y2 > 0)
y -= diffy;
else
y += diffy;
if (Math.abs(x - x2) > 15 || Math.abs(y - y2) > 15) {
canv.redraw(); // neu zeichnen
d.timerExec(150, this); // Schleife
} else { // angekommen
setAnt();
canv.redraw(); // neu zeichnen
controller.afterGraphDrawn();
isAnimationRunning = false;
}
}
};
d.timerExec(1, runnable); // Starten
}
private void drawKnots(PaintEvent e) {
e.gc.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));
String[] knots = m.getKnots();
Vector<Integer> trail = m.getTrail();
for (int i = 0; i < knots.length; i++) {
int[] a = this.getKnotCoord(i);
drawKnot(e, knots[i], a[0], a[1], trail.contains(i), i + 1);
}
}
/**
* Zeichnet den von der Ameise zurueckgelegten Weg auf das Canvas
*
* @param e
* PaintEvent
*/
private void drawTrail(PaintEvent e) {
Vector<Integer> weg = m.getTrail();
if (weg.size() > 1) {
for (int i = 0; i < weg.size() - 1; i++) {
drawKante(e, weg.elementAt(i), weg.elementAt(i + 1));
}
}
}
public void drawAllPropabilities(PaintEvent e) {
String[] knots = m.getKnots();
double[] probs = m.getProbabilities(); // W'keiten holen
for(int i = 0; i < knots.length; i++){
int[] a = getKnotCoord(i);
drawPropability(e, a[0], a[1], probs[i]);
}
}
private void drawPropability(PaintEvent e, int x, int y, double prob) {
if (prob > 0) { // W'keit
String str = prob * 100 + ""; //$NON-NLS-1$
str = str.substring(0, str.indexOf('.') + 2) + " %"; //$NON-NLS-1$
if(y < 180){
y -= 43;
} else {
y += 32;
}
e.gc.setBackground(highlightColor);
e.gc.drawString(str, x-18, y);
}
}
/**
* Zeichnet eine Kante des Weges von Knoten i zu Knoten j;
*
* @param e
* PaintEvent
* @param i
* Knoten i
* @param j
* Knoten j
*/
private void drawKante(PaintEvent e, int i, int j) {
e.gc.setForeground(highlightColor);
int[] a = this.getKnotCoord(i);
int[] b = this.getKnotCoord(j);
e.gc.drawLine(a[0], a[1], b[0], b[1]);
}
/**
* Zeichnet einen Knoten bei den uebergebenen Koordinaten und mit dem
* uebergebenen Text, Nummer und Wahrscheinlichkeit auf das Canvas.
*
* @param e
* PaintEvent
* @param s
* Spalte die zum Knoten gehoert
* @param x
* x-Koordinate Knoten
* @param y
* y-Koordinate Knoten
* @param set
* Knoten bereits passiert?
* @param prob
* W'keit, dass Ameise zu diesem Knoten im naechsten Schritt geht
* @param nr
* Knotennummer
*/
private void drawKnot(PaintEvent e, String s, int x, int y, boolean set,
int nr) {
if (set) // wenn bereits passiert in gruen
e.gc.setBackground(highlightColor);
else
e.gc.setBackground(normalColor);
// Kreis und Nummer zeichnen
e.gc.fillOval(x - 32, y - 32, 65, 65);
e.gc.drawString(nr + "", x -22, y -12); //$NON-NLS-1$
if (s.length() > 5)
s = s.substring(0, 5);
for (int i = 0; i < s.length(); i++) { // Text
e.gc.drawString(
Character.toUpperCase(s.charAt(i)) + "", x, y + 12 * (i + 1) - 40); //$NON-NLS-1$
}
}
public void destroyGraph() {
canv.dispose();
}
/**
* Zeichnet eine Ameise beim Punkt p auf das Canvas mit Orientierung
* Richtung Punkt p2
*
* @param e
* PaintEvent
* @param p
* Ort der Ameise
* @param p2
* Orientierung der Ameise
*/
private void drawAnt(PaintEvent e, Point p, Point p2) {
Color col = antColor;
e.gc.setBackground(col);
e.gc.fillOval(p.x, p.y, 15, 15);
double x = p2.x - p.x;
double y = p2.y - p.y;
// Laenge Vektor
double n = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
x /= n;
y /= n;
// Rumpf
e.gc.fillOval((int) (p.x + 15 * x), (int) (p.y + 15 * y), 15, 15);
e.gc.fillOval((int) (p.x - 15 * x), (int) (p.y - 15 * y), 15, 15);
// Fuehler
col = new Color(this.getDisplay(), 150, 150, 150);
e.gc.setForeground(col);
e.gc.drawLine((int) (p.x + 7 + 20 * x + 3 * y),
(int) (p.y + 7 + 20 * y - 3 * x),
(int) (p.x + 7 + 26 * x + 3 * y),
(int) (p.y + 7 + 26 * y - 3 * x));
e.gc.drawLine((int) (p.x + 7 + 20 * x - 3 * y),
(int) (p.y + 7 + 20 * y + 3 * x),
(int) (p.x + 7 + 26 * x - 3 * y),
(int) (p.y + 7 + 26 * y + 3 * x));
// Augen
// col = Display.getCurrent().getSystemColor(SWT.COLOR_WHITE);
e.gc.setBackground(eyeColor);
e.gc.fillOval((int) (p.x + 7 + 17 * x + 3 * y),
(int) (p.y + 7 + 17 * y - 3 * x), 3, 3);
e.gc.fillOval((int) (p.x + 7 + 17 * x - 3 * y),
(int) (p.y + 7 + 17 * y + 3 * x), 3, 3);
// col.dispose();*/
}
/**
* Liefert die Koordinaten, wo die Ameise platziert werden muss, wenn sie
* sich bei Knoten i befindet.
*
* @param i
* Knoten, bei dem sich die Ameise befindet
* @return c Array mit zugehoerigen Koordinaten
*/
private int[] getAntCoord(int i) {
return getCircleCoord(i, ANTRADIUS, new Point(175, 152));
}
private int[] getKnotCoord(int i) {
return getCircleCoord(i, KNOTRADIUS, new Point(183,160));
}
private int[] getCircleCoord(int i, int radius, Point center) {
int size = m.getSize();
int[] out = new int[2];
out[0] = (int) (Math.cos(Math.PI * 2 * (double) i / size + Math.PI /2-Math.PI/ size) * radius + center.x);
out[1] = (int) (Math.sin(Math.PI * 2 * (double) i / size + Math.PI /2-Math.PI/ size) * radius + center.y);
return out;
}
/**
* Setzt die Koordinaten, wo sich die Ameise befindet in Abhaengigkeit von
* dem jeweils aktuellen Knoten.
*
*/
private void setAnt() {
int i = m.getKnot();
int[] a = this.getAntCoord(i);
int oldX = x;
int oldY = y;
x = a[0];
y = a[1];
x2 = -(a[1]-172) + a[0];
y2 = (a[0]-172) + a[1];
int scalarProd = (x-oldX)*(x2-x)+(y-oldY)*(y2-y);
if(scalarProd < 0){
x2 = (a[1]-172) + a[0];
y2 = -(a[0]-172) + a[1];
}
}
public boolean isAnimationRunning() {
return isAnimationRunning;
}
public void addController(AntColEventController reg) {
this.controller = reg;
}
}
| jcryptool/crypto | org.jcryptool.visual.aco/src/org/jcryptool/visual/aco/view/AntColGraphComposite.java | 3,722 | /**
* Zeichnet eine Kante des Weges von Knoten i zu Knoten j;
*
* @param e
* PaintEvent
* @param i
* Knoten i
* @param j
* Knoten j
*/ | block_comment | nl | package org.jcryptool.visual.aco.view;
import java.awt.Point;
import java.util.Vector;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.jcryptool.visual.aco.controller.AntColEventController;
import org.jcryptool.visual.aco.model.CommonModel;
public class AntColGraphComposite extends Composite {
private static final int KNOTRADIUS = 120;
private static final int ANTRADIUS = 90;
private CommonModel m;
private Canvas canv;
private int x; // Position Ameise
private int y;
private int x2; // Ziel Ameise
private int y2;
private boolean isAnimationRunning = false;
private final Color highlightColor = new Color(this.getDisplay(), 100, 190,
0);
private Color normalColor = new Color(this.getDisplay(), 50, 120, 50);
private Color antColor = new Color(this.getDisplay(), 139, 90, 40);
private Color eyeColor = new Color(this.getDisplay(), 255, 255, 255);
private AntColEventController controller;
/**
* Konstruktor erhaelt Model und Parent.
*
* @param model
* @param c
*/
public AntColGraphComposite(CommonModel model, Composite c) {
super(c, SWT.NONE);
this.m = model;
setLayout(new GridLayout(1, false));
redraw();
}
public void redraw() {
super.redraw();
// visualisierung nur zeigen, wenn die schlüssellänge zwischen 3 und 5
// ist.
if (canv != null) {
canv.dispose();
}
GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
data.widthHint = 365;
// data.heightHint = 365;
canv = new Canvas(this, SWT.NONE);
canv.setLayoutData(data);
// Listener, der festlegt was geschieht wenn redraw aufgerufen wird
canv.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
// Fall: Entschluesselung darstellen
drawKnots(e); // Graph zeichnen
if (m.getState() != 0) {
drawAllPropabilities(e);
drawTrail(e);
// if (m.isAnimateable()) // Ameise zeichnen
drawAnt(e, new Point(x, y), new Point(x2, y2));
}
}
});
setAnt();
layout();
}
public void animationStep() {
final Display d = this.getDisplay();
x2 = getAntCoord(m.getKnot())[0];
y2 = getAntCoord(m.getKnot())[1];
// Schrittweite
isAnimationRunning = true;
final int diffx = (int) (Math.abs(x - x2) / 15 + 0.5);
final int diffy = (int) (Math.abs(y - y2) / 15 + 0.5);
// Thread, der Bewegung uebernimmt
Runnable runnable = new Runnable() {
public void run() {
// Schritt
if (x - x2 > 0)
x -= diffx;
else
x += diffx;
if (y - y2 > 0)
y -= diffy;
else
y += diffy;
if (Math.abs(x - x2) > 15 || Math.abs(y - y2) > 15) {
canv.redraw(); // neu zeichnen
d.timerExec(150, this); // Schleife
} else { // angekommen
setAnt();
canv.redraw(); // neu zeichnen
controller.afterGraphDrawn();
isAnimationRunning = false;
}
}
};
d.timerExec(1, runnable); // Starten
}
private void drawKnots(PaintEvent e) {
e.gc.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));
String[] knots = m.getKnots();
Vector<Integer> trail = m.getTrail();
for (int i = 0; i < knots.length; i++) {
int[] a = this.getKnotCoord(i);
drawKnot(e, knots[i], a[0], a[1], trail.contains(i), i + 1);
}
}
/**
* Zeichnet den von der Ameise zurueckgelegten Weg auf das Canvas
*
* @param e
* PaintEvent
*/
private void drawTrail(PaintEvent e) {
Vector<Integer> weg = m.getTrail();
if (weg.size() > 1) {
for (int i = 0; i < weg.size() - 1; i++) {
drawKante(e, weg.elementAt(i), weg.elementAt(i + 1));
}
}
}
public void drawAllPropabilities(PaintEvent e) {
String[] knots = m.getKnots();
double[] probs = m.getProbabilities(); // W'keiten holen
for(int i = 0; i < knots.length; i++){
int[] a = getKnotCoord(i);
drawPropability(e, a[0], a[1], probs[i]);
}
}
private void drawPropability(PaintEvent e, int x, int y, double prob) {
if (prob > 0) { // W'keit
String str = prob * 100 + ""; //$NON-NLS-1$
str = str.substring(0, str.indexOf('.') + 2) + " %"; //$NON-NLS-1$
if(y < 180){
y -= 43;
} else {
y += 32;
}
e.gc.setBackground(highlightColor);
e.gc.drawString(str, x-18, y);
}
}
/**
* Zeichnet eine Kante<SUF>*/
private void drawKante(PaintEvent e, int i, int j) {
e.gc.setForeground(highlightColor);
int[] a = this.getKnotCoord(i);
int[] b = this.getKnotCoord(j);
e.gc.drawLine(a[0], a[1], b[0], b[1]);
}
/**
* Zeichnet einen Knoten bei den uebergebenen Koordinaten und mit dem
* uebergebenen Text, Nummer und Wahrscheinlichkeit auf das Canvas.
*
* @param e
* PaintEvent
* @param s
* Spalte die zum Knoten gehoert
* @param x
* x-Koordinate Knoten
* @param y
* y-Koordinate Knoten
* @param set
* Knoten bereits passiert?
* @param prob
* W'keit, dass Ameise zu diesem Knoten im naechsten Schritt geht
* @param nr
* Knotennummer
*/
private void drawKnot(PaintEvent e, String s, int x, int y, boolean set,
int nr) {
if (set) // wenn bereits passiert in gruen
e.gc.setBackground(highlightColor);
else
e.gc.setBackground(normalColor);
// Kreis und Nummer zeichnen
e.gc.fillOval(x - 32, y - 32, 65, 65);
e.gc.drawString(nr + "", x -22, y -12); //$NON-NLS-1$
if (s.length() > 5)
s = s.substring(0, 5);
for (int i = 0; i < s.length(); i++) { // Text
e.gc.drawString(
Character.toUpperCase(s.charAt(i)) + "", x, y + 12 * (i + 1) - 40); //$NON-NLS-1$
}
}
public void destroyGraph() {
canv.dispose();
}
/**
* Zeichnet eine Ameise beim Punkt p auf das Canvas mit Orientierung
* Richtung Punkt p2
*
* @param e
* PaintEvent
* @param p
* Ort der Ameise
* @param p2
* Orientierung der Ameise
*/
private void drawAnt(PaintEvent e, Point p, Point p2) {
Color col = antColor;
e.gc.setBackground(col);
e.gc.fillOval(p.x, p.y, 15, 15);
double x = p2.x - p.x;
double y = p2.y - p.y;
// Laenge Vektor
double n = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
x /= n;
y /= n;
// Rumpf
e.gc.fillOval((int) (p.x + 15 * x), (int) (p.y + 15 * y), 15, 15);
e.gc.fillOval((int) (p.x - 15 * x), (int) (p.y - 15 * y), 15, 15);
// Fuehler
col = new Color(this.getDisplay(), 150, 150, 150);
e.gc.setForeground(col);
e.gc.drawLine((int) (p.x + 7 + 20 * x + 3 * y),
(int) (p.y + 7 + 20 * y - 3 * x),
(int) (p.x + 7 + 26 * x + 3 * y),
(int) (p.y + 7 + 26 * y - 3 * x));
e.gc.drawLine((int) (p.x + 7 + 20 * x - 3 * y),
(int) (p.y + 7 + 20 * y + 3 * x),
(int) (p.x + 7 + 26 * x - 3 * y),
(int) (p.y + 7 + 26 * y + 3 * x));
// Augen
// col = Display.getCurrent().getSystemColor(SWT.COLOR_WHITE);
e.gc.setBackground(eyeColor);
e.gc.fillOval((int) (p.x + 7 + 17 * x + 3 * y),
(int) (p.y + 7 + 17 * y - 3 * x), 3, 3);
e.gc.fillOval((int) (p.x + 7 + 17 * x - 3 * y),
(int) (p.y + 7 + 17 * y + 3 * x), 3, 3);
// col.dispose();*/
}
/**
* Liefert die Koordinaten, wo die Ameise platziert werden muss, wenn sie
* sich bei Knoten i befindet.
*
* @param i
* Knoten, bei dem sich die Ameise befindet
* @return c Array mit zugehoerigen Koordinaten
*/
private int[] getAntCoord(int i) {
return getCircleCoord(i, ANTRADIUS, new Point(175, 152));
}
private int[] getKnotCoord(int i) {
return getCircleCoord(i, KNOTRADIUS, new Point(183,160));
}
private int[] getCircleCoord(int i, int radius, Point center) {
int size = m.getSize();
int[] out = new int[2];
out[0] = (int) (Math.cos(Math.PI * 2 * (double) i / size + Math.PI /2-Math.PI/ size) * radius + center.x);
out[1] = (int) (Math.sin(Math.PI * 2 * (double) i / size + Math.PI /2-Math.PI/ size) * radius + center.y);
return out;
}
/**
* Setzt die Koordinaten, wo sich die Ameise befindet in Abhaengigkeit von
* dem jeweils aktuellen Knoten.
*
*/
private void setAnt() {
int i = m.getKnot();
int[] a = this.getAntCoord(i);
int oldX = x;
int oldY = y;
x = a[0];
y = a[1];
x2 = -(a[1]-172) + a[0];
y2 = (a[0]-172) + a[1];
int scalarProd = (x-oldX)*(x2-x)+(y-oldY)*(y2-y);
if(scalarProd < 0){
x2 = (a[1]-172) + a[0];
y2 = -(a[0]-172) + a[1];
}
}
public boolean isAnimationRunning() {
return isAnimationRunning;
}
public void addController(AntColEventController reg) {
this.controller = reg;
}
}
| False | 3,079 | 64 | 3,568 | 61 | 3,466 | 65 | 3,568 | 61 | 4,053 | 72 | false | false | false | false | false | true |
165 | 108554_5 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nl.b3p.catalog.stripes;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.validation.Validate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author Geert Plaisier
*/
public class GeoBrabantAction extends DefaultAction {
@Validate(required=false)
private String searchString;
@Validate(required=false)
private String searchType;
@Validate(required=false)
private String uuid;
private List<MapsBean> mapsList;
@DefaultHandler
public Resolution home() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/home.jsp");
}
/* Static pages */
public Resolution overgeobrabant() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/overgeobrabant.jsp");
}
public Resolution diensten() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/diensten.jsp");
}
public Resolution contact() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/contact.jsp");
}
public Resolution kaarten() {
// This JSON should be fetched from a server somewhere
String mapsJson = "[" +
"{ \"class\": \"wat-mag-waar\", \"title\": \"Wat mag waar?\", \"description\": \"Waar ligt dat stukje grond? Zou ik hier mogen bouwen? Vragen die u beantwoord zult zien worden via dit thema. Bekijk welk perceel waar ligt en wat je ermee mag doen.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN01/v1\" }," +
"{ \"class\": \"bekendmakingen\", \"title\": \"Bekendmakingen\", \"description\": \"Via bekendmakingen kunt u zien welke vergunningaanvragen in uw buurt zijn ingediend of verleend zijn. Hierdoor blijft u op de hoogte van de ontwikkelingen bij u in de buurt.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN02/v1\" }," +
"{ \"class\": \"bereikbaarheid\", \"title\": \"Bereikbaarheid\", \"description\": \"Via dit thema kunt u erachter komen hoe de beriekbaarheid van een bepaald gebied is. Zo vindt u bijvoorbeeld waar de dichtstbijzijnde parkeergarage is, waar u oplaadpalen aantreft en actuele informatie over verkeer en wegwerkzaamheden\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN03/v1\" }," +
"{ \"class\": \"veiligheid\", \"title\": \"Veiligheid\", \"description\": \"In dit thema vindt u informatie over de veiligheid in uw buurt. Waar zit de politie en brandweer, maar ook overstromingsrisico, waterkeringen en de veiligheidsregio staan hier.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN04/v1\" }," +
"{ \"class\": \"zorg\", \"title\": \"Zorg\", \"description\": \"Ziekenhuizen, doktersposten en verzorgingshuizen. Alle data met betrekking tot de (medische) zorg staan in dit thema beschreven.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN05/v1\" }," +
"{ \"class\": \"onderwijs-kinderopvang\", \"title\": \"Onderwijs & Kinderopvang\", \"description\": \"In dit thema vindt u de locatie van alle scholen en kinderopvang.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN06/v1\" }," +
"{ \"class\": \"wijkvoorzieningen\", \"title\": \"Wijkvoorzieningen\", \"description\": \"Waar bij mij in de buurt bevinden zich afvalbakken, hondenuitlaatplaatsen en de speeltuin? Dergelijke wijkvoorzieningen vindt u in dit thema, evenals buurthuizen, winkelcentra, etc.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN07/v1\" }," +
"{ \"class\": \"recreatie\", \"title\": \"Recreatie\", \"description\": \"Waar kan ik bij mij in de buurt vrije tijd besteden? In dit thema ziet u waar u kunt sporten en ontspannen. Ook wandel- en fietspaden, natuurgebieden en horecagelegenheden vindt u hier terug.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN08/v1\" }," +
"{ \"class\": \"kunst-cultuur\", \"title\": \"Kunst & Cultuur\", \"description\": \"In dit thema vindt u alle informatie over cultuurhistorie en musea: gemeentelijke- en rijksmonumenten, maar ook archeologische monumenten.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN09/v1\" }," +
"{ \"class\": \"werklocaties\", \"title\": \"Werklocaties\", \"description\": \"In dit thema vindt u alles over bedrijvigheid. Bedrijventerreinen en kantoorlocaties, maar ook winkelcentra bij u in de buurt.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN10/v1\" }" +
"]";
this.mapsList = new ArrayList<>();
try {
JSONArray maps = new JSONArray(mapsJson);
for (int i = 0; i < maps.length(); ++i) {
JSONObject rec = maps.getJSONObject(i);
MapsBean map = new MapsBean();
map.setTitle(rec.getString("title"));
map.setDescription(rec.getString("description"));
map.setUrl(rec.getString("url"));
map.setCssClass(rec.getString("class"));
this.mapsList.add(map);
}
} catch (JSONException ex) {
Logger.getLogger(GeoBrabantAction.class.getName()).log(Level.SEVERE, null, ex);
}
return new ForwardResolution("/WEB-INF/jsp/geobrabant/kaarten.jsp");
}
public Resolution catalogus() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/catalogus.jsp");
}
public Resolution zoeken() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/zoeken.jsp");
}
public String getSearchString() {
return searchString;
}
public void setSearchString(String searchString) {
this.searchString = searchString;
}
public String getSearchType() {
return searchType;
}
public void setSearchType(String searchType) {
this.searchType = searchType;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public List<MapsBean> getMapsList() {
return mapsList;
}
public void setMapsList(List<MapsBean> mapsList) {
this.mapsList = mapsList;
}
public class MapsBean {
private String title;
private String description;
private String url;
private String cssClass;
public MapsBean() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getCssClass() {
return cssClass;
}
public void setCssClass(String cssClass) {
this.cssClass = cssClass;
}
}
}
| B3Partners/B3pCatalog | src/main/java/nl/b3p/catalog/stripes/GeoBrabantAction.java | 2,384 | //acc.geobrabant.nl/viewer/app/RIN03/v1\" }," + | line_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nl.b3p.catalog.stripes;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.validation.Validate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author Geert Plaisier
*/
public class GeoBrabantAction extends DefaultAction {
@Validate(required=false)
private String searchString;
@Validate(required=false)
private String searchType;
@Validate(required=false)
private String uuid;
private List<MapsBean> mapsList;
@DefaultHandler
public Resolution home() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/home.jsp");
}
/* Static pages */
public Resolution overgeobrabant() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/overgeobrabant.jsp");
}
public Resolution diensten() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/diensten.jsp");
}
public Resolution contact() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/contact.jsp");
}
public Resolution kaarten() {
// This JSON should be fetched from a server somewhere
String mapsJson = "[" +
"{ \"class\": \"wat-mag-waar\", \"title\": \"Wat mag waar?\", \"description\": \"Waar ligt dat stukje grond? Zou ik hier mogen bouwen? Vragen die u beantwoord zult zien worden via dit thema. Bekijk welk perceel waar ligt en wat je ermee mag doen.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN01/v1\" }," +
"{ \"class\": \"bekendmakingen\", \"title\": \"Bekendmakingen\", \"description\": \"Via bekendmakingen kunt u zien welke vergunningaanvragen in uw buurt zijn ingediend of verleend zijn. Hierdoor blijft u op de hoogte van de ontwikkelingen bij u in de buurt.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN02/v1\" }," +
"{ \"class\": \"bereikbaarheid\", \"title\": \"Bereikbaarheid\", \"description\": \"Via dit thema kunt u erachter komen hoe de beriekbaarheid van een bepaald gebied is. Zo vindt u bijvoorbeeld waar de dichtstbijzijnde parkeergarage is, waar u oplaadpalen aantreft en actuele informatie over verkeer en wegwerkzaamheden\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN03/v1\" },"<SUF>
"{ \"class\": \"veiligheid\", \"title\": \"Veiligheid\", \"description\": \"In dit thema vindt u informatie over de veiligheid in uw buurt. Waar zit de politie en brandweer, maar ook overstromingsrisico, waterkeringen en de veiligheidsregio staan hier.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN04/v1\" }," +
"{ \"class\": \"zorg\", \"title\": \"Zorg\", \"description\": \"Ziekenhuizen, doktersposten en verzorgingshuizen. Alle data met betrekking tot de (medische) zorg staan in dit thema beschreven.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN05/v1\" }," +
"{ \"class\": \"onderwijs-kinderopvang\", \"title\": \"Onderwijs & Kinderopvang\", \"description\": \"In dit thema vindt u de locatie van alle scholen en kinderopvang.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN06/v1\" }," +
"{ \"class\": \"wijkvoorzieningen\", \"title\": \"Wijkvoorzieningen\", \"description\": \"Waar bij mij in de buurt bevinden zich afvalbakken, hondenuitlaatplaatsen en de speeltuin? Dergelijke wijkvoorzieningen vindt u in dit thema, evenals buurthuizen, winkelcentra, etc.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN07/v1\" }," +
"{ \"class\": \"recreatie\", \"title\": \"Recreatie\", \"description\": \"Waar kan ik bij mij in de buurt vrije tijd besteden? In dit thema ziet u waar u kunt sporten en ontspannen. Ook wandel- en fietspaden, natuurgebieden en horecagelegenheden vindt u hier terug.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN08/v1\" }," +
"{ \"class\": \"kunst-cultuur\", \"title\": \"Kunst & Cultuur\", \"description\": \"In dit thema vindt u alle informatie over cultuurhistorie en musea: gemeentelijke- en rijksmonumenten, maar ook archeologische monumenten.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN09/v1\" }," +
"{ \"class\": \"werklocaties\", \"title\": \"Werklocaties\", \"description\": \"In dit thema vindt u alles over bedrijvigheid. Bedrijventerreinen en kantoorlocaties, maar ook winkelcentra bij u in de buurt.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN10/v1\" }" +
"]";
this.mapsList = new ArrayList<>();
try {
JSONArray maps = new JSONArray(mapsJson);
for (int i = 0; i < maps.length(); ++i) {
JSONObject rec = maps.getJSONObject(i);
MapsBean map = new MapsBean();
map.setTitle(rec.getString("title"));
map.setDescription(rec.getString("description"));
map.setUrl(rec.getString("url"));
map.setCssClass(rec.getString("class"));
this.mapsList.add(map);
}
} catch (JSONException ex) {
Logger.getLogger(GeoBrabantAction.class.getName()).log(Level.SEVERE, null, ex);
}
return new ForwardResolution("/WEB-INF/jsp/geobrabant/kaarten.jsp");
}
public Resolution catalogus() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/catalogus.jsp");
}
public Resolution zoeken() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/zoeken.jsp");
}
public String getSearchString() {
return searchString;
}
public void setSearchString(String searchString) {
this.searchString = searchString;
}
public String getSearchType() {
return searchType;
}
public void setSearchType(String searchType) {
this.searchType = searchType;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public List<MapsBean> getMapsList() {
return mapsList;
}
public void setMapsList(List<MapsBean> mapsList) {
this.mapsList = mapsList;
}
public class MapsBean {
private String title;
private String description;
private String url;
private String cssClass;
public MapsBean() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getCssClass() {
return cssClass;
}
public void setCssClass(String cssClass) {
this.cssClass = cssClass;
}
}
}
| False | 1,851 | 20 | 2,127 | 25 | 2,019 | 24 | 2,127 | 25 | 2,324 | 26 | false | false | false | false | false | true |
4,338 | 38231_5 | package er.chronic.numerizer;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Numerizer {
protected static class DirectNum {
private Pattern _name;
private String _number;
public DirectNum(String name, String number) {
_name = Pattern.compile(name, Pattern.CASE_INSENSITIVE);
_number = number;
}
public Pattern getName() {
return _name;
}
public String getNumber() {
return _number;
}
}
protected static class Prefix {
private String _name;
private Pattern _pattern;
private long _number;
public Prefix(String name, Pattern pattern, long number) {
_name = name;
_pattern = pattern;
_number = number;
}
public String getName() {
return _name;
}
public Pattern getPattern() {
return _pattern;
}
public long getNumber() {
return _number;
}
}
protected static class TenPrefix extends Prefix {
public TenPrefix(String name, long number) {
super(name, Pattern.compile("(?:" + name + ") *<num>(\\d(?=\\D|$))*", Pattern.CASE_INSENSITIVE), number);
}
}
protected static class BigPrefix extends Prefix {
public BigPrefix(String name, long number) {
super(name, Pattern.compile("(?:<num>)?(\\d*) *" + name, Pattern.CASE_INSENSITIVE), number);
}
}
protected static DirectNum[] DIRECT_NUMS;
protected static TenPrefix[] TEN_PREFIXES;
protected static BigPrefix[] BIG_PREFIXES;
static {
List<DirectNum> directNums = new LinkedList<DirectNum>();
directNums.add(new DirectNum("eleven", "11"));
directNums.add(new DirectNum("twelve", "12"));
directNums.add(new DirectNum("thirteen", "13"));
directNums.add(new DirectNum("fourteen", "14"));
directNums.add(new DirectNum("fifteen", "15"));
directNums.add(new DirectNum("sixteen", "16"));
directNums.add(new DirectNum("seventeen", "17"));
directNums.add(new DirectNum("eighteen", "18"));
directNums.add(new DirectNum("nineteen", "19"));
directNums.add(new DirectNum("ninteen", "19")); // Common mis-spelling
directNums.add(new DirectNum("zero", "0"));
directNums.add(new DirectNum("one", "1"));
directNums.add(new DirectNum("two", "2"));
directNums.add(new DirectNum("three", "3"));
directNums.add(new DirectNum("four(\\W|$)", "4$1")); // The weird regex is so that it matches four but not fourty
directNums.add(new DirectNum("five", "5"));
directNums.add(new DirectNum("six(\\W|$)", "6$1"));
directNums.add(new DirectNum("seven(\\W|$)", "7$1"));
directNums.add(new DirectNum("eight(\\W|$)", "8$1"));
directNums.add(new DirectNum("nine(\\W|$)", "9$1"));
directNums.add(new DirectNum("ten", "10"));
directNums.add(new DirectNum("\\ba\\b(.)", "1$1"));
Numerizer.DIRECT_NUMS = directNums.toArray(new DirectNum[directNums.size()]);
List<TenPrefix> tenPrefixes = new LinkedList<TenPrefix>();
tenPrefixes.add(new TenPrefix("twenty", 20));
tenPrefixes.add(new TenPrefix("thirty", 30));
tenPrefixes.add(new TenPrefix("fourty", 40)); // Common mis-spelling
tenPrefixes.add(new TenPrefix("forty", 40));
tenPrefixes.add(new TenPrefix("fifty", 50));
tenPrefixes.add(new TenPrefix("sixty", 60));
tenPrefixes.add(new TenPrefix("seventy", 70));
tenPrefixes.add(new TenPrefix("eighty", 80));
tenPrefixes.add(new TenPrefix("ninety", 90));
tenPrefixes.add(new TenPrefix("ninty", 90)); // Common mis-spelling
Numerizer.TEN_PREFIXES = tenPrefixes.toArray(new TenPrefix[tenPrefixes.size()]);
List<BigPrefix> bigPrefixes = new LinkedList<BigPrefix>();
bigPrefixes.add(new BigPrefix("hundred", 100L));
bigPrefixes.add(new BigPrefix("thousand", 1000L));
bigPrefixes.add(new BigPrefix("million", 1000000L));
bigPrefixes.add(new BigPrefix("billion", 1000000000L));
bigPrefixes.add(new BigPrefix("trillion", 1000000000000L));
Numerizer.BIG_PREFIXES = bigPrefixes.toArray(new BigPrefix[bigPrefixes.size()]);
}
private static final Pattern DEHYPHENATOR = Pattern.compile(" +|(\\D)-(\\D)");
private static final Pattern DEHALFER = Pattern.compile("a half", Pattern.CASE_INSENSITIVE);
private static final Pattern DEHAALFER = Pattern.compile("(\\d+)(?: | and |-)*haAlf", Pattern.CASE_INSENSITIVE);
private static final Pattern ANDITION_PATTERN = Pattern.compile("<num>(\\d+)( | and )<num>(\\d+)(?=\\W|$)", Pattern.CASE_INSENSITIVE);
// FIXES
//string.gsub!(/ +|([^\d])-([^d])/, '\1 \2') # will mutilate hyphenated-words but shouldn't matter for date extraction
//string.gsub!(/ +|([^\d])-([^\\d])/, '\1 \2') # will mutilate hyphenated-words but shouldn't matter for date extraction
public static String numerize(String str) {
String numerizedStr = str;
// preprocess
numerizedStr = Numerizer.DEHYPHENATOR.matcher(numerizedStr).replaceAll("$1 $2"); // will mutilate hyphenated-words but shouldn't matter for date extraction
numerizedStr = Numerizer.DEHALFER.matcher(numerizedStr).replaceAll("haAlf"); // take the 'a' out so it doesn't turn into a 1, save the half for the end
// easy/direct replacements
for (DirectNum dn : Numerizer.DIRECT_NUMS) {
numerizedStr = dn.getName().matcher(numerizedStr).replaceAll("<num>" + dn.getNumber());
}
// ten, twenty, etc.
for (Prefix tp : Numerizer.TEN_PREFIXES) {
Matcher matcher = tp.getPattern().matcher(numerizedStr);
if (matcher.find()) {
StringBuffer matcherBuffer = new StringBuffer();
do {
if (matcher.group(1) == null) {
matcher.appendReplacement(matcherBuffer, "<num>" + String.valueOf(tp.getNumber()));
}
else {
matcher.appendReplacement(matcherBuffer, "<num>" + String.valueOf(tp.getNumber() + Long.parseLong(matcher.group(1).trim())));
}
} while (matcher.find());
matcher.appendTail(matcherBuffer);
numerizedStr = matcherBuffer.toString();
}
}
for (Prefix tp : Numerizer.TEN_PREFIXES) {
numerizedStr = Pattern.compile(tp.getName(), Pattern.CASE_INSENSITIVE).matcher(numerizedStr).replaceAll("<num>" + tp.getNumber());
}
// hundreds, thousands, millions, etc.
for (Prefix bp : Numerizer.BIG_PREFIXES) {
Matcher matcher = bp.getPattern().matcher(numerizedStr);
if (matcher.find()) {
StringBuffer matcherBuffer = new StringBuffer();
do {
if (matcher.group(1) == null) {
matcher.appendReplacement(matcherBuffer, "<num>" + String.valueOf(bp.getNumber()));
}
else {
matcher.appendReplacement(matcherBuffer, "<num>" + String.valueOf(bp.getNumber() * Long.parseLong(matcher.group(1).trim())));
}
} while (matcher.find());
matcher.appendTail(matcherBuffer);
numerizedStr = matcherBuffer.toString();
}
numerizedStr = Numerizer.andition(numerizedStr);
// combine_numbers(string) // Should to be more efficient way to do this
}
// fractional addition
// I'm not combining this with the previous block as using float addition complicates the strings
// (with extraneous .0's and such )
Matcher matcher = Numerizer.DEHAALFER.matcher(numerizedStr);
if (matcher.find()) {
StringBuffer matcherBuffer = new StringBuffer();
do {
matcher.appendReplacement(matcherBuffer, String.valueOf(Float.parseFloat(matcher.group(1).trim()) + 0.5f));
} while (matcher.find());
matcher.appendTail(matcherBuffer);
numerizedStr = matcherBuffer.toString();
}
//string.gsub!(/(\d+)(?: | and |-)*haAlf/i) { ($1.to_f + 0.5).to_s }
numerizedStr = numerizedStr.replaceAll("<num>", "");
return numerizedStr;
}
public static String andition(String str) {
StringBuilder anditionStr = new StringBuilder(str);
Matcher matcher = Numerizer.ANDITION_PATTERN.matcher(anditionStr);
while (matcher.find()) {
if (matcher.group(2).equalsIgnoreCase(" and ") || (matcher.group(1).length() > matcher.group(3).length() && matcher.group(1).matches("^.+0+$"))) {
anditionStr.replace(matcher.start(), matcher.end(), "<num>" + String.valueOf(Integer.parseInt(matcher.group(1).trim()) + Integer.parseInt(matcher.group(3).trim())));
matcher = Numerizer.ANDITION_PATTERN.matcher(anditionStr);
}
}
return anditionStr.toString();
}
}
| smarthealth/wonder | Frameworks/Misc/ERChronic/Sources/er/chronic/numerizer/Numerizer.java | 2,842 | // ten, twenty, etc. | line_comment | nl | package er.chronic.numerizer;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Numerizer {
protected static class DirectNum {
private Pattern _name;
private String _number;
public DirectNum(String name, String number) {
_name = Pattern.compile(name, Pattern.CASE_INSENSITIVE);
_number = number;
}
public Pattern getName() {
return _name;
}
public String getNumber() {
return _number;
}
}
protected static class Prefix {
private String _name;
private Pattern _pattern;
private long _number;
public Prefix(String name, Pattern pattern, long number) {
_name = name;
_pattern = pattern;
_number = number;
}
public String getName() {
return _name;
}
public Pattern getPattern() {
return _pattern;
}
public long getNumber() {
return _number;
}
}
protected static class TenPrefix extends Prefix {
public TenPrefix(String name, long number) {
super(name, Pattern.compile("(?:" + name + ") *<num>(\\d(?=\\D|$))*", Pattern.CASE_INSENSITIVE), number);
}
}
protected static class BigPrefix extends Prefix {
public BigPrefix(String name, long number) {
super(name, Pattern.compile("(?:<num>)?(\\d*) *" + name, Pattern.CASE_INSENSITIVE), number);
}
}
protected static DirectNum[] DIRECT_NUMS;
protected static TenPrefix[] TEN_PREFIXES;
protected static BigPrefix[] BIG_PREFIXES;
static {
List<DirectNum> directNums = new LinkedList<DirectNum>();
directNums.add(new DirectNum("eleven", "11"));
directNums.add(new DirectNum("twelve", "12"));
directNums.add(new DirectNum("thirteen", "13"));
directNums.add(new DirectNum("fourteen", "14"));
directNums.add(new DirectNum("fifteen", "15"));
directNums.add(new DirectNum("sixteen", "16"));
directNums.add(new DirectNum("seventeen", "17"));
directNums.add(new DirectNum("eighteen", "18"));
directNums.add(new DirectNum("nineteen", "19"));
directNums.add(new DirectNum("ninteen", "19")); // Common mis-spelling
directNums.add(new DirectNum("zero", "0"));
directNums.add(new DirectNum("one", "1"));
directNums.add(new DirectNum("two", "2"));
directNums.add(new DirectNum("three", "3"));
directNums.add(new DirectNum("four(\\W|$)", "4$1")); // The weird regex is so that it matches four but not fourty
directNums.add(new DirectNum("five", "5"));
directNums.add(new DirectNum("six(\\W|$)", "6$1"));
directNums.add(new DirectNum("seven(\\W|$)", "7$1"));
directNums.add(new DirectNum("eight(\\W|$)", "8$1"));
directNums.add(new DirectNum("nine(\\W|$)", "9$1"));
directNums.add(new DirectNum("ten", "10"));
directNums.add(new DirectNum("\\ba\\b(.)", "1$1"));
Numerizer.DIRECT_NUMS = directNums.toArray(new DirectNum[directNums.size()]);
List<TenPrefix> tenPrefixes = new LinkedList<TenPrefix>();
tenPrefixes.add(new TenPrefix("twenty", 20));
tenPrefixes.add(new TenPrefix("thirty", 30));
tenPrefixes.add(new TenPrefix("fourty", 40)); // Common mis-spelling
tenPrefixes.add(new TenPrefix("forty", 40));
tenPrefixes.add(new TenPrefix("fifty", 50));
tenPrefixes.add(new TenPrefix("sixty", 60));
tenPrefixes.add(new TenPrefix("seventy", 70));
tenPrefixes.add(new TenPrefix("eighty", 80));
tenPrefixes.add(new TenPrefix("ninety", 90));
tenPrefixes.add(new TenPrefix("ninty", 90)); // Common mis-spelling
Numerizer.TEN_PREFIXES = tenPrefixes.toArray(new TenPrefix[tenPrefixes.size()]);
List<BigPrefix> bigPrefixes = new LinkedList<BigPrefix>();
bigPrefixes.add(new BigPrefix("hundred", 100L));
bigPrefixes.add(new BigPrefix("thousand", 1000L));
bigPrefixes.add(new BigPrefix("million", 1000000L));
bigPrefixes.add(new BigPrefix("billion", 1000000000L));
bigPrefixes.add(new BigPrefix("trillion", 1000000000000L));
Numerizer.BIG_PREFIXES = bigPrefixes.toArray(new BigPrefix[bigPrefixes.size()]);
}
private static final Pattern DEHYPHENATOR = Pattern.compile(" +|(\\D)-(\\D)");
private static final Pattern DEHALFER = Pattern.compile("a half", Pattern.CASE_INSENSITIVE);
private static final Pattern DEHAALFER = Pattern.compile("(\\d+)(?: | and |-)*haAlf", Pattern.CASE_INSENSITIVE);
private static final Pattern ANDITION_PATTERN = Pattern.compile("<num>(\\d+)( | and )<num>(\\d+)(?=\\W|$)", Pattern.CASE_INSENSITIVE);
// FIXES
//string.gsub!(/ +|([^\d])-([^d])/, '\1 \2') # will mutilate hyphenated-words but shouldn't matter for date extraction
//string.gsub!(/ +|([^\d])-([^\\d])/, '\1 \2') # will mutilate hyphenated-words but shouldn't matter for date extraction
public static String numerize(String str) {
String numerizedStr = str;
// preprocess
numerizedStr = Numerizer.DEHYPHENATOR.matcher(numerizedStr).replaceAll("$1 $2"); // will mutilate hyphenated-words but shouldn't matter for date extraction
numerizedStr = Numerizer.DEHALFER.matcher(numerizedStr).replaceAll("haAlf"); // take the 'a' out so it doesn't turn into a 1, save the half for the end
// easy/direct replacements
for (DirectNum dn : Numerizer.DIRECT_NUMS) {
numerizedStr = dn.getName().matcher(numerizedStr).replaceAll("<num>" + dn.getNumber());
}
// ten, twenty,<SUF>
for (Prefix tp : Numerizer.TEN_PREFIXES) {
Matcher matcher = tp.getPattern().matcher(numerizedStr);
if (matcher.find()) {
StringBuffer matcherBuffer = new StringBuffer();
do {
if (matcher.group(1) == null) {
matcher.appendReplacement(matcherBuffer, "<num>" + String.valueOf(tp.getNumber()));
}
else {
matcher.appendReplacement(matcherBuffer, "<num>" + String.valueOf(tp.getNumber() + Long.parseLong(matcher.group(1).trim())));
}
} while (matcher.find());
matcher.appendTail(matcherBuffer);
numerizedStr = matcherBuffer.toString();
}
}
for (Prefix tp : Numerizer.TEN_PREFIXES) {
numerizedStr = Pattern.compile(tp.getName(), Pattern.CASE_INSENSITIVE).matcher(numerizedStr).replaceAll("<num>" + tp.getNumber());
}
// hundreds, thousands, millions, etc.
for (Prefix bp : Numerizer.BIG_PREFIXES) {
Matcher matcher = bp.getPattern().matcher(numerizedStr);
if (matcher.find()) {
StringBuffer matcherBuffer = new StringBuffer();
do {
if (matcher.group(1) == null) {
matcher.appendReplacement(matcherBuffer, "<num>" + String.valueOf(bp.getNumber()));
}
else {
matcher.appendReplacement(matcherBuffer, "<num>" + String.valueOf(bp.getNumber() * Long.parseLong(matcher.group(1).trim())));
}
} while (matcher.find());
matcher.appendTail(matcherBuffer);
numerizedStr = matcherBuffer.toString();
}
numerizedStr = Numerizer.andition(numerizedStr);
// combine_numbers(string) // Should to be more efficient way to do this
}
// fractional addition
// I'm not combining this with the previous block as using float addition complicates the strings
// (with extraneous .0's and such )
Matcher matcher = Numerizer.DEHAALFER.matcher(numerizedStr);
if (matcher.find()) {
StringBuffer matcherBuffer = new StringBuffer();
do {
matcher.appendReplacement(matcherBuffer, String.valueOf(Float.parseFloat(matcher.group(1).trim()) + 0.5f));
} while (matcher.find());
matcher.appendTail(matcherBuffer);
numerizedStr = matcherBuffer.toString();
}
//string.gsub!(/(\d+)(?: | and |-)*haAlf/i) { ($1.to_f + 0.5).to_s }
numerizedStr = numerizedStr.replaceAll("<num>", "");
return numerizedStr;
}
public static String andition(String str) {
StringBuilder anditionStr = new StringBuilder(str);
Matcher matcher = Numerizer.ANDITION_PATTERN.matcher(anditionStr);
while (matcher.find()) {
if (matcher.group(2).equalsIgnoreCase(" and ") || (matcher.group(1).length() > matcher.group(3).length() && matcher.group(1).matches("^.+0+$"))) {
anditionStr.replace(matcher.start(), matcher.end(), "<num>" + String.valueOf(Integer.parseInt(matcher.group(1).trim()) + Integer.parseInt(matcher.group(3).trim())));
matcher = Numerizer.ANDITION_PATTERN.matcher(anditionStr);
}
}
return anditionStr.toString();
}
}
| False | 2,220 | 7 | 2,408 | 8 | 2,574 | 7 | 2,408 | 8 | 2,886 | 7 | false | false | false | false | false | true |
1,355 | 70583_7 |
import greenfoot.*;
import java.util.List;
/**
*
* @author R. Springer
*/
public class TileEngine {
public static int TILE_WIDTH;
public static int TILE_HEIGHT;
public static int SCREEN_HEIGHT;
public static int SCREEN_WIDTH;
public static int MAP_WIDTH;
public static int MAP_HEIGHT;
private World world;
private int[][] map;
private Tile[][] generateMap;
private TileFactory tileFactory;
/**
* Constuctor of the TileEngine
*
* @param world A World class or a extend of it.
* @param tileWidth The width of the tile used in the TileFactory and
* calculations
* @param tileHeight The heigth of the tile used in the TileFactory and
* calculations
*/
public TileEngine(World world, int tileWidth, int tileHeight) {
this.world = world;
TILE_WIDTH = tileWidth;
TILE_HEIGHT = tileHeight;
SCREEN_WIDTH = world.getWidth();
SCREEN_HEIGHT = world.getHeight();
this.tileFactory = new TileFactory();
}
/**
* Constuctor of the TileEngine
*
* @param world A World class or a extend of it.
* @param tileWidth The width of the tile used in the TileFactory and
* calculations
* @param tileHeight The heigth of the tile used in the TileFactory and
* calculations
* @param map A tilemap with numbers
*/
public TileEngine(World world, int tileWidth, int tileHeight, int[][] map) {
this(world, tileWidth, tileHeight);
this.setMap(map);
}
/**
* The setMap method used to set a map. This method also clears the previous
* map and generates a new one.
*
* @param map
*/
public void setMap(int[][] map) {
this.clearTilesWorld();
this.map = map;
MAP_HEIGHT = this.map.length;
MAP_WIDTH = this.map[0].length;
this.generateMap = new Tile[MAP_HEIGHT][MAP_WIDTH];
this.generateWorld();
}
/**
* The setTileFactory sets a tilefactory. You can use this if you want to
* create you own tilefacory and use it in the class.
*
* @param tf A Tilefactory or extend of it.
*/
public void setTileFactory(TileFactory tf) {
this.tileFactory = tf;
}
/**
* Removes al the tiles from the world.
*/
public void clearTilesWorld() {
List<Tile> removeObjects = this.world.getObjects(Tile.class);
this.world.removeObjects(removeObjects);
this.map = null;
this.generateMap = null;
MAP_HEIGHT = 0;
MAP_WIDTH = 0;
}
/**
* Creates the tile world based on the TileFactory and the map icons.
*/
public void generateWorld() {
int mapID = 0;
for (int y = 0; y < MAP_HEIGHT; y++) {
for (int x = 0; x < MAP_WIDTH; x++) {
// Nummer ophalen in de int array
mapID++;
int mapIcon = this.map[y][x];
//if (mapIcon == -1) {
// continue;
//}
// Als de mapIcon -1 is dan wordt de code hieronder overgeslagen
// Dus er wordt geen tile aangemaakt. -1 is dus geen tile;
Tile createdTile = this.tileFactory.createTile(mapIcon);
createdTile.setMapID(mapID);
createdTile.setMapIcon(mapIcon);
addTileAt(createdTile, x, y);
}
}
}
/**
* Adds a tile on the colom and row. Calculation is based on TILE_WIDTH and
* TILE_HEIGHT
*
* @param tile The Tile
* @param colom The colom where the tile exist in the map
* @param row The row where the tile exist in the map
*/
public void addTileAt(Tile tile, int colom, int row) {
// De X en Y positie zitten het midden van de Actor.
// De tilemap genereerd een wereld gebaseerd op dat de X en Y
// positie links boven in zitten. Vandaar de we de helft van de
// breedte en hoogte optellen zodat de X en Y links boven zit voor
// het toevoegen van het object.
this.world.addObject(tile, (colom * TILE_WIDTH) + TILE_WIDTH / 2, (row * TILE_HEIGHT) + TILE_HEIGHT / 2);
tile.x = (colom * TILE_WIDTH) + TILE_WIDTH / 2;
tile.y = (row * TILE_HEIGHT) + TILE_HEIGHT / 2;
// Toevoegen aan onze lokale array. Makkelijk om de tile op te halen
// op basis van een x en y positie van de map
this.generateMap[row][colom] = tile;
tile.setColom(colom);
tile.setRow(row);
}
/**
* Retrieves a tile at the location based on colom and row in the map
*
* @param colom
* @param row
* @return The tile at the location colom and row. Returns null if it cannot
* find a tile.
*/
public Tile getTileAt(int colom, int row) {
if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) {
return null;
}
return this.generateMap[row][colom];
}
/**
* Retrieves a tile based on a x and y position in the world
*
* @param x X-position in the world
* @param y Y-position in the world
* @return The tile at the location colom and row. Returns null if it cannot
* find a tile.
*/
public Tile getTileAtXY(int x, int y) {
int col = getColumn(x);
int row = getRow(y);
Tile tile = getTileAt(col, row);
return tile;
}
/**
* Removes tile at the given colom and row
*
* @param colom
* @param row
* @return true if the tile has successfully been removed
*/
public boolean removeTileAt(int colom, int row) {
if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) {
return false;
}
Tile tile = this.generateMap[row][colom];
if (tile != null) {
this.world.removeObject(tile);
this.generateMap[row][colom] = null;
return true;
}
return false;
}
/**
* Removes tile at the given x and y position
*
* @param x X-position in the world
* @param y Y-position in the world
* @return true if the tile has successfully been removed
*/
public boolean removeTileAtXY(int x, int y) {
int col = getColumn(x);
int row = getRow(y);
return removeTileAt(col, row);
}
/**
* Removes the tile based on a tile
*
* @param tile Tile from the tilemap
* @return true if the tile has successfully been removed
*/
public boolean removeTile(Tile tile) {
int colom = tile.getColom();
int row = tile.getRow();
if (colom != -1 && row != -1) {
return this.removeTileAt(colom, row);
}
return false;
}
/**
* This methode checks if a tile on a x and y position in the world is solid
* or not.
*
* @param x X-position in the world
* @param y Y-position in the world
* @return Tile at location is solid
*/
public boolean checkTileSolid(int x, int y) {
Tile tile = getTileAtXY(x, y);
if (tile != null && tile.isSolid) {
return true;
}
return false;
}
/**
* This methode returns a colom based on a x position.
*
* @param x
* @return the colom
*/
public int getColumn(int x) {
return (int) Math.floor(x / TILE_WIDTH);
}
/**
* This methode returns a row based on a y position.
*
* @param y
* @return the row
*/
public int getRow(int y) {
return (int) Math.floor(y / TILE_HEIGHT);
}
/**
* This methode returns a x position based on the colom
*
* @param col
* @return The x position
*/
public int getX(int col) {
return col * TILE_WIDTH;
}
/**
* This methode returns a y position based on the row
*
* @param row
* @return The y position
*/
public int getY(int row) {
return row * TILE_HEIGHT;
}
}
| ROCMondriaanTIN/project-greenfoot-game-20Jorden01 | TileEngine.java | 2,484 | // Nummer ophalen in de int array | line_comment | nl |
import greenfoot.*;
import java.util.List;
/**
*
* @author R. Springer
*/
public class TileEngine {
public static int TILE_WIDTH;
public static int TILE_HEIGHT;
public static int SCREEN_HEIGHT;
public static int SCREEN_WIDTH;
public static int MAP_WIDTH;
public static int MAP_HEIGHT;
private World world;
private int[][] map;
private Tile[][] generateMap;
private TileFactory tileFactory;
/**
* Constuctor of the TileEngine
*
* @param world A World class or a extend of it.
* @param tileWidth The width of the tile used in the TileFactory and
* calculations
* @param tileHeight The heigth of the tile used in the TileFactory and
* calculations
*/
public TileEngine(World world, int tileWidth, int tileHeight) {
this.world = world;
TILE_WIDTH = tileWidth;
TILE_HEIGHT = tileHeight;
SCREEN_WIDTH = world.getWidth();
SCREEN_HEIGHT = world.getHeight();
this.tileFactory = new TileFactory();
}
/**
* Constuctor of the TileEngine
*
* @param world A World class or a extend of it.
* @param tileWidth The width of the tile used in the TileFactory and
* calculations
* @param tileHeight The heigth of the tile used in the TileFactory and
* calculations
* @param map A tilemap with numbers
*/
public TileEngine(World world, int tileWidth, int tileHeight, int[][] map) {
this(world, tileWidth, tileHeight);
this.setMap(map);
}
/**
* The setMap method used to set a map. This method also clears the previous
* map and generates a new one.
*
* @param map
*/
public void setMap(int[][] map) {
this.clearTilesWorld();
this.map = map;
MAP_HEIGHT = this.map.length;
MAP_WIDTH = this.map[0].length;
this.generateMap = new Tile[MAP_HEIGHT][MAP_WIDTH];
this.generateWorld();
}
/**
* The setTileFactory sets a tilefactory. You can use this if you want to
* create you own tilefacory and use it in the class.
*
* @param tf A Tilefactory or extend of it.
*/
public void setTileFactory(TileFactory tf) {
this.tileFactory = tf;
}
/**
* Removes al the tiles from the world.
*/
public void clearTilesWorld() {
List<Tile> removeObjects = this.world.getObjects(Tile.class);
this.world.removeObjects(removeObjects);
this.map = null;
this.generateMap = null;
MAP_HEIGHT = 0;
MAP_WIDTH = 0;
}
/**
* Creates the tile world based on the TileFactory and the map icons.
*/
public void generateWorld() {
int mapID = 0;
for (int y = 0; y < MAP_HEIGHT; y++) {
for (int x = 0; x < MAP_WIDTH; x++) {
// Nummer ophalen<SUF>
mapID++;
int mapIcon = this.map[y][x];
//if (mapIcon == -1) {
// continue;
//}
// Als de mapIcon -1 is dan wordt de code hieronder overgeslagen
// Dus er wordt geen tile aangemaakt. -1 is dus geen tile;
Tile createdTile = this.tileFactory.createTile(mapIcon);
createdTile.setMapID(mapID);
createdTile.setMapIcon(mapIcon);
addTileAt(createdTile, x, y);
}
}
}
/**
* Adds a tile on the colom and row. Calculation is based on TILE_WIDTH and
* TILE_HEIGHT
*
* @param tile The Tile
* @param colom The colom where the tile exist in the map
* @param row The row where the tile exist in the map
*/
public void addTileAt(Tile tile, int colom, int row) {
// De X en Y positie zitten het midden van de Actor.
// De tilemap genereerd een wereld gebaseerd op dat de X en Y
// positie links boven in zitten. Vandaar de we de helft van de
// breedte en hoogte optellen zodat de X en Y links boven zit voor
// het toevoegen van het object.
this.world.addObject(tile, (colom * TILE_WIDTH) + TILE_WIDTH / 2, (row * TILE_HEIGHT) + TILE_HEIGHT / 2);
tile.x = (colom * TILE_WIDTH) + TILE_WIDTH / 2;
tile.y = (row * TILE_HEIGHT) + TILE_HEIGHT / 2;
// Toevoegen aan onze lokale array. Makkelijk om de tile op te halen
// op basis van een x en y positie van de map
this.generateMap[row][colom] = tile;
tile.setColom(colom);
tile.setRow(row);
}
/**
* Retrieves a tile at the location based on colom and row in the map
*
* @param colom
* @param row
* @return The tile at the location colom and row. Returns null if it cannot
* find a tile.
*/
public Tile getTileAt(int colom, int row) {
if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) {
return null;
}
return this.generateMap[row][colom];
}
/**
* Retrieves a tile based on a x and y position in the world
*
* @param x X-position in the world
* @param y Y-position in the world
* @return The tile at the location colom and row. Returns null if it cannot
* find a tile.
*/
public Tile getTileAtXY(int x, int y) {
int col = getColumn(x);
int row = getRow(y);
Tile tile = getTileAt(col, row);
return tile;
}
/**
* Removes tile at the given colom and row
*
* @param colom
* @param row
* @return true if the tile has successfully been removed
*/
public boolean removeTileAt(int colom, int row) {
if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) {
return false;
}
Tile tile = this.generateMap[row][colom];
if (tile != null) {
this.world.removeObject(tile);
this.generateMap[row][colom] = null;
return true;
}
return false;
}
/**
* Removes tile at the given x and y position
*
* @param x X-position in the world
* @param y Y-position in the world
* @return true if the tile has successfully been removed
*/
public boolean removeTileAtXY(int x, int y) {
int col = getColumn(x);
int row = getRow(y);
return removeTileAt(col, row);
}
/**
* Removes the tile based on a tile
*
* @param tile Tile from the tilemap
* @return true if the tile has successfully been removed
*/
public boolean removeTile(Tile tile) {
int colom = tile.getColom();
int row = tile.getRow();
if (colom != -1 && row != -1) {
return this.removeTileAt(colom, row);
}
return false;
}
/**
* This methode checks if a tile on a x and y position in the world is solid
* or not.
*
* @param x X-position in the world
* @param y Y-position in the world
* @return Tile at location is solid
*/
public boolean checkTileSolid(int x, int y) {
Tile tile = getTileAtXY(x, y);
if (tile != null && tile.isSolid) {
return true;
}
return false;
}
/**
* This methode returns a colom based on a x position.
*
* @param x
* @return the colom
*/
public int getColumn(int x) {
return (int) Math.floor(x / TILE_WIDTH);
}
/**
* This methode returns a row based on a y position.
*
* @param y
* @return the row
*/
public int getRow(int y) {
return (int) Math.floor(y / TILE_HEIGHT);
}
/**
* This methode returns a x position based on the colom
*
* @param col
* @return The x position
*/
public int getX(int col) {
return col * TILE_WIDTH;
}
/**
* This methode returns a y position based on the row
*
* @param row
* @return The y position
*/
public int getY(int row) {
return row * TILE_HEIGHT;
}
}
| True | 2,015 | 10 | 2,123 | 11 | 2,313 | 8 | 2,141 | 11 | 2,542 | 10 | false | false | false | false | false | true |
796 | 127151_14 | // Copyright (c) 2014 by B.W. van Schooten, info@borisvanschooten.nl
package net.tmtg.glesjs;
import android.os.Bundle;
import android.app.Activity;
import android.app.Application;
import android.hardware.*;
import android.view.*;
import android.graphics.*;
import android.graphics.drawable.Drawable;
import android.content.Intent;
import android.net.Uri;
import android.content.Context;
import android.opengl.*;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.util.Log;
public class MainActivity extends Activity {
static boolean surface_already_created=false;
MyGLSurfaceView mView=null;
MyRenderer mRen=null;
@Override protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
GlesJSUtils.init(this);
mView = new MyGLSurfaceView(getApplication());
// Try to hang on to GL context
mView.setPreserveEGLContextOnPause(true);
setContentView(mView);
}
@Override protected void onPause() {
super.onPause();
//mView.setVisibility(View.GONE);
mView.onPause();
GlesJSUtils.pauseAudio();
}
@Override protected void onResume() {
super.onResume();
mView.onResume();
GlesJSUtils.resumeAudio();
}
/*@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus && mView.getVisibility() == View.GONE) {
mView.setVisibility(View.VISIBLE);
}
}*/
@Override public boolean onKeyDown(int keyCode, KeyEvent event) {
return GameController.onKeyDown(keyCode,event);
}
@Override public boolean onKeyUp(int keyCode, KeyEvent event) {
return GameController.onKeyUp(keyCode,event);
}
@Override public boolean onGenericMotionEvent(MotionEvent event) {
return GameController.onGenericMotionEvent(event);
}
class MyGLSurfaceView extends GLSurfaceView {
public MyGLSurfaceView(Context context){
super(context);
setEGLContextClientVersion(2);
// Set the Renderer for drawing on the GLSurfaceView
mRen = new MyRenderer();
setRenderer(mRen);
}
@Override
public boolean onTouchEvent(MotionEvent me) {
// queue event, and handle it from the renderer thread later
// to avoid concurrency handling
if (mRen!=null) mRen.queueTouchEvent(me);
return true;
}
}
class MyRenderer implements GLSurfaceView.Renderer {
static final int MAXQUEUELEN = 6;
Object queuelock = new Object();
MotionEvent [] motionqueue = new MotionEvent [MAXQUEUELEN];
int motionqueue_len = 0;
public void queueTouchEvent(MotionEvent ev) {
synchronized (queuelock) {
if (motionqueue_len >= MAXQUEUELEN) return;
motionqueue[motionqueue_len++] = MotionEvent.obtain(ev);
}
}
static final int MAXTOUCHES=8;
int [] touchids = new int[MAXTOUCHES];
double [] touchx = new double[MAXTOUCHES];
double [] touchy = new double[MAXTOUCHES];
int touchlen = 0;
public void handleTouchEvent(MotionEvent me) {
// XXX We should mask out the pointer id info in some of the
// action codes. Since 2.2, we should use getActionMasked for
// this.
// use MotionEventCompat to do this?
int action = me.getActionMasked();
int ptridx = me.getActionIndex();
// Default coord is the current coordinates of an arbitrary active
// pointer.
double x = me.getX(ptridx);
double y = me.getY(ptridx);
// on a multitouch, touches after the first touch are also
// considered mouse-down flanks.
boolean press = action == MotionEvent.ACTION_DOWN
|| action == MotionEvent.ACTION_POINTER_DOWN;
// boolean down = press || action == MotionEvent.ACTION_MOVE;
// Alcatel pop:
// down event: 0
// move event: 2
// up event: 9.
// ACTION_UP=1, ACTION_POINTER_UP=6
//boolean release = (action & ( MotionEvent.ACTION_UP)) != 0;
// Normal:
boolean release = action == MotionEvent.ACTION_UP
|| action == MotionEvent.ACTION_POINTER_UP;
int ptrid=0;
try {
ptrid = me.getPointerId(ptridx);
} catch (IllegalArgumentException e) {
// getPointerId sometimes throws pointer index out of range
// -> ignore
System.err.println("Failed getting pointer. Ignoring.");
e.printStackTrace();
return;
}
// pass multitouch coordinates before touch event
int pointerCount = me.getPointerCount();
// signal start multitouch info
GlesJSLib.onMultitouchCoordinates(-1,0,0);
for (int p = 0; p < pointerCount; p++) {
try {
int pid = me.getPointerId(p);
GlesJSLib.onMultitouchCoordinates(pid,me.getX(p),me.getY(p));
} catch (IllegalArgumentException e) {
// getPointerId sometimes throws pointer index out of range
// -> ignore
System.err.println("Failed getting pointer. Ignoring.");
e.printStackTrace();
}
}
// signal end coordinate info, start button info
//GlesJSLib.onMultitouchCoordinates(-2,0,0);
// single touch / press-release info
// !press && !release means move
GlesJSLib.onTouchEvent(ptrid,x,y,press,release);
// signal end touch info
GlesJSLib.onMultitouchCoordinates(-3,0,0);
}
public void onDrawFrame(GL10 gl) {
GameController.startOfFrame();
// handle events in the render thread
synchronized (queuelock) {
for (int i=0; i<motionqueue_len; i++) {
if (motionqueue[i]!=null) {
handleTouchEvent(motionqueue[i]);
motionqueue[i].recycle();
motionqueue[i] = null;
}
}
motionqueue_len = 0;
}
for (int i=0; i<GameController.NR_PLAYERS; i++) {
GameController con = GameController.getControllerByPlayer(i);
if (con.isConnected()) {
//System.out.println("##################active@@@@@"+i);
boolean [] buttons = con.getButtons();
float [] axes = con.getAxes();
GlesJSLib.onControllerEvent(i,true,buttons,axes);
} else {
GlesJSLib.onControllerEvent(i,false,null,null);
}
/* FOR TESTING:
} else if (i==0) {
boolean [] buttons = new boolean[]
{true,false,true,false,true,false,true};
float [] axes = new float[]
{9,8,7,6,5};
GlesJSLib.onControllerEvent(i,true,buttons,axes);
}
*/
}
GlesJSLib.onDrawFrame();
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
GameController.init(MainActivity.this);
GlesJSLib.onSurfaceChanged(width, height);
surface_already_created=true;
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
if (surface_already_created) {
// gl context was lost -> we can't handle that yet
// -> commit suicide
// TODO generate contextlost event in JS
System.err.println("GL context lost. Cannot restore. Exiting.");
System.exit(0);
}
// Do nothing.
}
}
}
| JakeCoxon/glesjs | src/net/tmtg/glesjs/MainActivity.java | 2,284 | // move event: 2 | line_comment | nl | // Copyright (c) 2014 by B.W. van Schooten, info@borisvanschooten.nl
package net.tmtg.glesjs;
import android.os.Bundle;
import android.app.Activity;
import android.app.Application;
import android.hardware.*;
import android.view.*;
import android.graphics.*;
import android.graphics.drawable.Drawable;
import android.content.Intent;
import android.net.Uri;
import android.content.Context;
import android.opengl.*;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.util.Log;
public class MainActivity extends Activity {
static boolean surface_already_created=false;
MyGLSurfaceView mView=null;
MyRenderer mRen=null;
@Override protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
GlesJSUtils.init(this);
mView = new MyGLSurfaceView(getApplication());
// Try to hang on to GL context
mView.setPreserveEGLContextOnPause(true);
setContentView(mView);
}
@Override protected void onPause() {
super.onPause();
//mView.setVisibility(View.GONE);
mView.onPause();
GlesJSUtils.pauseAudio();
}
@Override protected void onResume() {
super.onResume();
mView.onResume();
GlesJSUtils.resumeAudio();
}
/*@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus && mView.getVisibility() == View.GONE) {
mView.setVisibility(View.VISIBLE);
}
}*/
@Override public boolean onKeyDown(int keyCode, KeyEvent event) {
return GameController.onKeyDown(keyCode,event);
}
@Override public boolean onKeyUp(int keyCode, KeyEvent event) {
return GameController.onKeyUp(keyCode,event);
}
@Override public boolean onGenericMotionEvent(MotionEvent event) {
return GameController.onGenericMotionEvent(event);
}
class MyGLSurfaceView extends GLSurfaceView {
public MyGLSurfaceView(Context context){
super(context);
setEGLContextClientVersion(2);
// Set the Renderer for drawing on the GLSurfaceView
mRen = new MyRenderer();
setRenderer(mRen);
}
@Override
public boolean onTouchEvent(MotionEvent me) {
// queue event, and handle it from the renderer thread later
// to avoid concurrency handling
if (mRen!=null) mRen.queueTouchEvent(me);
return true;
}
}
class MyRenderer implements GLSurfaceView.Renderer {
static final int MAXQUEUELEN = 6;
Object queuelock = new Object();
MotionEvent [] motionqueue = new MotionEvent [MAXQUEUELEN];
int motionqueue_len = 0;
public void queueTouchEvent(MotionEvent ev) {
synchronized (queuelock) {
if (motionqueue_len >= MAXQUEUELEN) return;
motionqueue[motionqueue_len++] = MotionEvent.obtain(ev);
}
}
static final int MAXTOUCHES=8;
int [] touchids = new int[MAXTOUCHES];
double [] touchx = new double[MAXTOUCHES];
double [] touchy = new double[MAXTOUCHES];
int touchlen = 0;
public void handleTouchEvent(MotionEvent me) {
// XXX We should mask out the pointer id info in some of the
// action codes. Since 2.2, we should use getActionMasked for
// this.
// use MotionEventCompat to do this?
int action = me.getActionMasked();
int ptridx = me.getActionIndex();
// Default coord is the current coordinates of an arbitrary active
// pointer.
double x = me.getX(ptridx);
double y = me.getY(ptridx);
// on a multitouch, touches after the first touch are also
// considered mouse-down flanks.
boolean press = action == MotionEvent.ACTION_DOWN
|| action == MotionEvent.ACTION_POINTER_DOWN;
// boolean down = press || action == MotionEvent.ACTION_MOVE;
// Alcatel pop:
// down event: 0
// move event:<SUF>
// up event: 9.
// ACTION_UP=1, ACTION_POINTER_UP=6
//boolean release = (action & ( MotionEvent.ACTION_UP)) != 0;
// Normal:
boolean release = action == MotionEvent.ACTION_UP
|| action == MotionEvent.ACTION_POINTER_UP;
int ptrid=0;
try {
ptrid = me.getPointerId(ptridx);
} catch (IllegalArgumentException e) {
// getPointerId sometimes throws pointer index out of range
// -> ignore
System.err.println("Failed getting pointer. Ignoring.");
e.printStackTrace();
return;
}
// pass multitouch coordinates before touch event
int pointerCount = me.getPointerCount();
// signal start multitouch info
GlesJSLib.onMultitouchCoordinates(-1,0,0);
for (int p = 0; p < pointerCount; p++) {
try {
int pid = me.getPointerId(p);
GlesJSLib.onMultitouchCoordinates(pid,me.getX(p),me.getY(p));
} catch (IllegalArgumentException e) {
// getPointerId sometimes throws pointer index out of range
// -> ignore
System.err.println("Failed getting pointer. Ignoring.");
e.printStackTrace();
}
}
// signal end coordinate info, start button info
//GlesJSLib.onMultitouchCoordinates(-2,0,0);
// single touch / press-release info
// !press && !release means move
GlesJSLib.onTouchEvent(ptrid,x,y,press,release);
// signal end touch info
GlesJSLib.onMultitouchCoordinates(-3,0,0);
}
public void onDrawFrame(GL10 gl) {
GameController.startOfFrame();
// handle events in the render thread
synchronized (queuelock) {
for (int i=0; i<motionqueue_len; i++) {
if (motionqueue[i]!=null) {
handleTouchEvent(motionqueue[i]);
motionqueue[i].recycle();
motionqueue[i] = null;
}
}
motionqueue_len = 0;
}
for (int i=0; i<GameController.NR_PLAYERS; i++) {
GameController con = GameController.getControllerByPlayer(i);
if (con.isConnected()) {
//System.out.println("##################active@@@@@"+i);
boolean [] buttons = con.getButtons();
float [] axes = con.getAxes();
GlesJSLib.onControllerEvent(i,true,buttons,axes);
} else {
GlesJSLib.onControllerEvent(i,false,null,null);
}
/* FOR TESTING:
} else if (i==0) {
boolean [] buttons = new boolean[]
{true,false,true,false,true,false,true};
float [] axes = new float[]
{9,8,7,6,5};
GlesJSLib.onControllerEvent(i,true,buttons,axes);
}
*/
}
GlesJSLib.onDrawFrame();
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
GameController.init(MainActivity.this);
GlesJSLib.onSurfaceChanged(width, height);
surface_already_created=true;
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
if (surface_already_created) {
// gl context was lost -> we can't handle that yet
// -> commit suicide
// TODO generate contextlost event in JS
System.err.println("GL context lost. Cannot restore. Exiting.");
System.exit(0);
}
// Do nothing.
}
}
}
| False | 1,725 | 6 | 2,055 | 6 | 1,991 | 6 | 2,055 | 6 | 2,581 | 6 | false | false | false | false | false | true |
2,107 | 9505_7 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tomcat.dbcp.dbcp2;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.MessageFormat;
import java.time.Duration;
import java.time.Instant;
import java.util.Collection;
import java.util.HashSet;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.function.Consumer;
import org.apache.tomcat.dbcp.pool2.PooledObject;
/**
* Utility methods.
*
* @since 2.0
*/
public final class Utils {
private static final ResourceBundle messages = ResourceBundle
.getBundle(Utils.class.getPackage().getName() + ".LocalStrings");
/** Any SQL_STATE starting with this value is considered a fatal disconnect */
public static final String DISCONNECTION_SQL_CODE_PREFIX = "08";
/**
* SQL codes of fatal connection errors.
* <ul>
* <li>57P01 (Admin shutdown)</li>
* <li>57P02 (Crash shutdown)</li>
* <li>57P03 (Cannot connect now)</li>
* <li>01002 (SQL92 disconnect error)</li>
* <li>JZ0C0 (Sybase disconnect error)</li>
* <li>JZ0C1 (Sybase disconnect error)</li>
* </ul>
* @deprecated Use {@link #getDisconnectionSqlCodes()}.
*/
@Deprecated
public static final Set<String> DISCONNECTION_SQL_CODES;
static final ResultSet[] EMPTY_RESULT_SET_ARRAY = {};
static final String[] EMPTY_STRING_ARRAY = {};
static {
DISCONNECTION_SQL_CODES = new HashSet<>();
DISCONNECTION_SQL_CODES.add("57P01"); // Admin shutdown
DISCONNECTION_SQL_CODES.add("57P02"); // Crash shutdown
DISCONNECTION_SQL_CODES.add("57P03"); // Cannot connect now
DISCONNECTION_SQL_CODES.add("01002"); // SQL92 disconnect error
DISCONNECTION_SQL_CODES.add("JZ0C0"); // Sybase disconnect error
DISCONNECTION_SQL_CODES.add("JZ0C1"); // Sybase disconnect error
}
/**
* Clones the given char[] if not null.
*
* @param value may be null.
* @return a cloned char[] or null.
*/
public static char[] clone(final char[] value) {
return value == null ? null : value.clone();
}
/**
* Clones the given {@link Properties} without the standard "user" or "password" entries.
*
* @param properties may be null
* @return a clone of the input without the standard "user" or "password" entries.
* @since 2.8.0
*/
public static Properties cloneWithoutCredentials(final Properties properties) {
if (properties != null) {
final Properties temp = (Properties) properties.clone();
temp.remove(Constants.KEY_USER);
temp.remove(Constants.KEY_PASSWORD);
return temp;
}
return properties;
}
/**
* Closes the given {@link AutoCloseable} and if an exception is caught, then calls {@code exceptionHandler}.
*
* @param autoCloseable The resource to close.
* @param exceptionHandler Consumes exception thrown closing this resource.
* @since 2.10.0
*/
public static void close(final AutoCloseable autoCloseable, final Consumer<Exception> exceptionHandler) {
if (autoCloseable != null) {
try {
autoCloseable.close();
} catch (final Exception e) {
if (exceptionHandler != null) {
exceptionHandler.accept(e);
}
}
}
}
/**
* Closes the AutoCloseable (which may be null).
*
* @param autoCloseable an AutoCloseable, may be {@code null}
* @since 2.6.0
*/
public static void closeQuietly(final AutoCloseable autoCloseable) {
close(autoCloseable, null);
}
/**
* Closes the Connection (which may be null).
*
* @param connection a Connection, may be {@code null}
* @deprecated Use {@link #closeQuietly(AutoCloseable)}.
*/
@Deprecated
public static void closeQuietly(final Connection connection) {
closeQuietly((AutoCloseable) connection);
}
/**
* Closes the ResultSet (which may be null).
*
* @param resultSet a ResultSet, may be {@code null}
* @deprecated Use {@link #closeQuietly(AutoCloseable)}.
*/
@Deprecated
public static void closeQuietly(final ResultSet resultSet) {
closeQuietly((AutoCloseable) resultSet);
}
/**
* Closes the Statement (which may be null).
*
* @param statement a Statement, may be {@code null}.
* @deprecated Use {@link #closeQuietly(AutoCloseable)}.
*/
@Deprecated
public static void closeQuietly(final Statement statement) {
closeQuietly((AutoCloseable) statement);
}
/**
* Gets a copy of SQL codes of fatal connection errors.
* <ul>
* <li>57P01 (Admin shutdown)</li>
* <li>57P02 (Crash shutdown)</li>
* <li>57P03 (Cannot connect now)</li>
* <li>01002 (SQL92 disconnect error)</li>
* <li>JZ0C0 (Sybase disconnect error)</li>
* <li>JZ0C1 (Sybase disconnect error)</li>
* </ul>
* @return SQL codes of fatal connection errors.
* @since 2.10.0
*/
public static Set<String> getDisconnectionSqlCodes() {
return new HashSet<>(DISCONNECTION_SQL_CODES);
}
/**
* Gets the correct i18n message for the given key.
*
* @param key The key to look up an i18n message.
* @return The i18n message.
*/
public static String getMessage(final String key) {
return getMessage(key, (Object[]) null);
}
/**
* Gets the correct i18n message for the given key with placeholders replaced by the supplied arguments.
*
* @param key A message key.
* @param args The message arguments.
* @return An i18n message.
*/
public static String getMessage(final String key, final Object... args) {
final String msg = messages.getString(key);
if (args == null || args.length == 0) {
return msg;
}
final MessageFormat mf = new MessageFormat(msg);
return mf.format(args, new StringBuffer(), null).toString();
}
static boolean isEmpty(final Collection<?> collection) {
return collection == null || collection.isEmpty();
}
/**
* Converts the given String to a char[].
*
* @param value may be null.
* @return a char[] or null.
*/
public static char[] toCharArray(final String value) {
return value != null ? value.toCharArray() : null;
}
/**
* Converts the given char[] to a String.
*
* @param value may be null.
* @return a String or null.
*/
public static String toString(final char[] value) {
return value == null ? null : String.valueOf(value);
}
public static void validateLifetime(final PooledObject<?> p, final Duration maxDuration) throws LifetimeExceededException {
if (maxDuration.compareTo(Duration.ZERO) > 0) {
final Duration lifetimeDuration = Duration.between(p.getCreateInstant(), Instant.now());
if (lifetimeDuration.compareTo(maxDuration) > 0) {
throw new LifetimeExceededException(Utils.getMessage("connectionFactory.lifetimeExceeded", lifetimeDuration, maxDuration));
}
}
}
private Utils() {
// not instantiable
}
}
| apache/tomcat | java/org/apache/tomcat/dbcp/dbcp2/Utils.java | 2,324 | // Sybase disconnect error | 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.tomcat.dbcp.dbcp2;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.MessageFormat;
import java.time.Duration;
import java.time.Instant;
import java.util.Collection;
import java.util.HashSet;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.function.Consumer;
import org.apache.tomcat.dbcp.pool2.PooledObject;
/**
* Utility methods.
*
* @since 2.0
*/
public final class Utils {
private static final ResourceBundle messages = ResourceBundle
.getBundle(Utils.class.getPackage().getName() + ".LocalStrings");
/** Any SQL_STATE starting with this value is considered a fatal disconnect */
public static final String DISCONNECTION_SQL_CODE_PREFIX = "08";
/**
* SQL codes of fatal connection errors.
* <ul>
* <li>57P01 (Admin shutdown)</li>
* <li>57P02 (Crash shutdown)</li>
* <li>57P03 (Cannot connect now)</li>
* <li>01002 (SQL92 disconnect error)</li>
* <li>JZ0C0 (Sybase disconnect error)</li>
* <li>JZ0C1 (Sybase disconnect error)</li>
* </ul>
* @deprecated Use {@link #getDisconnectionSqlCodes()}.
*/
@Deprecated
public static final Set<String> DISCONNECTION_SQL_CODES;
static final ResultSet[] EMPTY_RESULT_SET_ARRAY = {};
static final String[] EMPTY_STRING_ARRAY = {};
static {
DISCONNECTION_SQL_CODES = new HashSet<>();
DISCONNECTION_SQL_CODES.add("57P01"); // Admin shutdown
DISCONNECTION_SQL_CODES.add("57P02"); // Crash shutdown
DISCONNECTION_SQL_CODES.add("57P03"); // Cannot connect now
DISCONNECTION_SQL_CODES.add("01002"); // SQL92 disconnect error
DISCONNECTION_SQL_CODES.add("JZ0C0"); // Sybase disconnect error
DISCONNECTION_SQL_CODES.add("JZ0C1"); // Sybase disconnect<SUF>
}
/**
* Clones the given char[] if not null.
*
* @param value may be null.
* @return a cloned char[] or null.
*/
public static char[] clone(final char[] value) {
return value == null ? null : value.clone();
}
/**
* Clones the given {@link Properties} without the standard "user" or "password" entries.
*
* @param properties may be null
* @return a clone of the input without the standard "user" or "password" entries.
* @since 2.8.0
*/
public static Properties cloneWithoutCredentials(final Properties properties) {
if (properties != null) {
final Properties temp = (Properties) properties.clone();
temp.remove(Constants.KEY_USER);
temp.remove(Constants.KEY_PASSWORD);
return temp;
}
return properties;
}
/**
* Closes the given {@link AutoCloseable} and if an exception is caught, then calls {@code exceptionHandler}.
*
* @param autoCloseable The resource to close.
* @param exceptionHandler Consumes exception thrown closing this resource.
* @since 2.10.0
*/
public static void close(final AutoCloseable autoCloseable, final Consumer<Exception> exceptionHandler) {
if (autoCloseable != null) {
try {
autoCloseable.close();
} catch (final Exception e) {
if (exceptionHandler != null) {
exceptionHandler.accept(e);
}
}
}
}
/**
* Closes the AutoCloseable (which may be null).
*
* @param autoCloseable an AutoCloseable, may be {@code null}
* @since 2.6.0
*/
public static void closeQuietly(final AutoCloseable autoCloseable) {
close(autoCloseable, null);
}
/**
* Closes the Connection (which may be null).
*
* @param connection a Connection, may be {@code null}
* @deprecated Use {@link #closeQuietly(AutoCloseable)}.
*/
@Deprecated
public static void closeQuietly(final Connection connection) {
closeQuietly((AutoCloseable) connection);
}
/**
* Closes the ResultSet (which may be null).
*
* @param resultSet a ResultSet, may be {@code null}
* @deprecated Use {@link #closeQuietly(AutoCloseable)}.
*/
@Deprecated
public static void closeQuietly(final ResultSet resultSet) {
closeQuietly((AutoCloseable) resultSet);
}
/**
* Closes the Statement (which may be null).
*
* @param statement a Statement, may be {@code null}.
* @deprecated Use {@link #closeQuietly(AutoCloseable)}.
*/
@Deprecated
public static void closeQuietly(final Statement statement) {
closeQuietly((AutoCloseable) statement);
}
/**
* Gets a copy of SQL codes of fatal connection errors.
* <ul>
* <li>57P01 (Admin shutdown)</li>
* <li>57P02 (Crash shutdown)</li>
* <li>57P03 (Cannot connect now)</li>
* <li>01002 (SQL92 disconnect error)</li>
* <li>JZ0C0 (Sybase disconnect error)</li>
* <li>JZ0C1 (Sybase disconnect error)</li>
* </ul>
* @return SQL codes of fatal connection errors.
* @since 2.10.0
*/
public static Set<String> getDisconnectionSqlCodes() {
return new HashSet<>(DISCONNECTION_SQL_CODES);
}
/**
* Gets the correct i18n message for the given key.
*
* @param key The key to look up an i18n message.
* @return The i18n message.
*/
public static String getMessage(final String key) {
return getMessage(key, (Object[]) null);
}
/**
* Gets the correct i18n message for the given key with placeholders replaced by the supplied arguments.
*
* @param key A message key.
* @param args The message arguments.
* @return An i18n message.
*/
public static String getMessage(final String key, final Object... args) {
final String msg = messages.getString(key);
if (args == null || args.length == 0) {
return msg;
}
final MessageFormat mf = new MessageFormat(msg);
return mf.format(args, new StringBuffer(), null).toString();
}
static boolean isEmpty(final Collection<?> collection) {
return collection == null || collection.isEmpty();
}
/**
* Converts the given String to a char[].
*
* @param value may be null.
* @return a char[] or null.
*/
public static char[] toCharArray(final String value) {
return value != null ? value.toCharArray() : null;
}
/**
* Converts the given char[] to a String.
*
* @param value may be null.
* @return a String or null.
*/
public static String toString(final char[] value) {
return value == null ? null : String.valueOf(value);
}
public static void validateLifetime(final PooledObject<?> p, final Duration maxDuration) throws LifetimeExceededException {
if (maxDuration.compareTo(Duration.ZERO) > 0) {
final Duration lifetimeDuration = Duration.between(p.getCreateInstant(), Instant.now());
if (lifetimeDuration.compareTo(maxDuration) > 0) {
throw new LifetimeExceededException(Utils.getMessage("connectionFactory.lifetimeExceeded", lifetimeDuration, maxDuration));
}
}
}
private Utils() {
// not instantiable
}
}
| False | 1,914 | 5 | 2,009 | 5 | 2,188 | 5 | 2,009 | 5 | 2,456 | 6 | false | false | false | false | false | true |
4,652 | 84266_1 | package nl.vpro.amara;
import java.io.IOException;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import nl.vpro.amara.domain.Action;
import nl.vpro.amara.domain.Subtitles;
import nl.vpro.amara_poms.Config;
import nl.vpro.amara_poms.poms.PomsBroadcast;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author joost
*/
public class SubtitlesTest {
final static Logger LOG = LoggerFactory.getLogger(SubtitlesTest.class);
@BeforeEach
public void setUp() {
Config.init();
}
@Test
public void testDummy() {
assertTrue(true);
}
@Test
public void testPost() {
Subtitles amaraSubtitles = new Subtitles("test subtitles", "vtt",
"WEBVTT\n" +
"\n" +
"1\n" +
"00:00:02.018 --> 00:00:05.007\n" +
"888\n" +
"\n" +
"2\n" +
"00:00:05.012 --> 00:00:07.018\n" +
"TUNE VAN DWDD\n", "test description", "complete");
Subtitles newAmaraSubtitles = Config.getAmaraClient().videos().post(amaraSubtitles, "gDq7bAA5XFCR", "nl");
assertNotNull(newAmaraSubtitles);
}
@Test
public void getActions() {
String video_id = "Ep1jZa6c2NRt";
List<Action> actions = Config.getAmaraClient().videos().getActions(video_id, "nl");
System.out.println("" + actions);
}
@Test
public void amarapoms3() throws IOException {
String video_id = "Ep1jZa6c2NRt";
PomsBroadcast pomsBroadcast = new PomsBroadcast("VPWON_1256298", null);
pomsBroadcast.downloadSubtitles();
Subtitles amaraSubtitles = new Subtitles("Blauw Bloed // Een interview met prinses Irene", "vtt",
pomsBroadcast.getSubtitles(), "Een interview met prinses Irene, we volgen koning Willem-Alexander bij de start van de Giro d'Italia en couturier Paul Schulten vertelt alles over koninklijke bloemetjesjurken.", "save-draft");
Subtitles newAmaraSubtitles = Config.getAmaraClient().videos().post(amaraSubtitles, video_id, "nl");
assertNotNull(newAmaraSubtitles);
}
public void testGetVTT() {
String amaraSubtitles = Config.getAmaraClient().videos().getAsVTT("G3CnVJdMw21Y", "nl", Config.getRequiredConfig("amara.subtitles.format"));
assertNotNull(amaraSubtitles);
LOG.info(amaraSubtitles);
}
public void testGet() {
Subtitles amaraSubtitles = Config.getAmaraClient().videos().getSubtitles("G3CnVJdMw21Y", "nl", Config.getRequiredConfig("amara.subtitles.format"));
assertNotNull(amaraSubtitles);
LOG.info(StringUtils.abbreviate(amaraSubtitles.getSubtitles(), 20));
LOG.info((amaraSubtitles.getVersion_no()));
}
}
| vpro/amara-poms | src/test/java/nl/vpro/amara/SubtitlesTest.java | 1,053 | // Een interview met prinses Irene", "vtt", | line_comment | nl | package nl.vpro.amara;
import java.io.IOException;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import nl.vpro.amara.domain.Action;
import nl.vpro.amara.domain.Subtitles;
import nl.vpro.amara_poms.Config;
import nl.vpro.amara_poms.poms.PomsBroadcast;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author joost
*/
public class SubtitlesTest {
final static Logger LOG = LoggerFactory.getLogger(SubtitlesTest.class);
@BeforeEach
public void setUp() {
Config.init();
}
@Test
public void testDummy() {
assertTrue(true);
}
@Test
public void testPost() {
Subtitles amaraSubtitles = new Subtitles("test subtitles", "vtt",
"WEBVTT\n" +
"\n" +
"1\n" +
"00:00:02.018 --> 00:00:05.007\n" +
"888\n" +
"\n" +
"2\n" +
"00:00:05.012 --> 00:00:07.018\n" +
"TUNE VAN DWDD\n", "test description", "complete");
Subtitles newAmaraSubtitles = Config.getAmaraClient().videos().post(amaraSubtitles, "gDq7bAA5XFCR", "nl");
assertNotNull(newAmaraSubtitles);
}
@Test
public void getActions() {
String video_id = "Ep1jZa6c2NRt";
List<Action> actions = Config.getAmaraClient().videos().getActions(video_id, "nl");
System.out.println("" + actions);
}
@Test
public void amarapoms3() throws IOException {
String video_id = "Ep1jZa6c2NRt";
PomsBroadcast pomsBroadcast = new PomsBroadcast("VPWON_1256298", null);
pomsBroadcast.downloadSubtitles();
Subtitles amaraSubtitles = new Subtitles("Blauw Bloed // Een interview<SUF>
pomsBroadcast.getSubtitles(), "Een interview met prinses Irene, we volgen koning Willem-Alexander bij de start van de Giro d'Italia en couturier Paul Schulten vertelt alles over koninklijke bloemetjesjurken.", "save-draft");
Subtitles newAmaraSubtitles = Config.getAmaraClient().videos().post(amaraSubtitles, video_id, "nl");
assertNotNull(newAmaraSubtitles);
}
public void testGetVTT() {
String amaraSubtitles = Config.getAmaraClient().videos().getAsVTT("G3CnVJdMw21Y", "nl", Config.getRequiredConfig("amara.subtitles.format"));
assertNotNull(amaraSubtitles);
LOG.info(amaraSubtitles);
}
public void testGet() {
Subtitles amaraSubtitles = Config.getAmaraClient().videos().getSubtitles("G3CnVJdMw21Y", "nl", Config.getRequiredConfig("amara.subtitles.format"));
assertNotNull(amaraSubtitles);
LOG.info(StringUtils.abbreviate(amaraSubtitles.getSubtitles(), 20));
LOG.info((amaraSubtitles.getVersion_no()));
}
}
| True | 797 | 13 | 926 | 17 | 931 | 12 | 926 | 17 | 1,083 | 14 | false | false | false | false | false | true |
684 | 74866_11 | package controller;
import database.mysql.CourseDAO;
import database.mysql.QuestionDAO;
import database.mysql.QuizDAO;
import javacouchdb.CouchDBaccess;
import javacouchdb.QuizResultCouchDBDAO;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import model.Question;
import model.Quiz;
import model.QuizResult;
import view.Main;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class FillOutQuizController {
private final QuestionDAO questionDAO = new QuestionDAO(Main.getDBaccess());
private final QuizDAO quizDAO = new QuizDAO(Main.getDBaccess());
CouchDBaccess couchDBaccess = new CouchDBaccess("quizmaster","admin", "admin");
private final QuizResultCouchDBDAO quizResultCouchDBDAO = new QuizResultCouchDBDAO(couchDBaccess);
List<Question> questionsQuiz = new ArrayList<>();
private int currentQuestionNumber;
private int vraagNummer = 1;
private int correctAnswers;
private int loginUserId;
private int quizId;
@FXML
private Label titleLabel;
@FXML
private TextArea questionArea;
@FXML
private Button answerA;
@FXML
private Button answerB;
@FXML
private Button answerC;
@FXML
private Button answerD;
@FXML
private Button previousQuestion;
@FXML
private Button nextQuestion;
@FXML
private Button finishQuiz;
@FXML
private Button back;
public void setup(int quizId, int userId) {
loginUserId = userId;
this.quizId = quizId;
//verzamel de vragen die horen bij ingegeven quizId
questionsQuiz = questionDAO.getQuestionsByQuizId(quizId);
//schud de vragen door elkaar
Collections.shuffle(questionsQuiz);
//beginnen met de 1e vraag
currentQuestionNumber = 0;
//score initializeren
correctAnswers = 0;
//Titel
titleLabel.setText("Vraag " + vraagNummer);
//1e vraag tonen
displayQuestion();
}
private void displayQuestion() {
//zolang currenctQuestionNumber tussen 0 en size van questionQuiz zit,
// wordt er een nieuwe vraag met antwoorden getoond
if (currentQuestionNumber >= 0 && currentQuestionNumber < questionsQuiz.size()){
Question currentQuestion = questionsQuiz.get(currentQuestionNumber);
//lijst van antwoorden maken en deze door elkaar shuffelen
ArrayList<String> answerChoices = new ArrayList<>();
answerChoices.add(currentQuestion.getCorrectAnswer());
answerChoices.add(currentQuestion.getAnswer2());
answerChoices.add(currentQuestion.getAnswer3());
answerChoices.add(currentQuestion.getAnswer4());
Collections.shuffle(answerChoices);
//Toon de vraag en de geshuffelde antwoorden in de textarea
String question = currentQuestion.getTextQuestion() + "\n";
String answers = "A. " + answerChoices.get(0) + "\n" +
"B. " + answerChoices.get(1) + "\n" +
"C. " + answerChoices.get(2) + "\n" +
"D. " + answerChoices.get(3);
questionArea.setText(question + answers);
//Button acties instellen
answerA.setOnAction(event -> checkAnswer(currentQuestion, answerChoices.get(0)));
answerB.setOnAction(event -> checkAnswer(currentQuestion, answerChoices.get(1)));
answerC.setOnAction(event -> checkAnswer(currentQuestion, answerChoices.get(2)));
answerD.setOnAction(event -> checkAnswer(currentQuestion, answerChoices.get(3)));
//aangeven wanneer knoppen next en previous niet werken
nextQuestion.setVisible(currentQuestionNumber != questionsQuiz.size() - 1);
finishQuiz.setVisible(currentQuestionNumber == questionsQuiz.size() - 1);
previousQuestion.setDisable(currentQuestionNumber == 0);
}
}
//Methode die controleert of de String van het gekozen antwoord van de currentQuestion
//overeenkomt met het attribuut correctAnswer van de currentQuestion.
//Als dit het geval is gaat correctAnswers 1 omhoog
private void checkAnswer(Question currentQuestion, String selectedAnswer) {
if (selectedAnswer.equals(currentQuestion.getCorrectAnswer())) {
correctAnswers++;
}
//volgende vraag tonen
currentQuestionNumber++;
vraagNummer++;
titleLabel.setText("Vraag " + vraagNummer);
displayQuestion();
}
//volgende vraag tonen
public void doNextQuestion() {
currentQuestionNumber++;
vraagNummer++;
titleLabel.setText("Vraag " + vraagNummer);
displayQuestion();
}
//vorige vraag tonen
public void doPreviousQuestion() {
currentQuestionNumber--;
vraagNummer--;
titleLabel.setText("Vraag " + vraagNummer);
displayQuestion();
}
public void doMenu() {
Main.getSceneManager().showSelectQuizForStudent(loginUserId);
}
public void doFinishQuiz () {
QuizResult quizResult = new QuizResult(loginUserId, quizId, quizDAO.getOneById(quizId).getSuccesDefinition(), LocalDateTime.now().toString(), correctAnswers, questionsQuiz.size());
quizResultCouchDBDAO.saveSingleQuizResult(quizResult);
Main.getSceneManager().showStudentFeedback(loginUserId, quizDAO.getOneById(quizId));
}
}
| Hayac1113/Quiz_System_Project | src/main/java/controller/FillOutQuizController.java | 1,637 | //overeenkomt met het attribuut correctAnswer van de currentQuestion. | line_comment | nl | package controller;
import database.mysql.CourseDAO;
import database.mysql.QuestionDAO;
import database.mysql.QuizDAO;
import javacouchdb.CouchDBaccess;
import javacouchdb.QuizResultCouchDBDAO;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import model.Question;
import model.Quiz;
import model.QuizResult;
import view.Main;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class FillOutQuizController {
private final QuestionDAO questionDAO = new QuestionDAO(Main.getDBaccess());
private final QuizDAO quizDAO = new QuizDAO(Main.getDBaccess());
CouchDBaccess couchDBaccess = new CouchDBaccess("quizmaster","admin", "admin");
private final QuizResultCouchDBDAO quizResultCouchDBDAO = new QuizResultCouchDBDAO(couchDBaccess);
List<Question> questionsQuiz = new ArrayList<>();
private int currentQuestionNumber;
private int vraagNummer = 1;
private int correctAnswers;
private int loginUserId;
private int quizId;
@FXML
private Label titleLabel;
@FXML
private TextArea questionArea;
@FXML
private Button answerA;
@FXML
private Button answerB;
@FXML
private Button answerC;
@FXML
private Button answerD;
@FXML
private Button previousQuestion;
@FXML
private Button nextQuestion;
@FXML
private Button finishQuiz;
@FXML
private Button back;
public void setup(int quizId, int userId) {
loginUserId = userId;
this.quizId = quizId;
//verzamel de vragen die horen bij ingegeven quizId
questionsQuiz = questionDAO.getQuestionsByQuizId(quizId);
//schud de vragen door elkaar
Collections.shuffle(questionsQuiz);
//beginnen met de 1e vraag
currentQuestionNumber = 0;
//score initializeren
correctAnswers = 0;
//Titel
titleLabel.setText("Vraag " + vraagNummer);
//1e vraag tonen
displayQuestion();
}
private void displayQuestion() {
//zolang currenctQuestionNumber tussen 0 en size van questionQuiz zit,
// wordt er een nieuwe vraag met antwoorden getoond
if (currentQuestionNumber >= 0 && currentQuestionNumber < questionsQuiz.size()){
Question currentQuestion = questionsQuiz.get(currentQuestionNumber);
//lijst van antwoorden maken en deze door elkaar shuffelen
ArrayList<String> answerChoices = new ArrayList<>();
answerChoices.add(currentQuestion.getCorrectAnswer());
answerChoices.add(currentQuestion.getAnswer2());
answerChoices.add(currentQuestion.getAnswer3());
answerChoices.add(currentQuestion.getAnswer4());
Collections.shuffle(answerChoices);
//Toon de vraag en de geshuffelde antwoorden in de textarea
String question = currentQuestion.getTextQuestion() + "\n";
String answers = "A. " + answerChoices.get(0) + "\n" +
"B. " + answerChoices.get(1) + "\n" +
"C. " + answerChoices.get(2) + "\n" +
"D. " + answerChoices.get(3);
questionArea.setText(question + answers);
//Button acties instellen
answerA.setOnAction(event -> checkAnswer(currentQuestion, answerChoices.get(0)));
answerB.setOnAction(event -> checkAnswer(currentQuestion, answerChoices.get(1)));
answerC.setOnAction(event -> checkAnswer(currentQuestion, answerChoices.get(2)));
answerD.setOnAction(event -> checkAnswer(currentQuestion, answerChoices.get(3)));
//aangeven wanneer knoppen next en previous niet werken
nextQuestion.setVisible(currentQuestionNumber != questionsQuiz.size() - 1);
finishQuiz.setVisible(currentQuestionNumber == questionsQuiz.size() - 1);
previousQuestion.setDisable(currentQuestionNumber == 0);
}
}
//Methode die controleert of de String van het gekozen antwoord van de currentQuestion
//overeenkomt met<SUF>
//Als dit het geval is gaat correctAnswers 1 omhoog
private void checkAnswer(Question currentQuestion, String selectedAnswer) {
if (selectedAnswer.equals(currentQuestion.getCorrectAnswer())) {
correctAnswers++;
}
//volgende vraag tonen
currentQuestionNumber++;
vraagNummer++;
titleLabel.setText("Vraag " + vraagNummer);
displayQuestion();
}
//volgende vraag tonen
public void doNextQuestion() {
currentQuestionNumber++;
vraagNummer++;
titleLabel.setText("Vraag " + vraagNummer);
displayQuestion();
}
//vorige vraag tonen
public void doPreviousQuestion() {
currentQuestionNumber--;
vraagNummer--;
titleLabel.setText("Vraag " + vraagNummer);
displayQuestion();
}
public void doMenu() {
Main.getSceneManager().showSelectQuizForStudent(loginUserId);
}
public void doFinishQuiz () {
QuizResult quizResult = new QuizResult(loginUserId, quizId, quizDAO.getOneById(quizId).getSuccesDefinition(), LocalDateTime.now().toString(), correctAnswers, questionsQuiz.size());
quizResultCouchDBDAO.saveSingleQuizResult(quizResult);
Main.getSceneManager().showStudentFeedback(loginUserId, quizDAO.getOneById(quizId));
}
}
| True | 1,221 | 17 | 1,362 | 19 | 1,357 | 15 | 1,362 | 19 | 1,610 | 18 | false | false | false | false | false | true |
1,559 | 69709_0 | package com.example.sanjiv.awarenessapp;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class LampDetails extends AppCompatActivity implements View.OnClickListener {
private TextView naam, brightness, maxDecibel, huidigeDecibel;
private Button edit, notify, removeNotify;
private FirebaseDatabase database;
private FirebaseAuth auth;
private FirebaseUser user;
private DatabaseReference mDatabase;
private String key, lampNaam, userRole;
private boolean isNotifyOn;
private Lampen lamp;
Context ctx;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lamp_details);
naam = findViewById(R.id.naamLamp);
maxDecibel = findViewById(R.id.MaxDecibel);
huidigeDecibel = findViewById(R.id.HuidigeDecibel);
edit = findViewById(R.id.editLamp);
notify = findViewById(R.id.addNotify);
removeNotify = findViewById(R.id.removeNotify);
edit.setOnClickListener(this);
notify.setOnClickListener(this);
removeNotify.setOnClickListener(this);
auth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
user = auth.getCurrentUser();
mDatabase = database.getReference();
//Scherm in het fragment, backPress brengt je terug naar Lampen fragment
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int) (width * .95), (int) (height * .9));
naam.setText(getIntent().getStringExtra("naam"));
maxDecibel.setText(getIntent().getStringExtra("maxDecibel"));
huidigeDecibel.setText(getIntent().getStringExtra("huidigeDecibel"));
isNotifyOn = Boolean.parseBoolean(getIntent().getStringExtra("notifyOn"));
Log.d("ADebugTag", "notifyOn = " + isNotifyOn);
edit.setVisibility(View.GONE);
notify.setVisibility(View.GONE);
removeNotify.setVisibility(View.GONE);
if (isNotifyOn) {
removeNotify.setVisibility(View.VISIBLE);
} else {
notify.setVisibility(View.VISIBLE);
}
userIsAdmin();
}
@Override
public void onClick(View v) {
if (v == edit) {
Intent intent = new Intent(this, EditLamp.class);
intent.putExtra("naam", getIntent().getStringExtra("naam"));
intent.putExtra("key", getIntent().getStringExtra("key"));
intent.putExtra("huidigeDecibel", getIntent().getStringExtra("huidigeDecibel"));
intent.putExtra("maxDecibel", getIntent().getStringExtra("maxDecibel"));
this.startActivity(intent);
}
if (v == notify) {
Intent intent = new Intent(this, AddNotifyLamp.class);
intent.putExtra("naam", getIntent().getStringExtra("naam"));
intent.putExtra("key", getIntent().getStringExtra("key"));
intent.putExtra("huidigeDecibel", getIntent().getStringExtra("huidigeDecibel"));
intent.putExtra("maxDecibel", getIntent().getStringExtra("maxDecibel"));
this.startActivity(intent);
}
if (v == removeNotify) {
Intent intent = new Intent(this, DeleteNotifyLamp.class);
intent.putExtra("key", getIntent().getStringExtra("key"));
this.startActivity(intent);
}
}
public void userIsAdmin() {
DatabaseReference ref_userRole = mDatabase.child("users").child(user.getUid()).child("rollen");
ref_userRole.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserModel userM = dataSnapshot.getValue(UserModel.class);
userRole = userM.getUserRole();
Log.d("ADebugTag", "Value from database: " + userRole);
updateButtons();
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.d("Lamps", "credentialsUserRoleGet:failure", databaseError.toException());
}
});
}
public void updateButtons() {
if (userRole != null) {
if (userRole.equalsIgnoreCase("admin")) {
Log.d("ADebugTag", "Value from updateButtons: " + userRole);
edit.setVisibility(View.VISIBLE);
}
}
}
}
| Sannijiv/AwarenessApp | app/src/main/java/com/example/sanjiv/awarenessapp/LampDetails.java | 1,525 | //Scherm in het fragment, backPress brengt je terug naar Lampen fragment | line_comment | nl | package com.example.sanjiv.awarenessapp;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class LampDetails extends AppCompatActivity implements View.OnClickListener {
private TextView naam, brightness, maxDecibel, huidigeDecibel;
private Button edit, notify, removeNotify;
private FirebaseDatabase database;
private FirebaseAuth auth;
private FirebaseUser user;
private DatabaseReference mDatabase;
private String key, lampNaam, userRole;
private boolean isNotifyOn;
private Lampen lamp;
Context ctx;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lamp_details);
naam = findViewById(R.id.naamLamp);
maxDecibel = findViewById(R.id.MaxDecibel);
huidigeDecibel = findViewById(R.id.HuidigeDecibel);
edit = findViewById(R.id.editLamp);
notify = findViewById(R.id.addNotify);
removeNotify = findViewById(R.id.removeNotify);
edit.setOnClickListener(this);
notify.setOnClickListener(this);
removeNotify.setOnClickListener(this);
auth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
user = auth.getCurrentUser();
mDatabase = database.getReference();
//Scherm in<SUF>
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int) (width * .95), (int) (height * .9));
naam.setText(getIntent().getStringExtra("naam"));
maxDecibel.setText(getIntent().getStringExtra("maxDecibel"));
huidigeDecibel.setText(getIntent().getStringExtra("huidigeDecibel"));
isNotifyOn = Boolean.parseBoolean(getIntent().getStringExtra("notifyOn"));
Log.d("ADebugTag", "notifyOn = " + isNotifyOn);
edit.setVisibility(View.GONE);
notify.setVisibility(View.GONE);
removeNotify.setVisibility(View.GONE);
if (isNotifyOn) {
removeNotify.setVisibility(View.VISIBLE);
} else {
notify.setVisibility(View.VISIBLE);
}
userIsAdmin();
}
@Override
public void onClick(View v) {
if (v == edit) {
Intent intent = new Intent(this, EditLamp.class);
intent.putExtra("naam", getIntent().getStringExtra("naam"));
intent.putExtra("key", getIntent().getStringExtra("key"));
intent.putExtra("huidigeDecibel", getIntent().getStringExtra("huidigeDecibel"));
intent.putExtra("maxDecibel", getIntent().getStringExtra("maxDecibel"));
this.startActivity(intent);
}
if (v == notify) {
Intent intent = new Intent(this, AddNotifyLamp.class);
intent.putExtra("naam", getIntent().getStringExtra("naam"));
intent.putExtra("key", getIntent().getStringExtra("key"));
intent.putExtra("huidigeDecibel", getIntent().getStringExtra("huidigeDecibel"));
intent.putExtra("maxDecibel", getIntent().getStringExtra("maxDecibel"));
this.startActivity(intent);
}
if (v == removeNotify) {
Intent intent = new Intent(this, DeleteNotifyLamp.class);
intent.putExtra("key", getIntent().getStringExtra("key"));
this.startActivity(intent);
}
}
public void userIsAdmin() {
DatabaseReference ref_userRole = mDatabase.child("users").child(user.getUid()).child("rollen");
ref_userRole.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserModel userM = dataSnapshot.getValue(UserModel.class);
userRole = userM.getUserRole();
Log.d("ADebugTag", "Value from database: " + userRole);
updateButtons();
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.d("Lamps", "credentialsUserRoleGet:failure", databaseError.toException());
}
});
}
public void updateButtons() {
if (userRole != null) {
if (userRole.equalsIgnoreCase("admin")) {
Log.d("ADebugTag", "Value from updateButtons: " + userRole);
edit.setVisibility(View.VISIBLE);
}
}
}
}
| True | 994 | 18 | 1,228 | 20 | 1,229 | 16 | 1,228 | 20 | 1,440 | 19 | false | false | false | false | false | true |
3,611 | 23619_1 | package nl.duckson.zombiesiege.entity;
import java.awt.geom.AffineTransform;
public class Human extends Entity implements Directionable, Attackable {
protected static int width = 64, height = 64;
/**
* The direction in degrees the entity is facing
*/
protected int direction = 0;
public Human() {
this.hitpoints = startHitpoints();
}
public int hit(Attackable enemy) {
return 0;
}
protected int hitpoints = 0;
public int startHitpoints() {
return 10;
}
public int getHitpoints() {
return hitpoints;
}
public boolean isDead() {
return hitpoints >= 0;
}
public void watch(int x, int y) {
// Bereken de hoek om naar te kijken...
int delta_x = this.x - x;
int delta_y = this.y - y;
// @todo: This calculation is terrible, refactor it!
direction = (int) Math.toDegrees(
Math.atan2(delta_y, delta_x)
);
// @todo: Find out what this offset is about
direction -= (90 + 45);
}
public AffineTransform getAffineTransform() {
AffineTransform trans = new AffineTransform();
trans.translate(x, y);
trans.rotate(Math.toRadians(direction), width / 2, height / 2);
return trans;
}
public int getDirectionDegrees() {
return direction;
}
public double getDirectionRadians() {
return Math.toRadians(direction);
}
public String getIcon() {
return "human.png";
}
}
| mbernson/zombiesiege | src/nl/duckson/zombiesiege/entity/Human.java | 457 | // Bereken de hoek om naar te kijken... | line_comment | nl | package nl.duckson.zombiesiege.entity;
import java.awt.geom.AffineTransform;
public class Human extends Entity implements Directionable, Attackable {
protected static int width = 64, height = 64;
/**
* The direction in degrees the entity is facing
*/
protected int direction = 0;
public Human() {
this.hitpoints = startHitpoints();
}
public int hit(Attackable enemy) {
return 0;
}
protected int hitpoints = 0;
public int startHitpoints() {
return 10;
}
public int getHitpoints() {
return hitpoints;
}
public boolean isDead() {
return hitpoints >= 0;
}
public void watch(int x, int y) {
// Bereken de<SUF>
int delta_x = this.x - x;
int delta_y = this.y - y;
// @todo: This calculation is terrible, refactor it!
direction = (int) Math.toDegrees(
Math.atan2(delta_y, delta_x)
);
// @todo: Find out what this offset is about
direction -= (90 + 45);
}
public AffineTransform getAffineTransform() {
AffineTransform trans = new AffineTransform();
trans.translate(x, y);
trans.rotate(Math.toRadians(direction), width / 2, height / 2);
return trans;
}
public int getDirectionDegrees() {
return direction;
}
public double getDirectionRadians() {
return Math.toRadians(direction);
}
public String getIcon() {
return "human.png";
}
}
| True | 359 | 11 | 395 | 13 | 434 | 10 | 395 | 13 | 477 | 13 | false | false | false | false | false | true |
1,672 | 68948_7 | package teammates.e2e.cases;
import org.testng.annotations.Test;
import teammates.common.datatransfer.attributes.StudentAttributes;
import teammates.common.util.AppUrl;
import teammates.common.util.Const;
import teammates.e2e.pageobjects.InstructorCourseEnrollPage;
/**
* SUT: {@link Const.WebPageURIs#INSTRUCTOR_COURSE_ENROLL_PAGE}.
*/
public class InstructorCourseEnrollPageE2ETest extends BaseE2ETestCase {
@Override
protected void prepareTestData() {
testData = loadDataBundle("/InstructorCourseEnrollPageE2ETest.json");
removeAndRestoreDataBundle(testData);
sqlTestData = removeAndRestoreSqlDataBundle(
loadSqlDataBundle("/InstructorCourseEnrollPageE2ETest_SqlEntities.json"));
}
@Test
@Override
public void testAll() {
AppUrl url = createFrontendUrl(Const.WebPageURIs.INSTRUCTOR_COURSE_ENROLL_PAGE)
.withCourseId(testData.courses.get("ICEnroll.CS2104").getId());
InstructorCourseEnrollPage enrollPage = loginToPage(url, InstructorCourseEnrollPage.class,
testData.instructors.get("ICEnroll.teammates.test").getGoogleId());
______TS("Add rows to enroll spreadsheet");
int numRowsToAdd = 30;
enrollPage.addEnrollSpreadsheetRows(numRowsToAdd);
enrollPage.verifyNumAddedEnrollSpreadsheetRows(numRowsToAdd);
______TS("Enroll students to empty course");
StudentAttributes student1 = createCourseStudent("Section 1", "Team 1", "Alice Betsy",
"alice.b.tmms@gmail.tmt", "Comment for Alice");
StudentAttributes student2 = createCourseStudent("Section 1", "Team 1", "Benny Charles",
"benny.c.tmms@gmail.tmt", "Comment for Benny");
StudentAttributes student3 = createCourseStudent("Section 2", "Team 2", "Charlie Davis",
"charlie.d.tmms@gmail.tmt", "Comment for Charlie");
StudentAttributes[] studentsEnrollingToEmptyCourse = { student1, student2, student3 };
enrollPage.enroll(studentsEnrollingToEmptyCourse);
enrollPage.verifyStatusMessage("Enrollment successful. Summary given below.");
enrollPage.verifyResultsPanelContains(studentsEnrollingToEmptyCourse, null, null, null, null);
// refresh page to confirm enrollment
enrollPage = getNewPageInstance(url, InstructorCourseEnrollPage.class);
enrollPage.verifyExistingStudentsTableContains(studentsEnrollingToEmptyCourse);
// verify students in database
assertEquals(getStudent(student1), student1);
assertEquals(getStudent(student2), student2);
assertEquals(getStudent(student3), student3);
______TS("Enroll and modify students in existing course");
// modify team details of existing student
student3.setTeam("Team 3");
// add valid new student
StudentAttributes student4 = createCourseStudent("Section 2", "Team 2", "Danny Engrid",
"danny.e.tmms@gmail.tmt", "Comment for Danny");
// add new student with invalid email
StudentAttributes student5 = createCourseStudent("Section 2", "Team 2", "Invalid Student",
"invalid.email", "Comment for Invalid");
// student2 included to test modified without change table
StudentAttributes[] studentsEnrollingToExistingCourse = {student2, student3, student4, student5};
enrollPage.enroll(studentsEnrollingToExistingCourse);
enrollPage.verifyStatusMessage("Some students failed to be enrolled, see the summary below.");
StudentAttributes[] newStudentsData = {student4};
StudentAttributes[] modifiedStudentsData = {student3};
StudentAttributes[] modifiedWithoutChangeStudentsData = {student2};
StudentAttributes[] errorStudentsData = {student5};
StudentAttributes[] unmodifiedStudentsData = {student1};
enrollPage.verifyResultsPanelContains(newStudentsData, modifiedStudentsData, modifiedWithoutChangeStudentsData,
errorStudentsData, unmodifiedStudentsData);
// verify students in database
assertEquals(getStudent(student1), student1);
assertEquals(getStudent(student2), student2);
assertEquals(getStudent(student3), student3);
assertEquals(getStudent(student4), student4);
assertNull(getStudent(student5));
// refresh page to confirm enrollment
enrollPage = getNewPageInstance(url, InstructorCourseEnrollPage.class);
StudentAttributes[] expectedExistingData = {student1, student2, student3, student4};
enrollPage.verifyExistingStudentsTableContains(expectedExistingData);
}
private StudentAttributes createCourseStudent(String section, String team, String name,
String email, String comments) {
return StudentAttributes.builder("tm.e2e.ICEnroll.CS2104", email)
.withName(name)
.withComment(comments)
.withTeamName(team)
.withSectionName(section)
.build();
}
}
| TEAMMATES/teammates | src/e2e/java/teammates/e2e/cases/InstructorCourseEnrollPageE2ETest.java | 1,406 | // verify students in database | line_comment | nl | package teammates.e2e.cases;
import org.testng.annotations.Test;
import teammates.common.datatransfer.attributes.StudentAttributes;
import teammates.common.util.AppUrl;
import teammates.common.util.Const;
import teammates.e2e.pageobjects.InstructorCourseEnrollPage;
/**
* SUT: {@link Const.WebPageURIs#INSTRUCTOR_COURSE_ENROLL_PAGE}.
*/
public class InstructorCourseEnrollPageE2ETest extends BaseE2ETestCase {
@Override
protected void prepareTestData() {
testData = loadDataBundle("/InstructorCourseEnrollPageE2ETest.json");
removeAndRestoreDataBundle(testData);
sqlTestData = removeAndRestoreSqlDataBundle(
loadSqlDataBundle("/InstructorCourseEnrollPageE2ETest_SqlEntities.json"));
}
@Test
@Override
public void testAll() {
AppUrl url = createFrontendUrl(Const.WebPageURIs.INSTRUCTOR_COURSE_ENROLL_PAGE)
.withCourseId(testData.courses.get("ICEnroll.CS2104").getId());
InstructorCourseEnrollPage enrollPage = loginToPage(url, InstructorCourseEnrollPage.class,
testData.instructors.get("ICEnroll.teammates.test").getGoogleId());
______TS("Add rows to enroll spreadsheet");
int numRowsToAdd = 30;
enrollPage.addEnrollSpreadsheetRows(numRowsToAdd);
enrollPage.verifyNumAddedEnrollSpreadsheetRows(numRowsToAdd);
______TS("Enroll students to empty course");
StudentAttributes student1 = createCourseStudent("Section 1", "Team 1", "Alice Betsy",
"alice.b.tmms@gmail.tmt", "Comment for Alice");
StudentAttributes student2 = createCourseStudent("Section 1", "Team 1", "Benny Charles",
"benny.c.tmms@gmail.tmt", "Comment for Benny");
StudentAttributes student3 = createCourseStudent("Section 2", "Team 2", "Charlie Davis",
"charlie.d.tmms@gmail.tmt", "Comment for Charlie");
StudentAttributes[] studentsEnrollingToEmptyCourse = { student1, student2, student3 };
enrollPage.enroll(studentsEnrollingToEmptyCourse);
enrollPage.verifyStatusMessage("Enrollment successful. Summary given below.");
enrollPage.verifyResultsPanelContains(studentsEnrollingToEmptyCourse, null, null, null, null);
// refresh page to confirm enrollment
enrollPage = getNewPageInstance(url, InstructorCourseEnrollPage.class);
enrollPage.verifyExistingStudentsTableContains(studentsEnrollingToEmptyCourse);
// verify students in database
assertEquals(getStudent(student1), student1);
assertEquals(getStudent(student2), student2);
assertEquals(getStudent(student3), student3);
______TS("Enroll and modify students in existing course");
// modify team details of existing student
student3.setTeam("Team 3");
// add valid new student
StudentAttributes student4 = createCourseStudent("Section 2", "Team 2", "Danny Engrid",
"danny.e.tmms@gmail.tmt", "Comment for Danny");
// add new student with invalid email
StudentAttributes student5 = createCourseStudent("Section 2", "Team 2", "Invalid Student",
"invalid.email", "Comment for Invalid");
// student2 included to test modified without change table
StudentAttributes[] studentsEnrollingToExistingCourse = {student2, student3, student4, student5};
enrollPage.enroll(studentsEnrollingToExistingCourse);
enrollPage.verifyStatusMessage("Some students failed to be enrolled, see the summary below.");
StudentAttributes[] newStudentsData = {student4};
StudentAttributes[] modifiedStudentsData = {student3};
StudentAttributes[] modifiedWithoutChangeStudentsData = {student2};
StudentAttributes[] errorStudentsData = {student5};
StudentAttributes[] unmodifiedStudentsData = {student1};
enrollPage.verifyResultsPanelContains(newStudentsData, modifiedStudentsData, modifiedWithoutChangeStudentsData,
errorStudentsData, unmodifiedStudentsData);
// verify students<SUF>
assertEquals(getStudent(student1), student1);
assertEquals(getStudent(student2), student2);
assertEquals(getStudent(student3), student3);
assertEquals(getStudent(student4), student4);
assertNull(getStudent(student5));
// refresh page to confirm enrollment
enrollPage = getNewPageInstance(url, InstructorCourseEnrollPage.class);
StudentAttributes[] expectedExistingData = {student1, student2, student3, student4};
enrollPage.verifyExistingStudentsTableContains(expectedExistingData);
}
private StudentAttributes createCourseStudent(String section, String team, String name,
String email, String comments) {
return StudentAttributes.builder("tm.e2e.ICEnroll.CS2104", email)
.withName(name)
.withComment(comments)
.withTeamName(team)
.withSectionName(section)
.build();
}
}
| False | 1,068 | 5 | 1,201 | 5 | 1,202 | 5 | 1,201 | 5 | 1,416 | 5 | false | false | false | false | false | true |
4,109 | 11184_1 | package ss.week7.cmdline;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* Client class for a simple client-server application
* @author Theo Ruys
* @version 2005.02.21
*/
public class Client {
private static final String USAGE = "usage: java week4.cmdline.Client <name> <address> <port>";
/** Start een Client-applicatie op. */
public static void main(String[] args) {
if (args.length != 3) {
System.out.println(USAGE);
System.exit(0);
}
String name = args[0];
InetAddress addr = null;
int port = 0;
Socket sock = null;
// check args[1] - the IP-adress
try {
addr = InetAddress.getByName(args[1]);
} catch (UnknownHostException e) {
System.out.println(USAGE);
System.out.println("ERROR: host " + args[1] + " unknown");
System.exit(0);
}
// parse args[2] - the port
try {
port = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
System.out.println(USAGE);
System.out.println("ERROR: port " + args[2] + " is not an integer");
System.exit(0);
}
// try to open a Socket to the server
try {
sock = new Socket(addr, port);
} catch (IOException e) {
System.out.println("ERROR: could not create a socket on " + addr
+ " and port " + port);
}
// create Peer object and start the two-way communication
try {
Peer client = new Peer(name, sock);
Thread streamInputHandler = new Thread(client);
streamInputHandler.start();
client.handleTerminalInput();
System.out.println("komt ie heir?");
client.shutDown();
} catch (IOException e) {
e.printStackTrace();
}
}
} // end of class Client
| ramononis/project-rollit | weeky7/src/ss/week7/cmdline/Client.java | 568 | /** Start een Client-applicatie op. */ | block_comment | nl | package ss.week7.cmdline;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* Client class for a simple client-server application
* @author Theo Ruys
* @version 2005.02.21
*/
public class Client {
private static final String USAGE = "usage: java week4.cmdline.Client <name> <address> <port>";
/** Start een Client-applicatie<SUF>*/
public static void main(String[] args) {
if (args.length != 3) {
System.out.println(USAGE);
System.exit(0);
}
String name = args[0];
InetAddress addr = null;
int port = 0;
Socket sock = null;
// check args[1] - the IP-adress
try {
addr = InetAddress.getByName(args[1]);
} catch (UnknownHostException e) {
System.out.println(USAGE);
System.out.println("ERROR: host " + args[1] + " unknown");
System.exit(0);
}
// parse args[2] - the port
try {
port = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
System.out.println(USAGE);
System.out.println("ERROR: port " + args[2] + " is not an integer");
System.exit(0);
}
// try to open a Socket to the server
try {
sock = new Socket(addr, port);
} catch (IOException e) {
System.out.println("ERROR: could not create a socket on " + addr
+ " and port " + port);
}
// create Peer object and start the two-way communication
try {
Peer client = new Peer(name, sock);
Thread streamInputHandler = new Thread(client);
streamInputHandler.start();
client.handleTerminalInput();
System.out.println("komt ie heir?");
client.shutDown();
} catch (IOException e) {
e.printStackTrace();
}
}
} // end of class Client
| True | 461 | 10 | 550 | 10 | 537 | 11 | 550 | 10 | 637 | 11 | false | false | false | false | false | true |
2,253 | 147951_1 | package sets;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Martijn van der Bruggen (c) Hogeschool van Arnhem en Nijmegen
*
*/
public class Auto implements Comparable {
protected String eigenaar;
protected String kleur;
protected int pk;
Auto(String e, String k, int p) {
setEigenaar(e);
setKleur(k);
setPk(p);
}
public String getEigenaar() {
return eigenaar;
}
public void setEigenaar(String eigenaar) {
this.eigenaar = eigenaar;
}
public String getKleur() {
return kleur;
}
public void setKleur(String kleur) {
this.kleur = kleur;
}
/*public int compareTo(Object x) {
Auto a = (Auto) x;
if (a.getEigenaar().length() > this.getEigenaar().length()) {
return -1;
} else if (a.getEigenaar().length() < this.getEigenaar().length()) {
return +1;
} else {
return 0;
}
}
*/
public int compareTo(Object x) {
Auto a = (Auto) x;
if (a.getPk() < this.getPk()) {
return +1;
} else if (a.getPk() > this.getPk()) {
return -1;
} else {
return 0;
}
}
@Override
public int hashCode() {
int hash = 3;
hash = 83 * hash + (this.eigenaar != null ? this.eigenaar.hashCode() : 0);
hash = 83 * hash + (this.kleur != null ? this.kleur.hashCode() : 0);
hash = 83 * hash + this.pk;
return hash;
}
@Override
public boolean equals(Object o) {
return this.hashCode()==o.hashCode();
}
@Override
public String toString() {
return eigenaar + " " + kleur + " pks:" + Integer.toString(pk);
}
public int getPk() {
return pk;
}
public void setPk(int pk) {
this.pk = pk;
}
}
| bio-informatica/Bi6a | GitCode/src/sets/Auto.java | 638 | /**
*
* @author Martijn van der Bruggen (c) Hogeschool van Arnhem en Nijmegen
*
*/ | block_comment | nl | package sets;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Martijn van<SUF>*/
public class Auto implements Comparable {
protected String eigenaar;
protected String kleur;
protected int pk;
Auto(String e, String k, int p) {
setEigenaar(e);
setKleur(k);
setPk(p);
}
public String getEigenaar() {
return eigenaar;
}
public void setEigenaar(String eigenaar) {
this.eigenaar = eigenaar;
}
public String getKleur() {
return kleur;
}
public void setKleur(String kleur) {
this.kleur = kleur;
}
/*public int compareTo(Object x) {
Auto a = (Auto) x;
if (a.getEigenaar().length() > this.getEigenaar().length()) {
return -1;
} else if (a.getEigenaar().length() < this.getEigenaar().length()) {
return +1;
} else {
return 0;
}
}
*/
public int compareTo(Object x) {
Auto a = (Auto) x;
if (a.getPk() < this.getPk()) {
return +1;
} else if (a.getPk() > this.getPk()) {
return -1;
} else {
return 0;
}
}
@Override
public int hashCode() {
int hash = 3;
hash = 83 * hash + (this.eigenaar != null ? this.eigenaar.hashCode() : 0);
hash = 83 * hash + (this.kleur != null ? this.kleur.hashCode() : 0);
hash = 83 * hash + this.pk;
return hash;
}
@Override
public boolean equals(Object o) {
return this.hashCode()==o.hashCode();
}
@Override
public String toString() {
return eigenaar + " " + kleur + " pks:" + Integer.toString(pk);
}
public int getPk() {
return pk;
}
public void setPk(int pk) {
this.pk = pk;
}
}
| False | 505 | 30 | 553 | 34 | 590 | 27 | 553 | 34 | 648 | 32 | false | false | false | false | false | true |
4,168 | 163363_0 | package nl.itris.mjop.elements.catalog.elementen.entity;
import nl.itris.mjop.elements.catalog.handelingen.boundary.Handeling;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Element {
private Long id = null;
private String omschrijving = null;
private String code = null;
private String elementgroep = null;
private String levensduur = null;
private nl.itris.mjop.elements.catalog.elementen.boundary.Kostensoort stdkostensoort = null;
private Element hoofdelement = null;
private List<Handeling> handelingen = new ArrayList<Handeling>();
/**
**/
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
**/
public String getOmschrijving() {
return omschrijving;
}
public void setOmschrijving(String omschrijving) {
this.omschrijving = omschrijving;
}
/**
**/
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
/**
* Nieuwbouw
**/
public String getElementgroep() {
return elementgroep;
}
public void setElementgroep(String elementgroep) {
this.elementgroep = elementgroep;
}
/**
**/
public String getLevensduur() {
return levensduur;
}
public void setLevensduur(String levensduur) {
this.levensduur = levensduur;
}
/**
**/
public nl.itris.mjop.elements.catalog.elementen.boundary.Kostensoort getStdkostensoort() {
return stdkostensoort;
}
public void setStdkostensoort(nl.itris.mjop.elements.catalog.elementen.boundary.Kostensoort stdkostensoort) {
this.stdkostensoort = stdkostensoort;
}
/**
**/
public Element getHoofdelement() {
return hoofdelement;
}
public void setHoofdelement(Element hoofdelement) {
this.hoofdelement = hoofdelement;
}
/**
**/
public List<Handeling> getHandelingen() {
return handelingen;
}
public void setHandelingen(List<Handeling> handelingen) {
this.handelingen = handelingen;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Element element = (Element) o;
return Objects.equals(id, element.id) &&
Objects.equals(omschrijving, element.omschrijving) &&
Objects.equals(code, element.code) &&
Objects.equals(elementgroep, element.elementgroep) &&
Objects.equals(levensduur, element.levensduur) &&
Objects.equals(stdkostensoort, element.stdkostensoort) &&
Objects.equals(hoofdelement, element.hoofdelement) &&
Objects.equals(handelingen, element.handelingen);
}
@Override
public int hashCode() {
return Objects.hash(id, omschrijving, code, elementgroep, levensduur, stdkostensoort, hoofdelement, handelingen);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Element {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" omschrijving: ").append(toIndentedString(omschrijving)).append("\n");
sb.append(" code: ").append(toIndentedString(code)).append("\n");
sb.append(" elementgroep: ").append(toIndentedString(elementgroep)).append("\n");
sb.append(" levensduur: ").append(toIndentedString(levensduur)).append("\n");
sb.append(" stdkostensoort: ").append(toIndentedString(stdkostensoort)).append("\n");
sb.append(" hoofdelement: ").append(toIndentedString(hoofdelement)).append("\n");
sb.append(" handelingen: ").append(toIndentedString(handelingen)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| rhuss/fabric8-maven-plugin-1 | src/main/java/nl/itris/mjop/elements/catalog/elementen/entity/Element.java | 1,354 | /**
* Nieuwbouw
**/ | block_comment | nl | package nl.itris.mjop.elements.catalog.elementen.entity;
import nl.itris.mjop.elements.catalog.handelingen.boundary.Handeling;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Element {
private Long id = null;
private String omschrijving = null;
private String code = null;
private String elementgroep = null;
private String levensduur = null;
private nl.itris.mjop.elements.catalog.elementen.boundary.Kostensoort stdkostensoort = null;
private Element hoofdelement = null;
private List<Handeling> handelingen = new ArrayList<Handeling>();
/**
**/
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
**/
public String getOmschrijving() {
return omschrijving;
}
public void setOmschrijving(String omschrijving) {
this.omschrijving = omschrijving;
}
/**
**/
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
/**
* Nieuwbouw
<SUF>*/
public String getElementgroep() {
return elementgroep;
}
public void setElementgroep(String elementgroep) {
this.elementgroep = elementgroep;
}
/**
**/
public String getLevensduur() {
return levensduur;
}
public void setLevensduur(String levensduur) {
this.levensduur = levensduur;
}
/**
**/
public nl.itris.mjop.elements.catalog.elementen.boundary.Kostensoort getStdkostensoort() {
return stdkostensoort;
}
public void setStdkostensoort(nl.itris.mjop.elements.catalog.elementen.boundary.Kostensoort stdkostensoort) {
this.stdkostensoort = stdkostensoort;
}
/**
**/
public Element getHoofdelement() {
return hoofdelement;
}
public void setHoofdelement(Element hoofdelement) {
this.hoofdelement = hoofdelement;
}
/**
**/
public List<Handeling> getHandelingen() {
return handelingen;
}
public void setHandelingen(List<Handeling> handelingen) {
this.handelingen = handelingen;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Element element = (Element) o;
return Objects.equals(id, element.id) &&
Objects.equals(omschrijving, element.omschrijving) &&
Objects.equals(code, element.code) &&
Objects.equals(elementgroep, element.elementgroep) &&
Objects.equals(levensduur, element.levensduur) &&
Objects.equals(stdkostensoort, element.stdkostensoort) &&
Objects.equals(hoofdelement, element.hoofdelement) &&
Objects.equals(handelingen, element.handelingen);
}
@Override
public int hashCode() {
return Objects.hash(id, omschrijving, code, elementgroep, levensduur, stdkostensoort, hoofdelement, handelingen);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Element {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" omschrijving: ").append(toIndentedString(omschrijving)).append("\n");
sb.append(" code: ").append(toIndentedString(code)).append("\n");
sb.append(" elementgroep: ").append(toIndentedString(elementgroep)).append("\n");
sb.append(" levensduur: ").append(toIndentedString(levensduur)).append("\n");
sb.append(" stdkostensoort: ").append(toIndentedString(stdkostensoort)).append("\n");
sb.append(" hoofdelement: ").append(toIndentedString(hoofdelement)).append("\n");
sb.append(" handelingen: ").append(toIndentedString(handelingen)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| False | 1,071 | 12 | 1,203 | 10 | 1,179 | 9 | 1,188 | 10 | 1,350 | 12 | false | false | false | false | false | true |
2,733 | 31689_7 | /*
* Copyright (C) 2013 FrankkieNL
*
* 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 nl.frankkie.ontp;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import org.apache.http.NameValuePair;
/**
* CUSTOM LOGGER
*
* Deze class zo gemaakt,
* dat hij zoveel mogelijk lijkt op het bestaande Log-systeem,
* en dat hij op dezelfde manier kan worden aangeroepen.
* Als je alle logs via deze class laat lopen,
* kan je makkelijk logging in en uit schakelen.
* Ook exceptions kan je hiermee printen mbv de writer.
* Voor later is het ook handig, (aanpasbaarheid)
* als voortaan de logs naar een file moeten of zo,
* hoef je niet alle logs in de app aan te passen,
* maar alleen deze class.
*
* Voorbeeld:
* normaal:
* Log.v("tag", "bericht");
* voortaan:
* CLog.v("bericht");
* @author Frankkie
*/
public class CLog extends OutputStream {
private ByteArrayOutputStream bos = new ByteArrayOutputStream();
public static String TAG = "CLog";
/**
* Minimum errorlevel om te worden gelogd.
* Waardes komen van android.util.Log.*;
*/
public static int errorLevel = Log.VERBOSE;
public static boolean shouldLog = true;
/**
* door deze printwriter kan je meteen zo doen:
* exception.printStackTrace(CLog.writer);
*/
public static PrintWriter writer = new PrintWriter(new CLog());
public CLog(Context c) {
setShouldLogByDebuggable(c);
}
public CLog(Context c, String tag) {
setShouldLogByDebuggable(c);
setTag(tag);
}
public static boolean checkDebuggable(Context c) {
return (0 != (c.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE));
}
public static void setShouldLog(boolean bool){
shouldLog = bool;
}
public static void setShouldLogByDebuggable(Context c) {
shouldLog = checkDebuggable(c);
}
public CLog() {
// le nothin'
}
public CLog(String tag) {
setTag(tag);
}
@Override
public void write(int b) throws IOException {
if (b == (int) '\n') {
String s = new String(this.bos.toByteArray());
CLog.v(TAG, s);
this.bos = new ByteArrayOutputStream();
} else {
this.bos.write(b);
}
}
public static void setTag(String s) {
TAG = s;
}
public static String getTag() {
return TAG;
}
/**
* print exceptions
* @param e
*/
public static void ex(Exception e) {
if (shouldLog) {
e.printStackTrace();
}
}
/**
* print exceptions
* @param e
*/
public static void exOLD(Exception e) {
if (shouldLog) {
e.printStackTrace(writer);
}
}
public static void e(String tag, String msg) {
if (shouldLog && errorLevel <= Log.ERROR) {
Log.e(tag, msg);
}
}
public static void d(String tag, String msg) {
if (shouldLog && errorLevel <= Log.DEBUG) {
Log.d(tag, msg);
}
}
public static void i(String tag, String msg) {
if (shouldLog && errorLevel <= Log.INFO) {
Log.i(tag, msg);
}
}
public static void v(String tag, String msg) {
if (shouldLog && errorLevel <= Log.VERBOSE) {
Log.v(tag, msg);
}
}
public static void w(String tag, String msg) {
if (shouldLog && errorLevel <= Log.WARN) {
Log.w(tag, msg);
}
}
public static void e(Object msg) {
e(TAG, msg.toString());
}
public static void d(Object msg) {
d(TAG, msg.toString());
}
public static void i(Object msg) {
i(TAG, msg.toString());
}
public static void v(Object msg) {
v(TAG, msg.toString());
}
public static void w(Object msg) {
w(TAG, msg.toString());
}
/**
* Print all parameter of List<NameValuePair>
* @param pairs the pairs to be printed
*/
public static void printNameValuePairs(List<NameValuePair> pairs) {
if (!shouldLog) {
return;
}
Iterator i = pairs.iterator();
while (i.hasNext()) {
NameValuePair p = (NameValuePair) i.next();
v(p.getName() + ":" + p.getValue());
}
}
/**
* Het sluiten van een dialog geeft veel te
* vaak een exception, waar we toch niets mee doen.
* @param d
*/
public static void dismissDialog(Dialog d) {
try {
d.dismiss();
} catch (Exception e) {
//./ignore
}
}
}
| frankkienl/NTP-Sync | src/nl/frankkie/ontp/CLog.java | 1,589 | /**
* Het sluiten van een dialog geeft veel te
* vaak een exception, waar we toch niets mee doen.
* @param d
*/ | block_comment | nl | /*
* Copyright (C) 2013 FrankkieNL
*
* 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 nl.frankkie.ontp;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import org.apache.http.NameValuePair;
/**
* CUSTOM LOGGER
*
* Deze class zo gemaakt,
* dat hij zoveel mogelijk lijkt op het bestaande Log-systeem,
* en dat hij op dezelfde manier kan worden aangeroepen.
* Als je alle logs via deze class laat lopen,
* kan je makkelijk logging in en uit schakelen.
* Ook exceptions kan je hiermee printen mbv de writer.
* Voor later is het ook handig, (aanpasbaarheid)
* als voortaan de logs naar een file moeten of zo,
* hoef je niet alle logs in de app aan te passen,
* maar alleen deze class.
*
* Voorbeeld:
* normaal:
* Log.v("tag", "bericht");
* voortaan:
* CLog.v("bericht");
* @author Frankkie
*/
public class CLog extends OutputStream {
private ByteArrayOutputStream bos = new ByteArrayOutputStream();
public static String TAG = "CLog";
/**
* Minimum errorlevel om te worden gelogd.
* Waardes komen van android.util.Log.*;
*/
public static int errorLevel = Log.VERBOSE;
public static boolean shouldLog = true;
/**
* door deze printwriter kan je meteen zo doen:
* exception.printStackTrace(CLog.writer);
*/
public static PrintWriter writer = new PrintWriter(new CLog());
public CLog(Context c) {
setShouldLogByDebuggable(c);
}
public CLog(Context c, String tag) {
setShouldLogByDebuggable(c);
setTag(tag);
}
public static boolean checkDebuggable(Context c) {
return (0 != (c.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE));
}
public static void setShouldLog(boolean bool){
shouldLog = bool;
}
public static void setShouldLogByDebuggable(Context c) {
shouldLog = checkDebuggable(c);
}
public CLog() {
// le nothin'
}
public CLog(String tag) {
setTag(tag);
}
@Override
public void write(int b) throws IOException {
if (b == (int) '\n') {
String s = new String(this.bos.toByteArray());
CLog.v(TAG, s);
this.bos = new ByteArrayOutputStream();
} else {
this.bos.write(b);
}
}
public static void setTag(String s) {
TAG = s;
}
public static String getTag() {
return TAG;
}
/**
* print exceptions
* @param e
*/
public static void ex(Exception e) {
if (shouldLog) {
e.printStackTrace();
}
}
/**
* print exceptions
* @param e
*/
public static void exOLD(Exception e) {
if (shouldLog) {
e.printStackTrace(writer);
}
}
public static void e(String tag, String msg) {
if (shouldLog && errorLevel <= Log.ERROR) {
Log.e(tag, msg);
}
}
public static void d(String tag, String msg) {
if (shouldLog && errorLevel <= Log.DEBUG) {
Log.d(tag, msg);
}
}
public static void i(String tag, String msg) {
if (shouldLog && errorLevel <= Log.INFO) {
Log.i(tag, msg);
}
}
public static void v(String tag, String msg) {
if (shouldLog && errorLevel <= Log.VERBOSE) {
Log.v(tag, msg);
}
}
public static void w(String tag, String msg) {
if (shouldLog && errorLevel <= Log.WARN) {
Log.w(tag, msg);
}
}
public static void e(Object msg) {
e(TAG, msg.toString());
}
public static void d(Object msg) {
d(TAG, msg.toString());
}
public static void i(Object msg) {
i(TAG, msg.toString());
}
public static void v(Object msg) {
v(TAG, msg.toString());
}
public static void w(Object msg) {
w(TAG, msg.toString());
}
/**
* Print all parameter of List<NameValuePair>
* @param pairs the pairs to be printed
*/
public static void printNameValuePairs(List<NameValuePair> pairs) {
if (!shouldLog) {
return;
}
Iterator i = pairs.iterator();
while (i.hasNext()) {
NameValuePair p = (NameValuePair) i.next();
v(p.getName() + ":" + p.getValue());
}
}
/**
* Het sluiten van<SUF>*/
public static void dismissDialog(Dialog d) {
try {
d.dismiss();
} catch (Exception e) {
//./ignore
}
}
}
| True | 1,263 | 37 | 1,430 | 41 | 1,511 | 36 | 1,430 | 41 | 1,641 | 43 | false | false | false | false | false | true |
4,245 | 28800_0 | package domain;
import persistence.Marshalling;
import javax.xml.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
public class Ring {
private String naam;
private String letter;
private int index;
@XmlElementWrapper(name = "Tijdslots")
@XmlElement(name = "Tijdslot")
private final List<Tijdslot> tijdslots;
@XmlIDREF
@XmlElementWrapper(name = "Disciplines")
@XmlElement(name = "Discipline")
private final HashSet<Discipline> disciplines;
public Ring(String ringNaam, String ringLetter, int ringIndex) {
naam = ringNaam;
letter = ringLetter;
index = ringIndex;
tijdslots = new ArrayList<>();
disciplines = new HashSet<>();
}
public Ring(){
this("Ring zonder naam " + Math.random(), "", 0);
}
public String getNaam() { return naam; }
public void setNaam(String naam) { this.naam = naam; }
public String getLetter() { return letter; }
public void setLetter(String letter) { this.letter = letter; }
@XmlID
@XmlAttribute(name = "id")
public String getRef() { return "R"+ index; }
public void setRef(String s) { this.index = Integer.parseInt(s.substring(1)); }
public int getRingIndex() { return index; }
public void setRingIndex(int ringIndex) { index = ringIndex; }
@XmlTransient
public List<Tijdslot> getTijdslots() {
return tijdslots;
}
@XmlTransient
public HashSet<Discipline> getDisciplines() { return disciplines;}
public void addDiscipline(Discipline discipline) {
disciplines.add(discipline);
//tijdslots voor ring maken als ze nog niet bestaan
if(tijdslots.size() == 0) {
for (int i = 0; i < Marshalling.TOTALETIJD; i = i + discipline.getDuur()) { //TODO: property van maken
Tijdslot tijdslot = new Tijdslot(i, discipline.getDuur(), this);
tijdslots.add(tijdslot);
}
}
}
public String getVerkorteNotatie() {
return naam
.replace("meisjes","")
.replace("jongens","")
.replace("gemengd","");
}
@Override
public String toString() { return naam + (letter != "" ? " " + letter : ""); }
@Override
public int hashCode() { return Objects.hash(getRingIndex()); }
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (o instanceof Ring) {
Ring other = (Ring) o;
return getRingIndex() == other.getRingIndex();
} else {
return false;
}
}
}
| samverstraete/klj-sf-planner | src/main/java/domain/Ring.java | 822 | //tijdslots voor ring maken als ze nog niet bestaan | line_comment | nl | package domain;
import persistence.Marshalling;
import javax.xml.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
public class Ring {
private String naam;
private String letter;
private int index;
@XmlElementWrapper(name = "Tijdslots")
@XmlElement(name = "Tijdslot")
private final List<Tijdslot> tijdslots;
@XmlIDREF
@XmlElementWrapper(name = "Disciplines")
@XmlElement(name = "Discipline")
private final HashSet<Discipline> disciplines;
public Ring(String ringNaam, String ringLetter, int ringIndex) {
naam = ringNaam;
letter = ringLetter;
index = ringIndex;
tijdslots = new ArrayList<>();
disciplines = new HashSet<>();
}
public Ring(){
this("Ring zonder naam " + Math.random(), "", 0);
}
public String getNaam() { return naam; }
public void setNaam(String naam) { this.naam = naam; }
public String getLetter() { return letter; }
public void setLetter(String letter) { this.letter = letter; }
@XmlID
@XmlAttribute(name = "id")
public String getRef() { return "R"+ index; }
public void setRef(String s) { this.index = Integer.parseInt(s.substring(1)); }
public int getRingIndex() { return index; }
public void setRingIndex(int ringIndex) { index = ringIndex; }
@XmlTransient
public List<Tijdslot> getTijdslots() {
return tijdslots;
}
@XmlTransient
public HashSet<Discipline> getDisciplines() { return disciplines;}
public void addDiscipline(Discipline discipline) {
disciplines.add(discipline);
//tijdslots voor<SUF>
if(tijdslots.size() == 0) {
for (int i = 0; i < Marshalling.TOTALETIJD; i = i + discipline.getDuur()) { //TODO: property van maken
Tijdslot tijdslot = new Tijdslot(i, discipline.getDuur(), this);
tijdslots.add(tijdslot);
}
}
}
public String getVerkorteNotatie() {
return naam
.replace("meisjes","")
.replace("jongens","")
.replace("gemengd","");
}
@Override
public String toString() { return naam + (letter != "" ? " " + letter : ""); }
@Override
public int hashCode() { return Objects.hash(getRingIndex()); }
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (o instanceof Ring) {
Ring other = (Ring) o;
return getRingIndex() == other.getRingIndex();
} else {
return false;
}
}
}
| True | 632 | 13 | 797 | 15 | 734 | 11 | 797 | 15 | 876 | 15 | false | false | false | false | false | true |
3,331 | 76544_1 | package iOS_screens;
import org.openqa.selenium.By;
import io.appium.java_client.MobileBy;
public interface Swimlane_Contents_Screen {
By movies_and_series_page_title = MobileBy.xpath("//XCUIElementTypeNavigationBar[@name=\"Movies & Series\"]");
By category = MobileBy.className("XCUIElementTypeCell");
By new_this_week_page_title = MobileBy.xpath("//*[@text='Nieuw deze week']");
By new_this_week_page_titleList = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[1]");
By new_this_week_page_titleList_tab = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[1]");
By movies_page_title =MobileBy.name("Movies");
By movies_page_titleList = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[2]");
By movies_page_titleList_tab = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[2]");
By series_page_title = MobileBy.name("series");
By series_page_titleList = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[3]");
By series_page_titleList_tab = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[3]");
By entertainment_page_title = By.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[4]");
By entertainment_page_title_tab = By.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[4]");
By swimlane_content_page_program_title = MobileBy.xpath("(//XCUIElementTypeStaticText[@name=\"Locked content\"])[8]");
By programs_in_series = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell");
By programs_in_movies = MobileBy.className("XCUIElementTypeCell");
By swimlane_content_page_close_button = MobileBy.AccessibilityId("Back");
By top_films =MobileBy.name("top films");
// By episode_subtitle1 = MobileBy.AccessibilityId("S01 E01");
By episode_subtitle = MobileBy.xpath("//*[contains(@name,\"S01 E01\")]");
By svod_icon_locked = By.id("be.belgacom.mobile.tveverywhere:id/imageview_icon_locked");
By view_all = By.xpath("//*[@text='All']");
// By entertainment_page_title = By.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[4]");
By image_view =By.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell/XCUIElementTypeOther/XCUIElementTypeImage");
// By movies_page_title = MobileBy.xpath("//*[@text='Movies']");
// By category = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell");
// By series_page_title = MobileBy.xpath("//*[@text='series']");
// By svod_icon_age = By.id("be.belgacom.mobile.tveverywhere:id/imageview_icon_age");
// By non_playable_icon = MobileBy.id("be.belgacom.mobile.tveverywhere:id/view_overlay_not_playable");
// By top_films = MobileBy.xpath("//XCUIElementTypeNavigationBar[@name=\"top films\"]");
// By programs_in_movies = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell");
By pickx_mix_page_title = MobileBy.xpath("//XCUIElementTypeNavigationBar[@name='Pickx Mix']");
By pickx_pix_entertainment_page_title = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[1]");
By kids_page_title = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[2]");
By inhoud_per_zender_page_title = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[3]");
By documentaires_page_title = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[4]");
By muziek_page_title = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[5]");
By sport_title = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[6]");
}
| karmohan/Pickx_MobileAPP | src/main/java/iOS_screens/Swimlane_Contents_Screen.java | 3,061 | //*[@text='Nieuw deze week']"); | line_comment | nl | package iOS_screens;
import org.openqa.selenium.By;
import io.appium.java_client.MobileBy;
public interface Swimlane_Contents_Screen {
By movies_and_series_page_title = MobileBy.xpath("//XCUIElementTypeNavigationBar[@name=\"Movies & Series\"]");
By category = MobileBy.className("XCUIElementTypeCell");
By new_this_week_page_title = MobileBy.xpath("//*[@text='Nieuw deze<SUF>
By new_this_week_page_titleList = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[1]");
By new_this_week_page_titleList_tab = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[1]");
By movies_page_title =MobileBy.name("Movies");
By movies_page_titleList = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[2]");
By movies_page_titleList_tab = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[2]");
By series_page_title = MobileBy.name("series");
By series_page_titleList = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[3]");
By series_page_titleList_tab = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[3]");
By entertainment_page_title = By.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[4]");
By entertainment_page_title_tab = By.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[4]");
By swimlane_content_page_program_title = MobileBy.xpath("(//XCUIElementTypeStaticText[@name=\"Locked content\"])[8]");
By programs_in_series = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell");
By programs_in_movies = MobileBy.className("XCUIElementTypeCell");
By swimlane_content_page_close_button = MobileBy.AccessibilityId("Back");
By top_films =MobileBy.name("top films");
// By episode_subtitle1 = MobileBy.AccessibilityId("S01 E01");
By episode_subtitle = MobileBy.xpath("//*[contains(@name,\"S01 E01\")]");
By svod_icon_locked = By.id("be.belgacom.mobile.tveverywhere:id/imageview_icon_locked");
By view_all = By.xpath("//*[@text='All']");
// By entertainment_page_title = By.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[4]");
By image_view =By.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell/XCUIElementTypeOther/XCUIElementTypeImage");
// By movies_page_title = MobileBy.xpath("//*[@text='Movies']");
// By category = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell");
// By series_page_title = MobileBy.xpath("//*[@text='series']");
// By svod_icon_age = By.id("be.belgacom.mobile.tveverywhere:id/imageview_icon_age");
// By non_playable_icon = MobileBy.id("be.belgacom.mobile.tveverywhere:id/view_overlay_not_playable");
// By top_films = MobileBy.xpath("//XCUIElementTypeNavigationBar[@name=\"top films\"]");
// By programs_in_movies = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell");
By pickx_mix_page_title = MobileBy.xpath("//XCUIElementTypeNavigationBar[@name='Pickx Mix']");
By pickx_pix_entertainment_page_title = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[1]");
By kids_page_title = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[2]");
By inhoud_per_zender_page_title = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[3]");
By documentaires_page_title = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[4]");
By muziek_page_title = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[5]");
By sport_title = MobileBy.xpath("//XCUIElementTypeApplication[@name=\"Proximus Pickx\"]/XCUIElementTypeWindow/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeCollectionView/XCUIElementTypeCell[6]");
}
| False | 2,145 | 10 | 2,341 | 11 | 2,601 | 8 | 2,341 | 11 | 2,979 | 12 | false | false | false | false | false | true |
3,090 | 174_2 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.roleobject;
import java.lang.reflect.InvocationTargetException;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Possible roles.
*/
public enum Role {
BORROWER(BorrowerRole.class), INVESTOR(InvestorRole.class);
private final Class<? extends CustomerRole> typeCst;
Role(Class<? extends CustomerRole> typeCst) {
this.typeCst = typeCst;
}
private static final Logger logger = LoggerFactory.getLogger(Role.class);
/**
* Get instance.
*/
@SuppressWarnings("unchecked")
public <T extends CustomerRole> Optional<T> instance() {
var typeCst = this.typeCst;
try {
return (Optional<T>) Optional.of(typeCst.getDeclaredConstructor().newInstance());
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
logger.error("error creating an object", e);
}
return Optional.empty();
}
} | iluwatar/java-design-patterns | role-object/src/main/java/com/iluwatar/roleobject/Role.java | 659 | /**
* Get instance.
*/ | block_comment | nl | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.roleobject;
import java.lang.reflect.InvocationTargetException;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Possible roles.
*/
public enum Role {
BORROWER(BorrowerRole.class), INVESTOR(InvestorRole.class);
private final Class<? extends CustomerRole> typeCst;
Role(Class<? extends CustomerRole> typeCst) {
this.typeCst = typeCst;
}
private static final Logger logger = LoggerFactory.getLogger(Role.class);
/**
* Get instance.
<SUF>*/
@SuppressWarnings("unchecked")
public <T extends CustomerRole> Optional<T> instance() {
var typeCst = this.typeCst;
try {
return (Optional<T>) Optional.of(typeCst.getDeclaredConstructor().newInstance());
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
logger.error("error creating an object", e);
}
return Optional.empty();
}
} | False | 494 | 8 | 549 | 8 | 567 | 10 | 549 | 8 | 722 | 10 | false | false | false | false | false | true |
2,325 | 133480_39 | // Targeted by JavaCPP version 1.5.10: DO NOT EDIT THIS FILE
package org.bytedeco.bullet.LinearMath;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import static org.bytedeco.bullet.global.LinearMath.*;
// #else
// #endif //BT_USE_DOUBLE_PRECISION
// #if defined BT_USE_SSE
// #endif
// #ifdef BT_USE_NEON
// #endif
/**\brief btVector3 can be used to represent 3D points and vectors.
* It has an un-used w component to suit 16-byte alignment when btVector3 is stored in containers. This extra component can be used by derived classes (Quaternion?) or by user
* Ideally, this class should be replaced by a platform optimized SIMD version that keeps the data in registers
*/
@NoOffset @Properties(inherit = org.bytedeco.bullet.presets.LinearMath.class)
public class btVector3 extends Pointer {
static { Loader.load(); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public btVector3(Pointer p) { super(p); }
/** Native array allocator. Access with {@link Pointer#position(long)}. */
public btVector3(long size) { super((Pointer)null); allocateArray(size); }
private native void allocateArray(long size);
@Override public btVector3 position(long position) {
return (btVector3)super.position(position);
}
@Override public btVector3 getPointer(long i) {
return new btVector3((Pointer)this).offsetAddress(i);
}
// #if defined(__SPU__) && defined(__CELLOS_LV2__)
// #else //__CELLOS_LV2__ __SPU__
// #if defined(BT_USE_SSE) || defined(BT_USE_NEON) // _WIN32 || ARM
// #else
public native @Cast("btScalar") double m_floats(int i); public native btVector3 m_floats(int i, double setter);
@MemberGetter public native @Cast("btScalar*") DoublePointer m_floats();
/**\brief No initialization constructor */
public btVector3() { super((Pointer)null); allocate(); }
private native void allocate();
/**\brief Constructor from scalars
* @param x X value
* @param y Y value
* @param z Z value
*/
public btVector3(@Cast("const btScalar") double _x, @Cast("const btScalar") double _y, @Cast("const btScalar") double _z) { super((Pointer)null); allocate(_x, _y, _z); }
private native void allocate(@Cast("const btScalar") double _x, @Cast("const btScalar") double _y, @Cast("const btScalar") double _z);
// #if (defined(BT_USE_SSE_IN_API) && defined(BT_USE_SSE)) || defined(BT_USE_NEON)
// #endif // #if defined (BT_USE_SSE_IN_API) || defined (BT_USE_NEON)
/**\brief Add a vector to this one
* @param The vector to add to this one */
public native @ByRef @Name("operator +=") btVector3 addPut(@Const @ByRef btVector3 v);
/**\brief Subtract a vector from this one
* @param The vector to subtract */
public native @ByRef @Name("operator -=") btVector3 subtractPut(@Const @ByRef btVector3 v);
/**\brief Scale the vector
* @param s Scale factor */
public native @ByRef @Name("operator *=") btVector3 multiplyPut(@Cast("const btScalar") double s);
/**\brief Inversely scale the vector
* @param s Scale factor to divide by */
public native @ByRef @Name("operator /=") btVector3 dividePut(@Cast("const btScalar") double s);
/**\brief Return the dot product
* @param v The other vector in the dot product */
public native @Cast("btScalar") double dot(@Const @ByRef btVector3 v);
/**\brief Return the length of the vector squared */
public native @Cast("btScalar") double length2();
/**\brief Return the length of the vector */
public native @Cast("btScalar") double length();
/**\brief Return the norm (length) of the vector */
public native @Cast("btScalar") double norm();
/**\brief Return the norm (length) of the vector */
public native @Cast("btScalar") double safeNorm();
/**\brief Return the distance squared between the ends of this and another vector
* This is symantically treating the vector like a point */
public native @Cast("btScalar") double distance2(@Const @ByRef btVector3 v);
/**\brief Return the distance between the ends of this and another vector
* This is symantically treating the vector like a point */
public native @Cast("btScalar") double distance(@Const @ByRef btVector3 v);
public native @ByRef btVector3 safeNormalize();
/**\brief Normalize this vector
* x^2 + y^2 + z^2 = 1 */
public native @ByRef btVector3 normalize();
/**\brief Return a normalized version of this vector */
public native @ByVal btVector3 normalized();
/**\brief Return a rotated version of this vector
* @param wAxis The axis to rotate about
* @param angle The angle to rotate by */
public native @ByVal btVector3 rotate(@Const @ByRef btVector3 wAxis, @Cast("const btScalar") double angle);
/**\brief Return the angle between this and another vector
* @param v The other vector */
public native @Cast("btScalar") double angle(@Const @ByRef btVector3 v);
/**\brief Return a vector with the absolute values of each element */
public native @ByVal btVector3 absolute();
/**\brief Return the cross product between this and another vector
* @param v The other vector */
public native @ByVal btVector3 cross(@Const @ByRef btVector3 v);
public native @Cast("btScalar") double triple(@Const @ByRef btVector3 v1, @Const @ByRef btVector3 v2);
/**\brief Return the axis with the smallest value
* Note return values are 0,1,2 for x, y, or z */
public native int minAxis();
/**\brief Return the axis with the largest value
* Note return values are 0,1,2 for x, y, or z */
public native int maxAxis();
public native int furthestAxis();
public native int closestAxis();
public native void setInterpolate3(@Const @ByRef btVector3 v0, @Const @ByRef btVector3 v1, @Cast("btScalar") double rt);
/**\brief Return the linear interpolation between this and another vector
* @param v The other vector
* @param t The ration of this to v (t = 0 => return this, t=1 => return other) */
public native @ByVal btVector3 lerp(@Const @ByRef btVector3 v, @Cast("const btScalar") double t);
/**\brief Elementwise multiply this vector by the other
* @param v The other vector */
public native @ByRef @Name("operator *=") btVector3 multiplyPut(@Const @ByRef btVector3 v);
/**\brief Return the x value */
public native @Cast("const btScalar") double getX();
/**\brief Return the y value */
public native @Cast("const btScalar") double getY();
/**\brief Return the z value */
public native @Cast("const btScalar") double getZ();
/**\brief Set the x value */
public native void setX(@Cast("btScalar") double _x);
/**\brief Set the y value */
public native void setY(@Cast("btScalar") double _y);
/**\brief Set the z value */
public native void setZ(@Cast("btScalar") double _z);
/**\brief Set the w value */
public native void setW(@Cast("btScalar") double _w);
/**\brief Return the x value */
public native @Cast("const btScalar") double x();
/**\brief Return the y value */
public native @Cast("const btScalar") double y();
/**\brief Return the z value */
public native @Cast("const btScalar") double z();
/**\brief Return the w value */
public native @Cast("const btScalar") double w();
//SIMD_FORCE_INLINE btScalar& operator[](int i) { return (&m_floats[0])[i]; }
//SIMD_FORCE_INLINE const btScalar& operator[](int i) const { return (&m_floats[0])[i]; }
/**operator btScalar*() replaces operator[], using implicit conversion. We added operator != and operator == to avoid pointer comparisons. */
public native @Cast("btScalar*") @Name("operator btScalar*") DoublePointer asDoublePointer();
public native @Cast("bool") @Name("operator ==") boolean equals(@Const @ByRef btVector3 other);
public native @Cast("bool") @Name("operator !=") boolean notEquals(@Const @ByRef btVector3 other);
/**\brief Set each element to the max of the current values and the values of another btVector3
* @param other The other btVector3 to compare with
*/
public native void setMax(@Const @ByRef btVector3 other);
/**\brief Set each element to the min of the current values and the values of another btVector3
* @param other The other btVector3 to compare with
*/
public native void setMin(@Const @ByRef btVector3 other);
public native void setValue(@Cast("const btScalar") double _x, @Cast("const btScalar") double _y, @Cast("const btScalar") double _z);
public native void getSkewSymmetricMatrix(btVector3 v0, btVector3 v1, btVector3 v2);
public native void setZero();
public native @Cast("bool") boolean isZero();
public native @Cast("bool") boolean fuzzyZero();
public native void serialize(@ByRef btVector3DoubleData dataOut);
public native void deSerialize(@Const @ByRef btVector3DoubleData dataIn);
public native void deSerialize(@Const @ByRef btVector3FloatData dataIn);
public native void serializeFloat(@ByRef btVector3FloatData dataOut);
public native void deSerializeFloat(@Const @ByRef btVector3FloatData dataIn);
public native void serializeDouble(@ByRef btVector3DoubleData dataOut);
public native void deSerializeDouble(@Const @ByRef btVector3DoubleData dataIn);
/**\brief returns index of maximum dot product between this and vectors in array[]
* @param array The other vectors
* @param array_count The number of other vectors
* @param dotOut The maximum dot product */
public native long maxDot(@Const btVector3 array, long array_count, @Cast("btScalar*") @ByRef DoublePointer dotOut);
public native long maxDot(@Const btVector3 array, long array_count, @Cast("btScalar*") @ByRef DoubleBuffer dotOut);
public native long maxDot(@Const btVector3 array, long array_count, @Cast("btScalar*") @ByRef double[] dotOut);
/**\brief returns index of minimum dot product between this and vectors in array[]
* @param array The other vectors
* @param array_count The number of other vectors
* @param dotOut The minimum dot product */
public native long minDot(@Const btVector3 array, long array_count, @Cast("btScalar*") @ByRef DoublePointer dotOut);
public native long minDot(@Const btVector3 array, long array_count, @Cast("btScalar*") @ByRef DoubleBuffer dotOut);
public native long minDot(@Const btVector3 array, long array_count, @Cast("btScalar*") @ByRef double[] dotOut);
/* create a vector as btVector3( this->dot( btVector3 v0 ), this->dot( btVector3 v1), this->dot( btVector3 v2 )) */
public native @ByVal btVector3 dot3(@Const @ByRef btVector3 v0, @Const @ByRef btVector3 v1, @Const @ByRef btVector3 v2);
}
| bytedeco/javacpp-presets | bullet/src/gen/java/org/bytedeco/bullet/LinearMath/btVector3.java | 3,263 | /**\brief Set the z value */ | block_comment | nl | // Targeted by JavaCPP version 1.5.10: DO NOT EDIT THIS FILE
package org.bytedeco.bullet.LinearMath;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import static org.bytedeco.bullet.global.LinearMath.*;
// #else
// #endif //BT_USE_DOUBLE_PRECISION
// #if defined BT_USE_SSE
// #endif
// #ifdef BT_USE_NEON
// #endif
/**\brief btVector3 can be used to represent 3D points and vectors.
* It has an un-used w component to suit 16-byte alignment when btVector3 is stored in containers. This extra component can be used by derived classes (Quaternion?) or by user
* Ideally, this class should be replaced by a platform optimized SIMD version that keeps the data in registers
*/
@NoOffset @Properties(inherit = org.bytedeco.bullet.presets.LinearMath.class)
public class btVector3 extends Pointer {
static { Loader.load(); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public btVector3(Pointer p) { super(p); }
/** Native array allocator. Access with {@link Pointer#position(long)}. */
public btVector3(long size) { super((Pointer)null); allocateArray(size); }
private native void allocateArray(long size);
@Override public btVector3 position(long position) {
return (btVector3)super.position(position);
}
@Override public btVector3 getPointer(long i) {
return new btVector3((Pointer)this).offsetAddress(i);
}
// #if defined(__SPU__) && defined(__CELLOS_LV2__)
// #else //__CELLOS_LV2__ __SPU__
// #if defined(BT_USE_SSE) || defined(BT_USE_NEON) // _WIN32 || ARM
// #else
public native @Cast("btScalar") double m_floats(int i); public native btVector3 m_floats(int i, double setter);
@MemberGetter public native @Cast("btScalar*") DoublePointer m_floats();
/**\brief No initialization constructor */
public btVector3() { super((Pointer)null); allocate(); }
private native void allocate();
/**\brief Constructor from scalars
* @param x X value
* @param y Y value
* @param z Z value
*/
public btVector3(@Cast("const btScalar") double _x, @Cast("const btScalar") double _y, @Cast("const btScalar") double _z) { super((Pointer)null); allocate(_x, _y, _z); }
private native void allocate(@Cast("const btScalar") double _x, @Cast("const btScalar") double _y, @Cast("const btScalar") double _z);
// #if (defined(BT_USE_SSE_IN_API) && defined(BT_USE_SSE)) || defined(BT_USE_NEON)
// #endif // #if defined (BT_USE_SSE_IN_API) || defined (BT_USE_NEON)
/**\brief Add a vector to this one
* @param The vector to add to this one */
public native @ByRef @Name("operator +=") btVector3 addPut(@Const @ByRef btVector3 v);
/**\brief Subtract a vector from this one
* @param The vector to subtract */
public native @ByRef @Name("operator -=") btVector3 subtractPut(@Const @ByRef btVector3 v);
/**\brief Scale the vector
* @param s Scale factor */
public native @ByRef @Name("operator *=") btVector3 multiplyPut(@Cast("const btScalar") double s);
/**\brief Inversely scale the vector
* @param s Scale factor to divide by */
public native @ByRef @Name("operator /=") btVector3 dividePut(@Cast("const btScalar") double s);
/**\brief Return the dot product
* @param v The other vector in the dot product */
public native @Cast("btScalar") double dot(@Const @ByRef btVector3 v);
/**\brief Return the length of the vector squared */
public native @Cast("btScalar") double length2();
/**\brief Return the length of the vector */
public native @Cast("btScalar") double length();
/**\brief Return the norm (length) of the vector */
public native @Cast("btScalar") double norm();
/**\brief Return the norm (length) of the vector */
public native @Cast("btScalar") double safeNorm();
/**\brief Return the distance squared between the ends of this and another vector
* This is symantically treating the vector like a point */
public native @Cast("btScalar") double distance2(@Const @ByRef btVector3 v);
/**\brief Return the distance between the ends of this and another vector
* This is symantically treating the vector like a point */
public native @Cast("btScalar") double distance(@Const @ByRef btVector3 v);
public native @ByRef btVector3 safeNormalize();
/**\brief Normalize this vector
* x^2 + y^2 + z^2 = 1 */
public native @ByRef btVector3 normalize();
/**\brief Return a normalized version of this vector */
public native @ByVal btVector3 normalized();
/**\brief Return a rotated version of this vector
* @param wAxis The axis to rotate about
* @param angle The angle to rotate by */
public native @ByVal btVector3 rotate(@Const @ByRef btVector3 wAxis, @Cast("const btScalar") double angle);
/**\brief Return the angle between this and another vector
* @param v The other vector */
public native @Cast("btScalar") double angle(@Const @ByRef btVector3 v);
/**\brief Return a vector with the absolute values of each element */
public native @ByVal btVector3 absolute();
/**\brief Return the cross product between this and another vector
* @param v The other vector */
public native @ByVal btVector3 cross(@Const @ByRef btVector3 v);
public native @Cast("btScalar") double triple(@Const @ByRef btVector3 v1, @Const @ByRef btVector3 v2);
/**\brief Return the axis with the smallest value
* Note return values are 0,1,2 for x, y, or z */
public native int minAxis();
/**\brief Return the axis with the largest value
* Note return values are 0,1,2 for x, y, or z */
public native int maxAxis();
public native int furthestAxis();
public native int closestAxis();
public native void setInterpolate3(@Const @ByRef btVector3 v0, @Const @ByRef btVector3 v1, @Cast("btScalar") double rt);
/**\brief Return the linear interpolation between this and another vector
* @param v The other vector
* @param t The ration of this to v (t = 0 => return this, t=1 => return other) */
public native @ByVal btVector3 lerp(@Const @ByRef btVector3 v, @Cast("const btScalar") double t);
/**\brief Elementwise multiply this vector by the other
* @param v The other vector */
public native @ByRef @Name("operator *=") btVector3 multiplyPut(@Const @ByRef btVector3 v);
/**\brief Return the x value */
public native @Cast("const btScalar") double getX();
/**\brief Return the y value */
public native @Cast("const btScalar") double getY();
/**\brief Return the z value */
public native @Cast("const btScalar") double getZ();
/**\brief Set the x value */
public native void setX(@Cast("btScalar") double _x);
/**\brief Set the y value */
public native void setY(@Cast("btScalar") double _y);
/**\brief Set the<SUF>*/
public native void setZ(@Cast("btScalar") double _z);
/**\brief Set the w value */
public native void setW(@Cast("btScalar") double _w);
/**\brief Return the x value */
public native @Cast("const btScalar") double x();
/**\brief Return the y value */
public native @Cast("const btScalar") double y();
/**\brief Return the z value */
public native @Cast("const btScalar") double z();
/**\brief Return the w value */
public native @Cast("const btScalar") double w();
//SIMD_FORCE_INLINE btScalar& operator[](int i) { return (&m_floats[0])[i]; }
//SIMD_FORCE_INLINE const btScalar& operator[](int i) const { return (&m_floats[0])[i]; }
/**operator btScalar*() replaces operator[], using implicit conversion. We added operator != and operator == to avoid pointer comparisons. */
public native @Cast("btScalar*") @Name("operator btScalar*") DoublePointer asDoublePointer();
public native @Cast("bool") @Name("operator ==") boolean equals(@Const @ByRef btVector3 other);
public native @Cast("bool") @Name("operator !=") boolean notEquals(@Const @ByRef btVector3 other);
/**\brief Set each element to the max of the current values and the values of another btVector3
* @param other The other btVector3 to compare with
*/
public native void setMax(@Const @ByRef btVector3 other);
/**\brief Set each element to the min of the current values and the values of another btVector3
* @param other The other btVector3 to compare with
*/
public native void setMin(@Const @ByRef btVector3 other);
public native void setValue(@Cast("const btScalar") double _x, @Cast("const btScalar") double _y, @Cast("const btScalar") double _z);
public native void getSkewSymmetricMatrix(btVector3 v0, btVector3 v1, btVector3 v2);
public native void setZero();
public native @Cast("bool") boolean isZero();
public native @Cast("bool") boolean fuzzyZero();
public native void serialize(@ByRef btVector3DoubleData dataOut);
public native void deSerialize(@Const @ByRef btVector3DoubleData dataIn);
public native void deSerialize(@Const @ByRef btVector3FloatData dataIn);
public native void serializeFloat(@ByRef btVector3FloatData dataOut);
public native void deSerializeFloat(@Const @ByRef btVector3FloatData dataIn);
public native void serializeDouble(@ByRef btVector3DoubleData dataOut);
public native void deSerializeDouble(@Const @ByRef btVector3DoubleData dataIn);
/**\brief returns index of maximum dot product between this and vectors in array[]
* @param array The other vectors
* @param array_count The number of other vectors
* @param dotOut The maximum dot product */
public native long maxDot(@Const btVector3 array, long array_count, @Cast("btScalar*") @ByRef DoublePointer dotOut);
public native long maxDot(@Const btVector3 array, long array_count, @Cast("btScalar*") @ByRef DoubleBuffer dotOut);
public native long maxDot(@Const btVector3 array, long array_count, @Cast("btScalar*") @ByRef double[] dotOut);
/**\brief returns index of minimum dot product between this and vectors in array[]
* @param array The other vectors
* @param array_count The number of other vectors
* @param dotOut The minimum dot product */
public native long minDot(@Const btVector3 array, long array_count, @Cast("btScalar*") @ByRef DoublePointer dotOut);
public native long minDot(@Const btVector3 array, long array_count, @Cast("btScalar*") @ByRef DoubleBuffer dotOut);
public native long minDot(@Const btVector3 array, long array_count, @Cast("btScalar*") @ByRef double[] dotOut);
/* create a vector as btVector3( this->dot( btVector3 v0 ), this->dot( btVector3 v1), this->dot( btVector3 v2 )) */
public native @ByVal btVector3 dot3(@Const @ByRef btVector3 v0, @Const @ByRef btVector3 v1, @Const @ByRef btVector3 v2);
}
| False | 2,734 | 8 | 2,967 | 8 | 3,011 | 8 | 2,967 | 8 | 3,378 | 9 | false | false | false | false | false | true |
12 | 28346_9 | package org.firstinspires.ftc.teamcode.autonomousroutes;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import org.firstinspires.ftc.teamcode.autonomousclasses.BezierCurveRoute;
import org.firstinspires.ftc.teamcode.robots.CompetitionRobot;
/** Comment to make the program disappear from the driverstation app. */
@Autonomous
public class RedStart1VisionPushParkB extends LinearOpMode {
private final boolean BLUE_SIDE = false;
private final boolean SKIP_VISION = false;
private BezierCurveRoute case0;
private BezierCurveRoute case2;
private BezierCurveRoute case0ParkB;
private BezierCurveRoute case1ParkB;
private BezierCurveRoute case2ParkB;
private CompetitionRobot robot;
private void initAutonomous() {
robot = new CompetitionRobot(this);
case0 = new BezierCurveRoute(
new double[] {-134.835833333334, 221.373750000001, -150.769166666667, 36.0989583333336}, //The x-coefficients
new double[] {-5.57666666666569, 65.7249999999985, 155.350000000001, -151.1675}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
case2 = new BezierCurveRoute(
new double[] {6.37333333333339, -11.9500000000003, -27.0866666666663, 52.9783333333332}, //The x-coefficients
new double[] {195.98, -169.69, 7.96666666666653, 29.4766666666668}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
case0ParkB= new BezierCurveRoute(
new double[] {-12.1989583333324, -1351.993125, 7146.846875, -15288.7802083333, 15483.615, -7288.35479166666, 1574.16354166666}, //The x-coefficients
new double[] {-408.490833333334, 2329.6525, -6601.37916666666, 14366.8875, -18804.52, 12077.6658333333, -2888.51416666666}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
case1ParkB = new BezierCurveRoute(
new double[] {-525.252291666667, 2972.711875, -8830.303125, 15647.778125, -17231.9, 10713.1252083333, -2509.54979166667}, //The x-coefficients
new double[] {73.8908333333343, -798.857500000003, 4133.70416666667, -7758.53750000001, 6842.57000000001, -2920.77916666668, 490.945833333336}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
case2ParkB = new BezierCurveRoute(
new double[] {-525.252291666667, 2972.711875, -8830.303125, 15647.778125, -17231.9, 10713.1252083333, -2509.54979166667}, //The x-coefficients
new double[] {73.8908333333343, -798.857500000003, 4133.70416666667, -7758.53750000001, 6842.57000000001, -2920.77916666668, 490.945833333336}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
}
@Override
public void runOpMode() {
int markerPosition = 1;
initAutonomous();
robot.grabber.grab();
sleep(1000);
// TODO: Hier 1 functie van maken.
while (!isStarted() && !isStopRequested()) {
markerPosition = robot.webcam.getMarkerPosition(BLUE_SIDE);
// result
telemetry.addData("Position", markerPosition);
telemetry.update();
}
// Jeroen denkt dat dit niet nodig is.
waitForStart();
// Choose default option if skip.
if (SKIP_VISION) {
markerPosition = 1;
}
switch (markerPosition) {
case 0: // LEFT
leftPixelPlacement();
return;
case 2: // RIGHT
rightPixelPlacement();
return;
default: // Default MIDDLE
middlePixelPlacement();
return;
}
}
private void middlePixelPlacement() {
robot.arm.AutoArmToBoardPosition();
sleep(1000);
robot.tiltMechanism.TiltMechanismStartPosition();
sleep(200);
//Push pixel naar de middelste streep.
robot.drivetrain.driveStraight(65, 0.4);
sleep(200);
robot.pusher.release();
sleep(200);
robot.tiltMechanism.TiltMechanismDown();
//Rij een stuk naar achter zodat de pixel niet meer onder de robot ligt.
robot.drivetrain.driveStraight(-25, 0.4);
//Rij naar de backstage en parkeer.
case1ParkB.executeWithPointSkip();
robot.drivetrain.driveStraight(-5, 0.4);
}
private void rightPixelPlacement() {
robot.arm.AutoArmToBoardPosition();
sleep(1000);
robot.drivetrain.driveStraight(45, 0.4);
robot.drivetrain.turnRobotAO(45);
robot.drivetrain.driveStraight(20, 0.4);
sleep(200);
robot.pusher.release();
sleep(200);
robot.drivetrain.driveStraight(-20, 0.4);
robot.drivetrain.turnRobotAO(0);
robot.drivetrain.driveStraight(10, 0.4);
//Rij naar de backstage en parkeer.
case2ParkB.executeWithPointSkip();
robot.drivetrain.driveStraight(-5, 0.4);
}
private void leftPixelPlacement() {
robot.arm.AutoArmToBoardPosition();
sleep(1000);
robot.tiltMechanism.TiltMechanismStartPosition();
sleep(200);
//Push pixel naar de linker streep.
case0.executeWithPointSkip();
sleep(200);
robot.pusher.release();
sleep(200);
//Rij een stuk naar achter zodat de pixel niet meer onder de robot ligt.
robot.drivetrain.driveStraight(-10, 0.4);
robot.tiltMechanism.TiltMechanismDown();
//Rij naar de backstage en parkeer.
case0ParkB.executeWithPointSkip();
robot.drivetrain.driveStraight(-5, 0.4);
}
} | 16788-TheEncryptedGentlemen/FtcRobotController | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/autonomousroutes/RedStart1VisionPushParkB.java | 2,111 | //Push pixel naar de middelste streep. | line_comment | nl | package org.firstinspires.ftc.teamcode.autonomousroutes;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import org.firstinspires.ftc.teamcode.autonomousclasses.BezierCurveRoute;
import org.firstinspires.ftc.teamcode.robots.CompetitionRobot;
/** Comment to make the program disappear from the driverstation app. */
@Autonomous
public class RedStart1VisionPushParkB extends LinearOpMode {
private final boolean BLUE_SIDE = false;
private final boolean SKIP_VISION = false;
private BezierCurveRoute case0;
private BezierCurveRoute case2;
private BezierCurveRoute case0ParkB;
private BezierCurveRoute case1ParkB;
private BezierCurveRoute case2ParkB;
private CompetitionRobot robot;
private void initAutonomous() {
robot = new CompetitionRobot(this);
case0 = new BezierCurveRoute(
new double[] {-134.835833333334, 221.373750000001, -150.769166666667, 36.0989583333336}, //The x-coefficients
new double[] {-5.57666666666569, 65.7249999999985, 155.350000000001, -151.1675}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
case2 = new BezierCurveRoute(
new double[] {6.37333333333339, -11.9500000000003, -27.0866666666663, 52.9783333333332}, //The x-coefficients
new double[] {195.98, -169.69, 7.96666666666653, 29.4766666666668}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
case0ParkB= new BezierCurveRoute(
new double[] {-12.1989583333324, -1351.993125, 7146.846875, -15288.7802083333, 15483.615, -7288.35479166666, 1574.16354166666}, //The x-coefficients
new double[] {-408.490833333334, 2329.6525, -6601.37916666666, 14366.8875, -18804.52, 12077.6658333333, -2888.51416666666}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
case1ParkB = new BezierCurveRoute(
new double[] {-525.252291666667, 2972.711875, -8830.303125, 15647.778125, -17231.9, 10713.1252083333, -2509.54979166667}, //The x-coefficients
new double[] {73.8908333333343, -798.857500000003, 4133.70416666667, -7758.53750000001, 6842.57000000001, -2920.77916666668, 490.945833333336}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
case2ParkB = new BezierCurveRoute(
new double[] {-525.252291666667, 2972.711875, -8830.303125, 15647.778125, -17231.9, 10713.1252083333, -2509.54979166667}, //The x-coefficients
new double[] {73.8908333333343, -798.857500000003, 4133.70416666667, -7758.53750000001, 6842.57000000001, -2920.77916666668, 490.945833333336}, //The y-coefficients
robot,
0.4,
BezierCurveRoute.DRIVE_METHOD.STRAFE, //STRAFE or FOLLOW
this
);
}
@Override
public void runOpMode() {
int markerPosition = 1;
initAutonomous();
robot.grabber.grab();
sleep(1000);
// TODO: Hier 1 functie van maken.
while (!isStarted() && !isStopRequested()) {
markerPosition = robot.webcam.getMarkerPosition(BLUE_SIDE);
// result
telemetry.addData("Position", markerPosition);
telemetry.update();
}
// Jeroen denkt dat dit niet nodig is.
waitForStart();
// Choose default option if skip.
if (SKIP_VISION) {
markerPosition = 1;
}
switch (markerPosition) {
case 0: // LEFT
leftPixelPlacement();
return;
case 2: // RIGHT
rightPixelPlacement();
return;
default: // Default MIDDLE
middlePixelPlacement();
return;
}
}
private void middlePixelPlacement() {
robot.arm.AutoArmToBoardPosition();
sleep(1000);
robot.tiltMechanism.TiltMechanismStartPosition();
sleep(200);
//Push pixel<SUF>
robot.drivetrain.driveStraight(65, 0.4);
sleep(200);
robot.pusher.release();
sleep(200);
robot.tiltMechanism.TiltMechanismDown();
//Rij een stuk naar achter zodat de pixel niet meer onder de robot ligt.
robot.drivetrain.driveStraight(-25, 0.4);
//Rij naar de backstage en parkeer.
case1ParkB.executeWithPointSkip();
robot.drivetrain.driveStraight(-5, 0.4);
}
private void rightPixelPlacement() {
robot.arm.AutoArmToBoardPosition();
sleep(1000);
robot.drivetrain.driveStraight(45, 0.4);
robot.drivetrain.turnRobotAO(45);
robot.drivetrain.driveStraight(20, 0.4);
sleep(200);
robot.pusher.release();
sleep(200);
robot.drivetrain.driveStraight(-20, 0.4);
robot.drivetrain.turnRobotAO(0);
robot.drivetrain.driveStraight(10, 0.4);
//Rij naar de backstage en parkeer.
case2ParkB.executeWithPointSkip();
robot.drivetrain.driveStraight(-5, 0.4);
}
private void leftPixelPlacement() {
robot.arm.AutoArmToBoardPosition();
sleep(1000);
robot.tiltMechanism.TiltMechanismStartPosition();
sleep(200);
//Push pixel naar de linker streep.
case0.executeWithPointSkip();
sleep(200);
robot.pusher.release();
sleep(200);
//Rij een stuk naar achter zodat de pixel niet meer onder de robot ligt.
robot.drivetrain.driveStraight(-10, 0.4);
robot.tiltMechanism.TiltMechanismDown();
//Rij naar de backstage en parkeer.
case0ParkB.executeWithPointSkip();
robot.drivetrain.driveStraight(-5, 0.4);
}
} | True | 2,193 | 11 | 2,259 | 12 | 2,296 | 10 | 2,259 | 12 | 2,576 | 13 | false | false | false | false | false | true |
2,565 | 166310_0 | package com.fokkenrood.antlr;_x000D_
_x000D_
import java.util.Calendar;_x000D_
_x000D_
import com.fokkenrood.antlr.ProfielSpraakParser.ObjectContext;_x000D_
import com.fokkenrood.antlr.ProfielSpraakParser.RegelContext;_x000D_
_x000D_
_x000D_
public class AangifteDroolsListener extends ProfielSpraakBaseListener {_x000D_
private Calendar TODAY = Calendar.getInstance();_x000D_
private String regel = "Regel";_x000D_
private String regelset = "Regelset";_x000D_
private StringBuilder drlWhen = new StringBuilder();_x000D_
private StringBuilder drlThen = new StringBuilder();_x000D_
_x000D_
// CONSTRUCTOR:_x000D_
public AangifteDroolsListener() {_x000D_
TODAY.set(2017, 1, 16); // Datum voor digitaal Tijdreizen: YYYY, (MM=0-11), (DD=1-31)_x000D_
} // end constructor_x000D_
_x000D_
// GET-er:_x000D_
public String getDRL() {_x000D_
return (drlWhen.toString() + drlThen.toString());_x000D_
}_x000D_
_x000D_
_x000D_
@Override_x000D_
public void enterRegel(RegelContext ctx) {_x000D_
drlWhen.setLength(0);_x000D_
drlWhen.append("package ");_x000D_
drlWhen.append(regelset);_x000D_
drlWhen.append("\n\n");_x000D_
drlWhen.append("import com.fokkenrood.drools.Aangifte;\n\n");_x000D_
drlWhen.append("rule \"");_x000D_
drlWhen.append(regel);_x000D_
drlWhen.append("\"\n");_x000D_
drlWhen.append(" when\n");_x000D_
drlThen.setLength(0);_x000D_
drlThen.append("\n )\n");_x000D_
drlThen.append(" then\n");_x000D_
} // end enterRegel_x000D_
_x000D_
_x000D_
@Override_x000D_
public void exitRegel(RegelContext ctx) {_x000D_
drlThen.append(" $aangifte.setScore(\"");_x000D_
drlThen.append(ctx.w.getText());_x000D_
drlThen.append("\");\n");_x000D_
drlThen.append("end\n");_x000D_
} // end exitRegel_x000D_
_x000D_
_x000D_
@Override_x000D_
public void exitObject(ObjectContext ctx) {_x000D_
drlWhen.append(drlWhen.indexOf("$aangifte") < 1 ? " $aangifte : Aangifte(\n" : ",\n");_x000D_
if (ctx.w1 != null) {_x000D_
drlWhen.append(" ");_x000D_
drlWhen.append(ctx.f.signifier);_x000D_
drlWhen.append(" ");_x000D_
drlWhen.append(ctx.v.operator);_x000D_
drlWhen.append(" ");_x000D_
drlWhen.append(ctx.w1.value);_x000D_
} // end if_x000D_
if (ctx.w2 != null) {_x000D_
drlWhen.append(" ");_x000D_
drlWhen.append(ctx.f.signifier);_x000D_
drlWhen.append((ctx.not != null ? " not" : ""));_x000D_
drlWhen.append(" matches \".*(");_x000D_
drlWhen.append(ctx.w2.getText());_x000D_
drlWhen.append(").*\"");_x000D_
} // end if_x000D_
} // end exitObject_x000D_
_x000D_
_x000D_
} // end class_x000D_
| discipl/act-native | backend/src/main/java/com/fokkenrood/antlr/AangifteDroolsListener.java | 873 | // Datum voor digitaal Tijdreizen: YYYY, (MM=0-11), (DD=1-31)_x000D_ | line_comment | nl | package com.fokkenrood.antlr;_x000D_
_x000D_
import java.util.Calendar;_x000D_
_x000D_
import com.fokkenrood.antlr.ProfielSpraakParser.ObjectContext;_x000D_
import com.fokkenrood.antlr.ProfielSpraakParser.RegelContext;_x000D_
_x000D_
_x000D_
public class AangifteDroolsListener extends ProfielSpraakBaseListener {_x000D_
private Calendar TODAY = Calendar.getInstance();_x000D_
private String regel = "Regel";_x000D_
private String regelset = "Regelset";_x000D_
private StringBuilder drlWhen = new StringBuilder();_x000D_
private StringBuilder drlThen = new StringBuilder();_x000D_
_x000D_
// CONSTRUCTOR:_x000D_
public AangifteDroolsListener() {_x000D_
TODAY.set(2017, 1, 16); // Datum voor<SUF>
} // end constructor_x000D_
_x000D_
// GET-er:_x000D_
public String getDRL() {_x000D_
return (drlWhen.toString() + drlThen.toString());_x000D_
}_x000D_
_x000D_
_x000D_
@Override_x000D_
public void enterRegel(RegelContext ctx) {_x000D_
drlWhen.setLength(0);_x000D_
drlWhen.append("package ");_x000D_
drlWhen.append(regelset);_x000D_
drlWhen.append("\n\n");_x000D_
drlWhen.append("import com.fokkenrood.drools.Aangifte;\n\n");_x000D_
drlWhen.append("rule \"");_x000D_
drlWhen.append(regel);_x000D_
drlWhen.append("\"\n");_x000D_
drlWhen.append(" when\n");_x000D_
drlThen.setLength(0);_x000D_
drlThen.append("\n )\n");_x000D_
drlThen.append(" then\n");_x000D_
} // end enterRegel_x000D_
_x000D_
_x000D_
@Override_x000D_
public void exitRegel(RegelContext ctx) {_x000D_
drlThen.append(" $aangifte.setScore(\"");_x000D_
drlThen.append(ctx.w.getText());_x000D_
drlThen.append("\");\n");_x000D_
drlThen.append("end\n");_x000D_
} // end exitRegel_x000D_
_x000D_
_x000D_
@Override_x000D_
public void exitObject(ObjectContext ctx) {_x000D_
drlWhen.append(drlWhen.indexOf("$aangifte") < 1 ? " $aangifte : Aangifte(\n" : ",\n");_x000D_
if (ctx.w1 != null) {_x000D_
drlWhen.append(" ");_x000D_
drlWhen.append(ctx.f.signifier);_x000D_
drlWhen.append(" ");_x000D_
drlWhen.append(ctx.v.operator);_x000D_
drlWhen.append(" ");_x000D_
drlWhen.append(ctx.w1.value);_x000D_
} // end if_x000D_
if (ctx.w2 != null) {_x000D_
drlWhen.append(" ");_x000D_
drlWhen.append(ctx.f.signifier);_x000D_
drlWhen.append((ctx.not != null ? " not" : ""));_x000D_
drlWhen.append(" matches \".*(");_x000D_
drlWhen.append(ctx.w2.getText());_x000D_
drlWhen.append(").*\"");_x000D_
} // end if_x000D_
} // end exitObject_x000D_
_x000D_
_x000D_
} // end class_x000D_
| True | 1,151 | 35 | 1,337 | 36 | 1,290 | 33 | 1,337 | 36 | 1,421 | 38 | false | false | false | false | false | true |
2,960 | 112978_0 | package nl.novi.javaprogrammeren;
import nl.novi.javaprogrammeren.overerving.Rocket;
public class Main {
/*
Bekijk onderstaande code. Er zijn twee klasse, twee objecten.
ApolloRocket extends Rocket.
De ApolloRocket is speciaal. Wanneer deze geïnstantieerd wordt, moeten we ook het aantal motoren meegeven. Pas de
constructor aan.
Maak vervolgens in deze klasse een ApolloRocket object aan en roep de toString()-methode aan.
*/
public static void main(String[] args) {
Rocket genericRocket = new Rocket(100);
genericRocket.fly(10);
System.out.println(genericRocket.toString());
}
}
| hogeschoolnovi/SD-BE-JP-Overerving-01b | src/nl/novi/javaprogrammeren/Main.java | 206 | /*
Bekijk onderstaande code. Er zijn twee klasse, twee objecten.
ApolloRocket extends Rocket.
De ApolloRocket is speciaal. Wanneer deze geïnstantieerd wordt, moeten we ook het aantal motoren meegeven. Pas de
constructor aan.
Maak vervolgens in deze klasse een ApolloRocket object aan en roep de toString()-methode aan.
*/ | block_comment | nl | package nl.novi.javaprogrammeren;
import nl.novi.javaprogrammeren.overerving.Rocket;
public class Main {
/*
Bekijk onderstaande code.<SUF>*/
public static void main(String[] args) {
Rocket genericRocket = new Rocket(100);
genericRocket.fly(10);
System.out.println(genericRocket.toString());
}
}
| True | 162 | 90 | 185 | 97 | 169 | 82 | 185 | 97 | 217 | 110 | false | false | false | false | false | true |
206 | 22196_13 | package nl.noscope.emeraldextraction.objects;_x000D_
_x000D_
import android.util.Log;_x000D_
import nl.saxion.act.playground.model.GameBoard;_x000D_
import nl.saxion.act.playground.model.GameObject;_x000D_
_x000D_
/**_x000D_
* De miner is ons speler object, deze verplaatst zich dan ook steeds_x000D_
* _x000D_
* @author Boyd_x000D_
*/_x000D_
public class Miner extends GameObject {_x000D_
public static final String MINER_IMAGE = "miner";_x000D_
public static final String MINER_UP = "up";_x000D_
public static final String MINER_DOWN = "down";_x000D_
public static final String MINER_LEFT = "links";_x000D_
public static final String MINER_RIGHT = "rechts";_x000D_
_x000D_
int position = 0;_x000D_
_x000D_
_x000D_
/** Returns the ImageId of the image to show. */_x000D_
@Override_x000D_
public String getImageId() {_x000D_
if (position == 1) {_x000D_
return MINER_LEFT; _x000D_
} else if (position == 2) {_x000D_
return MINER_RIGHT; _x000D_
} else if (position == 3) {_x000D_
return MINER_UP; _x000D_
} else if (position == 4) {_x000D_
return MINER_DOWN; _x000D_
} else {_x000D_
return MINER_IMAGE;_x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
public void walkLeft(GameBoard gameBoard) {_x000D_
_x000D_
position = 1;_x000D_
_x000D_
int newPosX = getPositionX() - 1;_x000D_
int newPosY = getPositionY();_x000D_
_x000D_
StateCheck(newPosX, newPosY, gameBoard, position);_x000D_
_x000D_
}_x000D_
_x000D_
public void walkRight(GameBoard gameBoard) {_x000D_
_x000D_
position = 2;_x000D_
_x000D_
int newPosX = getPositionX() + 1;_x000D_
int newPosY = getPositionY();_x000D_
StateCheck(newPosX, newPosY, gameBoard, position);_x000D_
}_x000D_
_x000D_
public void walkUp(GameBoard gameBoard) {_x000D_
_x000D_
position = 3;_x000D_
_x000D_
int newPosX = getPositionX();_x000D_
int newPosY = getPositionY() - 1;_x000D_
_x000D_
StateCheck(newPosX, newPosY, gameBoard, position);_x000D_
}_x000D_
_x000D_
public void walkDown(GameBoard gameBoard) {_x000D_
_x000D_
position = 4;_x000D_
_x000D_
int newPosX = getPositionX();_x000D_
int newPosY = getPositionY() + 1;_x000D_
_x000D_
StateCheck(newPosX, newPosY, gameBoard, position);_x000D_
_x000D_
}_x000D_
_x000D_
private void StateCheck(int newPosX, int newPosY, GameBoard gameBoard, int direction) {_x000D_
// Als de nieuwe positie naast het bord is doet hij niks_x000D_
if (newPosX >= gameBoard.getWidth() - 1 || newPosX == 0) {_x000D_
return;_x000D_
} else if (newPosY >= gameBoard.getHeight() - 1 || newPosY == 0){_x000D_
return;_x000D_
}_x000D_
_x000D_
// Kijk of er een object is op het nieuwe punt_x000D_
GameObject objectAtNewPos = gameBoard.getObject(newPosX, newPosY);_x000D_
if (objectAtNewPos != null) {_x000D_
_x000D_
// Miner kan niet door een aantal objecten heen_x000D_
if (objectAtNewPos instanceof Stone) {_x000D_
return;_x000D_
}_x000D_
if (objectAtNewPos instanceof Iron) {_x000D_
return;_x000D_
}_x000D_
if (objectAtNewPos instanceof Minecart) {_x000D_
return;_x000D_
}_x000D_
_x000D_
if (objectAtNewPos instanceof Emerald) {_x000D_
// Je kan een emerald niet naar beneden drukken_x000D_
if (direction == 4) { return; }_x000D_
// Duw de emerald omhoog als er vrije ruimte boven is_x000D_
if (direction == 3) {_x000D_
if (gameBoard.getObject(newPosX, newPosY - 1) == null) {_x000D_
gameBoard.moveObject(objectAtNewPos, newPosX, newPosY - 1);_x000D_
}_x000D_
else { return; }_x000D_
}_x000D_
// Duw de emerald naar links als er vrije ruimte links van de emerald is_x000D_
if (direction == 1) {_x000D_
if (gameBoard.getObject(newPosX - 1, newPosY) == null) {_x000D_
gameBoard.moveObject(objectAtNewPos, newPosX -1, newPosY);_x000D_
}_x000D_
else { return; }_x000D_
}_x000D_
// Duw de emerald naar rechts als er vrije ruimte rechts van de emerald is_x000D_
if (direction == 2) {_x000D_
if (gameBoard.getObject(newPosX + 1, newPosY) == null) {_x000D_
gameBoard.moveObject(objectAtNewPos, newPosX + 1, newPosY);_x000D_
}_x000D_
else { return ; }_x000D_
}_x000D_
}_x000D_
if (objectAtNewPos instanceof StoneMove) {_x000D_
// Je kan een emerald niet naar beneden drukken_x000D_
if (direction == 4) { return; }_x000D_
// Duw de emerald omhoog als er vrije ruimte boven is_x000D_
if (direction == 3) {_x000D_
if (gameBoard.getObject(newPosX, newPosY - 1) == null) {_x000D_
gameBoard.moveObject(objectAtNewPos, newPosX, newPosY - 1);_x000D_
}_x000D_
else { return; }_x000D_
}_x000D_
// Duw de emerald naar links als er vrije ruimte links van de emerald is_x000D_
if (direction == 1) {_x000D_
if (gameBoard.getObject(newPosX - 1, newPosY) == null) {_x000D_
gameBoard.moveObject(objectAtNewPos, newPosX -1, newPosY);_x000D_
}_x000D_
else { return; }_x000D_
}_x000D_
// Duw de emerald naar rechts als er vrije ruimte rechts van de emerald is_x000D_
if (direction == 2) {_x000D_
if (gameBoard.getObject(newPosX + 1, newPosY) == null) {_x000D_
gameBoard.moveObject(objectAtNewPos, newPosX + 1, newPosY);_x000D_
}_x000D_
else { return ; }_x000D_
}_x000D_
}_x000D_
_x000D_
if (objectAtNewPos instanceof Sand) {_x000D_
gameBoard.removeObject(objectAtNewPos);_x000D_
_x000D_
}_x000D_
}_x000D_
_x000D_
// Verplaats de miner naar zijn nieuwe positie_x000D_
//Log.d("Miner", "Ik verplaats nu de miner");_x000D_
gameBoard.moveObject(this, newPosX, newPosY);_x000D_
//gameBoard.updateView();_x000D_
Log.d("Miner", "Miner verplaatst");_x000D_
_x000D_
}_x000D_
_x000D_
@Override_x000D_
public void onTouched(GameBoard gameBoard) {_x000D_
// TODO Auto-generated method stub_x000D_
_x000D_
}_x000D_
}_x000D_
| Bernardez/Speelveld | src/nl/noscope/emeraldextraction/objects/Miner.java | 1,801 | // Verplaats de miner naar zijn nieuwe positie_x000D_ | line_comment | nl | package nl.noscope.emeraldextraction.objects;_x000D_
_x000D_
import android.util.Log;_x000D_
import nl.saxion.act.playground.model.GameBoard;_x000D_
import nl.saxion.act.playground.model.GameObject;_x000D_
_x000D_
/**_x000D_
* De miner is ons speler object, deze verplaatst zich dan ook steeds_x000D_
* _x000D_
* @author Boyd_x000D_
*/_x000D_
public class Miner extends GameObject {_x000D_
public static final String MINER_IMAGE = "miner";_x000D_
public static final String MINER_UP = "up";_x000D_
public static final String MINER_DOWN = "down";_x000D_
public static final String MINER_LEFT = "links";_x000D_
public static final String MINER_RIGHT = "rechts";_x000D_
_x000D_
int position = 0;_x000D_
_x000D_
_x000D_
/** Returns the ImageId of the image to show. */_x000D_
@Override_x000D_
public String getImageId() {_x000D_
if (position == 1) {_x000D_
return MINER_LEFT; _x000D_
} else if (position == 2) {_x000D_
return MINER_RIGHT; _x000D_
} else if (position == 3) {_x000D_
return MINER_UP; _x000D_
} else if (position == 4) {_x000D_
return MINER_DOWN; _x000D_
} else {_x000D_
return MINER_IMAGE;_x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
public void walkLeft(GameBoard gameBoard) {_x000D_
_x000D_
position = 1;_x000D_
_x000D_
int newPosX = getPositionX() - 1;_x000D_
int newPosY = getPositionY();_x000D_
_x000D_
StateCheck(newPosX, newPosY, gameBoard, position);_x000D_
_x000D_
}_x000D_
_x000D_
public void walkRight(GameBoard gameBoard) {_x000D_
_x000D_
position = 2;_x000D_
_x000D_
int newPosX = getPositionX() + 1;_x000D_
int newPosY = getPositionY();_x000D_
StateCheck(newPosX, newPosY, gameBoard, position);_x000D_
}_x000D_
_x000D_
public void walkUp(GameBoard gameBoard) {_x000D_
_x000D_
position = 3;_x000D_
_x000D_
int newPosX = getPositionX();_x000D_
int newPosY = getPositionY() - 1;_x000D_
_x000D_
StateCheck(newPosX, newPosY, gameBoard, position);_x000D_
}_x000D_
_x000D_
public void walkDown(GameBoard gameBoard) {_x000D_
_x000D_
position = 4;_x000D_
_x000D_
int newPosX = getPositionX();_x000D_
int newPosY = getPositionY() + 1;_x000D_
_x000D_
StateCheck(newPosX, newPosY, gameBoard, position);_x000D_
_x000D_
}_x000D_
_x000D_
private void StateCheck(int newPosX, int newPosY, GameBoard gameBoard, int direction) {_x000D_
// Als de nieuwe positie naast het bord is doet hij niks_x000D_
if (newPosX >= gameBoard.getWidth() - 1 || newPosX == 0) {_x000D_
return;_x000D_
} else if (newPosY >= gameBoard.getHeight() - 1 || newPosY == 0){_x000D_
return;_x000D_
}_x000D_
_x000D_
// Kijk of er een object is op het nieuwe punt_x000D_
GameObject objectAtNewPos = gameBoard.getObject(newPosX, newPosY);_x000D_
if (objectAtNewPos != null) {_x000D_
_x000D_
// Miner kan niet door een aantal objecten heen_x000D_
if (objectAtNewPos instanceof Stone) {_x000D_
return;_x000D_
}_x000D_
if (objectAtNewPos instanceof Iron) {_x000D_
return;_x000D_
}_x000D_
if (objectAtNewPos instanceof Minecart) {_x000D_
return;_x000D_
}_x000D_
_x000D_
if (objectAtNewPos instanceof Emerald) {_x000D_
// Je kan een emerald niet naar beneden drukken_x000D_
if (direction == 4) { return; }_x000D_
// Duw de emerald omhoog als er vrije ruimte boven is_x000D_
if (direction == 3) {_x000D_
if (gameBoard.getObject(newPosX, newPosY - 1) == null) {_x000D_
gameBoard.moveObject(objectAtNewPos, newPosX, newPosY - 1);_x000D_
}_x000D_
else { return; }_x000D_
}_x000D_
// Duw de emerald naar links als er vrije ruimte links van de emerald is_x000D_
if (direction == 1) {_x000D_
if (gameBoard.getObject(newPosX - 1, newPosY) == null) {_x000D_
gameBoard.moveObject(objectAtNewPos, newPosX -1, newPosY);_x000D_
}_x000D_
else { return; }_x000D_
}_x000D_
// Duw de emerald naar rechts als er vrije ruimte rechts van de emerald is_x000D_
if (direction == 2) {_x000D_
if (gameBoard.getObject(newPosX + 1, newPosY) == null) {_x000D_
gameBoard.moveObject(objectAtNewPos, newPosX + 1, newPosY);_x000D_
}_x000D_
else { return ; }_x000D_
}_x000D_
}_x000D_
if (objectAtNewPos instanceof StoneMove) {_x000D_
// Je kan een emerald niet naar beneden drukken_x000D_
if (direction == 4) { return; }_x000D_
// Duw de emerald omhoog als er vrije ruimte boven is_x000D_
if (direction == 3) {_x000D_
if (gameBoard.getObject(newPosX, newPosY - 1) == null) {_x000D_
gameBoard.moveObject(objectAtNewPos, newPosX, newPosY - 1);_x000D_
}_x000D_
else { return; }_x000D_
}_x000D_
// Duw de emerald naar links als er vrije ruimte links van de emerald is_x000D_
if (direction == 1) {_x000D_
if (gameBoard.getObject(newPosX - 1, newPosY) == null) {_x000D_
gameBoard.moveObject(objectAtNewPos, newPosX -1, newPosY);_x000D_
}_x000D_
else { return; }_x000D_
}_x000D_
// Duw de emerald naar rechts als er vrije ruimte rechts van de emerald is_x000D_
if (direction == 2) {_x000D_
if (gameBoard.getObject(newPosX + 1, newPosY) == null) {_x000D_
gameBoard.moveObject(objectAtNewPos, newPosX + 1, newPosY);_x000D_
}_x000D_
else { return ; }_x000D_
}_x000D_
}_x000D_
_x000D_
if (objectAtNewPos instanceof Sand) {_x000D_
gameBoard.removeObject(objectAtNewPos);_x000D_
_x000D_
}_x000D_
}_x000D_
_x000D_
// Verplaats de<SUF>
//Log.d("Miner", "Ik verplaats nu de miner");_x000D_
gameBoard.moveObject(this, newPosX, newPosY);_x000D_
//gameBoard.updateView();_x000D_
Log.d("Miner", "Miner verplaatst");_x000D_
_x000D_
}_x000D_
_x000D_
@Override_x000D_
public void onTouched(GameBoard gameBoard) {_x000D_
// TODO Auto-generated method stub_x000D_
_x000D_
}_x000D_
}_x000D_
| True | 2,472 | 17 | 2,817 | 21 | 2,674 | 17 | 2,817 | 21 | 3,136 | 19 | false | false | false | false | false | true |
1,401 | 72767_14 |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
*
* @author R. Springer
*/
public class MyWorld extends World {
private CollisionEngine ce;
/**
* Constructor for objects of class MyWorld.
*
*/
public MyWorld() {
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(1000, 800, 1, false);
int[][] map = {
{17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,},
{16,16,16,16,16,16,16,16,16,16,16,16,17,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,},
{17,16,17,16,17,17,17,17,17,17,17,16,17,16,17,17,17,16,17,17,17,17,17,17,17,17,16,16,16,17,},
{17,16,17,16,16,16,16,16,16,16,17,16,17,16,16,16,17,16,17,16,16,16,16,16,16,17,16,17,16,17,},
{17,16,17,16,17,17,17,17,17,16,17,16,17,16,17,17,17,16,17,17,17,17,17,16,16,17,16,17,16,17,},
{17,16,17,16,17,16,16,16,16,16,17,16,17,16,16,16,16,16,16,16,16,16,17,16,16,17,16,17,16,17,},
{17,16,17,16,17,17,17,17,17,17,17,16,17,17,17,17,17,17,17,17,16,16,17,16,17,17,16,17,16,17,},
{17,16,17,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,16,16,17,16,17,16,16,17,16,17,},
{17,16,17,16,17,17,17,17,17,17,17,17,17,16,16,16,17,16,16,17,16,16,17,16,17,16,17,17,16,17,},
{17,16,17,16,16,16,16,16,16,17,17,16,17,17,16,16,17,16,16,17,16,16,17,16,17,17,16,16,16,17,},
{17,16,17,17,17,17,17,17,16,16,16,16,16,16,16,16,17,16,16,17,16,16,17,16,16,16,16,17,16,17,},
{17,16,16,16,16,16,16,16,16,17,17,17,17,17,16,16,17,16,16,16,16,16,17,16,16,17,17,17,16,17,},
{17,16,17,17,17,17,17,16,16,17,17,16,16,17,16,17,17,17,17,17,16,16,17,17,16,16,17,17,16,17,},
{17,16,17,16,16,16,17,16,16,16,16,16,16,17,16,17,16,16,16,16,16,16,16,17,16,16,17,16,16,17,},
{17,16,17,16,16,16,17,16,16,17,17,17,17,17,16,17,16,17,17,17,17,17,16,17,16,16,17,17,17,17,},
{17,16,17,16,16,16,17,16,17,17,16,16,16,16,16,17,16,17,16,16,16,17,16,17,16,16,16,16,16,17,},
{17,16,17,16,16,16,17,16,17,16,17,17,16,17,16,17,16,16,17,16,16,17,16,16,17,17,17,16,16,17,},
{17,16,16,16,16,16,17,16,17,16,17,16,16,17,16,17,16,17,16,17,16,17,16,17,17,16,17,16,16,17,},
{17,16,17,17,17,17,17,16,17,16,17,16,16,17,16,17,17,16,16,17,16,17,16,16,16,16,17,16,16,17,},
{17,16,16,17,17,17,17,16,17,16,17,16,16,17,16,16,16,16,17,17,16,17,17,17,17,17,17,16,16,17,},
{17,17,16,16,16,16,17,17,17,16,16,16,16,17,17,17,17,16,17,16,16,17,16,16,16,16,17,16,16,17,},
{17,17,17,16,16,16,16,16,16,16,16,16,16,17,16,16,16,16,16,16,16,16,16,16,16,16,17,16,16,16,},
{17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,},
};
// Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen
TileEngine te = new TileEngine(this, 70, 70, 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();
Star star = new Star();
// 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, 30, 105);
addObject(new Letters('J'),385,385);
addObject(new Letters('U'),665,1155);
addObject(new Letters('M'),1085,245);
addObject(new Letters('P'),1925,945);
addObject(star, 245, 660);
//addObject(new Enemy(), 1170, 410);
// 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-Toni2000 | MyWorld.java | 2,095 | // Toevoegen van de mover instantie of een extentie hiervan | line_comment | nl |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
*
* @author R. Springer
*/
public class MyWorld extends World {
private CollisionEngine ce;
/**
* Constructor for objects of class MyWorld.
*
*/
public MyWorld() {
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(1000, 800, 1, false);
int[][] map = {
{17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,},
{16,16,16,16,16,16,16,16,16,16,16,16,17,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,},
{17,16,17,16,17,17,17,17,17,17,17,16,17,16,17,17,17,16,17,17,17,17,17,17,17,17,16,16,16,17,},
{17,16,17,16,16,16,16,16,16,16,17,16,17,16,16,16,17,16,17,16,16,16,16,16,16,17,16,17,16,17,},
{17,16,17,16,17,17,17,17,17,16,17,16,17,16,17,17,17,16,17,17,17,17,17,16,16,17,16,17,16,17,},
{17,16,17,16,17,16,16,16,16,16,17,16,17,16,16,16,16,16,16,16,16,16,17,16,16,17,16,17,16,17,},
{17,16,17,16,17,17,17,17,17,17,17,16,17,17,17,17,17,17,17,17,16,16,17,16,17,17,16,17,16,17,},
{17,16,17,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,16,16,17,16,17,16,16,17,16,17,},
{17,16,17,16,17,17,17,17,17,17,17,17,17,16,16,16,17,16,16,17,16,16,17,16,17,16,17,17,16,17,},
{17,16,17,16,16,16,16,16,16,17,17,16,17,17,16,16,17,16,16,17,16,16,17,16,17,17,16,16,16,17,},
{17,16,17,17,17,17,17,17,16,16,16,16,16,16,16,16,17,16,16,17,16,16,17,16,16,16,16,17,16,17,},
{17,16,16,16,16,16,16,16,16,17,17,17,17,17,16,16,17,16,16,16,16,16,17,16,16,17,17,17,16,17,},
{17,16,17,17,17,17,17,16,16,17,17,16,16,17,16,17,17,17,17,17,16,16,17,17,16,16,17,17,16,17,},
{17,16,17,16,16,16,17,16,16,16,16,16,16,17,16,17,16,16,16,16,16,16,16,17,16,16,17,16,16,17,},
{17,16,17,16,16,16,17,16,16,17,17,17,17,17,16,17,16,17,17,17,17,17,16,17,16,16,17,17,17,17,},
{17,16,17,16,16,16,17,16,17,17,16,16,16,16,16,17,16,17,16,16,16,17,16,17,16,16,16,16,16,17,},
{17,16,17,16,16,16,17,16,17,16,17,17,16,17,16,17,16,16,17,16,16,17,16,16,17,17,17,16,16,17,},
{17,16,16,16,16,16,17,16,17,16,17,16,16,17,16,17,16,17,16,17,16,17,16,17,17,16,17,16,16,17,},
{17,16,17,17,17,17,17,16,17,16,17,16,16,17,16,17,17,16,16,17,16,17,16,16,16,16,17,16,16,17,},
{17,16,16,17,17,17,17,16,17,16,17,16,16,17,16,16,16,16,17,17,16,17,17,17,17,17,17,16,16,17,},
{17,17,16,16,16,16,17,17,17,16,16,16,16,17,17,17,17,16,17,16,16,17,16,16,16,16,17,16,16,17,},
{17,17,17,16,16,16,16,16,16,16,16,16,16,17,16,16,16,16,16,16,16,16,16,16,16,16,17,16,16,16,},
{17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,},
};
// Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen
TileEngine te = new TileEngine(this, 70, 70, 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();
Star star = new Star();
// 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, 30, 105);
addObject(new Letters('J'),385,385);
addObject(new Letters('U'),665,1155);
addObject(new Letters('M'),1085,245);
addObject(new Letters('P'),1925,945);
addObject(star, 245, 660);
//addObject(new Enemy(), 1170, 410);
// 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<SUF>
ce.addCollidingMover(hero);
}
@Override
public void act() {
ce.update();
}
}
| True | 2,675 | 16 | 2,737 | 18 | 2,748 | 15 | 2,737 | 18 | 2,818 | 17 | false | false | false | false | false | true |
37 | 24509_4 | /*_x000D_
* To change this license header, choose License Headers in Project Properties._x000D_
* To change this template file, choose Tools | Templates_x000D_
* and open the template in the editor._x000D_
*/_x000D_
package henkapp;_x000D_
_x000D_
import java.util.Objects;_x000D_
_x000D_
/**_x000D_
*_x000D_
* @author Stijn_x000D_
*/_x000D_
public class Persoon implements Comparable<Persoon>{_x000D_
_x000D_
private String naam;_x000D_
private String plaats;_x000D_
private String telefoon;_x000D_
_x000D_
Persoon(String naam, String plaats, String telefoon) {_x000D_
this.naam = naam;_x000D_
this.plaats = plaats;_x000D_
this.telefoon = telefoon;_x000D_
}_x000D_
_x000D_
@Override_x000D_
public String toString() {_x000D_
return naam + " - " + telefoon;_x000D_
}_x000D_
_x000D_
public String getNaam() {_x000D_
return naam;_x000D_
}_x000D_
_x000D_
public void setNaam(String naam) {_x000D_
this.naam = naam;_x000D_
}_x000D_
_x000D_
public String getPlaats() {_x000D_
return plaats;_x000D_
}_x000D_
_x000D_
public void setPlaats(String plaats) {_x000D_
this.plaats = plaats;_x000D_
}_x000D_
_x000D_
public String getTelefoon() {_x000D_
return telefoon;_x000D_
}_x000D_
_x000D_
public void setTelefoon(String telefoon) {_x000D_
this.telefoon = telefoon;_x000D_
}_x000D_
_x000D_
boolean contentEquals(Persoon p) {_x000D_
if (this.naam.equals(p.getNaam())) {_x000D_
if (this.plaats.equals(p.getPlaats())) {_x000D_
if (this.telefoon.equals(p.getTelefoon())) {_x000D_
return true;_x000D_
}_x000D_
}_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
//Bron: http://stackoverflow.com/questions/185937/overriding-the-java-equals-method-quirk_x000D_
@Override_x000D_
public boolean equals(Object other) {_x000D_
if (other == null) { //Wanneer het andere object null is zijn de twee ongelijk_x000D_
return false;_x000D_
}_x000D_
if (other.hashCode() == this.hashCode()) {_x000D_
return true;_x000D_
}_x000D_
if (!(other instanceof Persoon)) {_x000D_
return false;_x000D_
}_x000D_
Persoon otherPersoon = (Persoon) other;_x000D_
if (this.naam.equals(otherPersoon.getNaam())) {_x000D_
if (this.plaats.equals(otherPersoon.getPlaats())) {_x000D_
if (this.telefoon.equals(otherPersoon.getTelefoon())) {_x000D_
return true;_x000D_
}_x000D_
}_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
// Automatisch gegenereerde hashCode() methode_x000D_
// Geen aanpassingen omdat het me zo goed lijkt_x000D_
@Override_x000D_
public int hashCode() {_x000D_
int hash = 7;_x000D_
hash = 83 * hash + Objects.hashCode(this.naam);_x000D_
hash = 83 * hash + Objects.hashCode(this.plaats);_x000D_
hash = 83 * hash + Objects.hashCode(this.telefoon);_x000D_
return hash;_x000D_
}_x000D_
_x000D_
// Bron:http://www.tutorialspoint.com/java/java_using_comparator.htm_x000D_
// Vergelijken van de namen._x000D_
@Override_x000D_
public int compareTo(Persoon o) {_x000D_
return (this.naam).compareTo(o.naam);_x000D_
}_x000D_
}_x000D_
| 94BasMulder/JCF4MitStijn | HenkApp/src/henkapp/Persoon.java | 864 | // Geen aanpassingen omdat het me zo goed lijkt_x000D_ | line_comment | nl | /*_x000D_
* To change this license header, choose License Headers in Project Properties._x000D_
* To change this template file, choose Tools | Templates_x000D_
* and open the template in the editor._x000D_
*/_x000D_
package henkapp;_x000D_
_x000D_
import java.util.Objects;_x000D_
_x000D_
/**_x000D_
*_x000D_
* @author Stijn_x000D_
*/_x000D_
public class Persoon implements Comparable<Persoon>{_x000D_
_x000D_
private String naam;_x000D_
private String plaats;_x000D_
private String telefoon;_x000D_
_x000D_
Persoon(String naam, String plaats, String telefoon) {_x000D_
this.naam = naam;_x000D_
this.plaats = plaats;_x000D_
this.telefoon = telefoon;_x000D_
}_x000D_
_x000D_
@Override_x000D_
public String toString() {_x000D_
return naam + " - " + telefoon;_x000D_
}_x000D_
_x000D_
public String getNaam() {_x000D_
return naam;_x000D_
}_x000D_
_x000D_
public void setNaam(String naam) {_x000D_
this.naam = naam;_x000D_
}_x000D_
_x000D_
public String getPlaats() {_x000D_
return plaats;_x000D_
}_x000D_
_x000D_
public void setPlaats(String plaats) {_x000D_
this.plaats = plaats;_x000D_
}_x000D_
_x000D_
public String getTelefoon() {_x000D_
return telefoon;_x000D_
}_x000D_
_x000D_
public void setTelefoon(String telefoon) {_x000D_
this.telefoon = telefoon;_x000D_
}_x000D_
_x000D_
boolean contentEquals(Persoon p) {_x000D_
if (this.naam.equals(p.getNaam())) {_x000D_
if (this.plaats.equals(p.getPlaats())) {_x000D_
if (this.telefoon.equals(p.getTelefoon())) {_x000D_
return true;_x000D_
}_x000D_
}_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
//Bron: http://stackoverflow.com/questions/185937/overriding-the-java-equals-method-quirk_x000D_
@Override_x000D_
public boolean equals(Object other) {_x000D_
if (other == null) { //Wanneer het andere object null is zijn de twee ongelijk_x000D_
return false;_x000D_
}_x000D_
if (other.hashCode() == this.hashCode()) {_x000D_
return true;_x000D_
}_x000D_
if (!(other instanceof Persoon)) {_x000D_
return false;_x000D_
}_x000D_
Persoon otherPersoon = (Persoon) other;_x000D_
if (this.naam.equals(otherPersoon.getNaam())) {_x000D_
if (this.plaats.equals(otherPersoon.getPlaats())) {_x000D_
if (this.telefoon.equals(otherPersoon.getTelefoon())) {_x000D_
return true;_x000D_
}_x000D_
}_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
// Automatisch gegenereerde hashCode() methode_x000D_
// Geen aanpassingen<SUF>
@Override_x000D_
public int hashCode() {_x000D_
int hash = 7;_x000D_
hash = 83 * hash + Objects.hashCode(this.naam);_x000D_
hash = 83 * hash + Objects.hashCode(this.plaats);_x000D_
hash = 83 * hash + Objects.hashCode(this.telefoon);_x000D_
return hash;_x000D_
}_x000D_
_x000D_
// Bron:http://www.tutorialspoint.com/java/java_using_comparator.htm_x000D_
// Vergelijken van de namen._x000D_
@Override_x000D_
public int compareTo(Persoon o) {_x000D_
return (this.naam).compareTo(o.naam);_x000D_
}_x000D_
}_x000D_
| True | 1,335 | 19 | 1,463 | 24 | 1,459 | 18 | 1,463 | 24 | 1,585 | 22 | false | false | false | false | false | true |
1,125 | 124819_13 | package nl.overheid.stelsel.gba.reva.bag.triemap;
import java.io.Serializable;
import org.apache.commons.lang.StringUtils;
public class BagAdres implements Serializable {
private static final long serialVersionUID = -733312179296502981L;
/**
* Een categorisering van de gebruiksdoelen van het betreffende
* VERBLIJFSOBJECT, zoals dit formeel door de overheid als zodanig is
* toegestaan. Een VERBLIJFSOBJECT is de kleinste binnen één of meerdere
* panden gelegen en voor woon -, bedrijfsmatige - of recreatieve doeleinden
* geschikte eenheid van gebruik, die ontsloten wordt via een eigen toegang
* vanaf de openbare weg, een erf of een gedeelde verkeersruimte en die
* onderwerp kan zijn van rechtshandelingen.
*/
private String gebruiksdoel;
/**
* Een door of namens het gemeentebestuur ten aanzien van een adresseerbaar
* object toegekende nummering.
*/
private String huisnummer;
/**
* Een door of namens het gemeentebestuur ten aanzien van een adresseerbaar
* object toegekende nadere toevoeging aan een huisnummer of een combinatie
* van huisnummer en huisletter.
*/
private String huisnummertoevoeging;
/**
* Een door of namens het gemeentebestuur ten aanzien van een adresseerbaar
* object toegekende toevoeging aan een huisnummer in de vorm van een
* alfanumeriek teken.
*/
private String huisletter;
/**
* De unieke aanduiding van een NUMMERAANDUIDING. Een NUMMERAANDUIDING is een
* door de gemeenteraad als zodanig toegekende aanduiding van een
* adresseerbaar object.
*/
private String nummeraanduidingId;
/**
* Een naam die aan een OPENBARE RUIMTE is toegekend in een daartoe strekkend
* formeel gemeentelijk besluit. Een OPENBARE RUIMTE is een door de
* gemeenteraad als zodanig aangewezen benaming van een binnen 1 woonplaats
* gelegen buitenruimte.
*
*/
private String openbareRuimteNaam;
/**
* De door TNT Post vastgestelde code behorende bij een bepaalde combinatie
* van een straatnaam en een huisnummer.
*/
private String postcode;
/**
* De aard van een als zodanig benoemde NUMMERAANDUIDING. Een NUMMERAANDUIDING
* is een door de gemeenteraad als zodanig toegekende aanduiding van een
* adresseerbaar object.
*/
private String type;
/**
* De landelijk unieke aanduiding van een WOONPLAATS, zoals vastgesteld door
* de beheerder van de landelijke tabel voor woonplaatsen. Een WOONPLAATS is
* een door de gemeenteraad als zodanig aangewezen gedeelte van het
* gemeentelijk grondgebied.
*/
private String woonplaatsId;
/**
* De benaming van een door het gemeentebestuur aangewezen WOONPLAATS. Een
* WOONPLAATS is een door de gemeenteraad als zodanig aangewezen gedeelte van
* het gemeentelijk grondgebied.
*/
private String woonplaatsNaam;
public BagAdres() {
// Lege constructor.
}
public String getGebruiksdoel() {
return gebruiksdoel;
}
public void setGebruiksdoel( String gebruiksdoel ) {
this.gebruiksdoel = gebruiksdoel;
}
public String getHuisnummer() {
return huisnummer;
}
public void setHuisnummer( String huisnummer ) {
this.huisnummer = huisnummer;
}
public String getHuisnummertoevoeging() {
return huisnummertoevoeging;
}
public void setHuisnummertoevoeging( String huisnummertoevoeging ) {
this.huisnummertoevoeging = huisnummertoevoeging;
}
public String getHuisletter() {
return huisletter;
}
public void setHuisletter( String huisletter ) {
this.huisletter = huisletter;
}
public String getNummeraanduidingId() {
return nummeraanduidingId;
}
public void setNummeraanduidingId( String nummeraanduidingId ) {
this.nummeraanduidingId = nummeraanduidingId;
}
public String getOpenbareRuimteNaam() {
return openbareRuimteNaam;
}
public void setOpenbareRuimteNaam( String openbareRuimteNaam ) {
this.openbareRuimteNaam = openbareRuimteNaam;
}
public String getPostcode() {
return postcode;
}
public void setPostcode( String postcode ) {
this.postcode = postcode;
}
public String getType() {
return type;
}
public void setType( String type ) {
this.type = type;
}
public String getWoonplaatsId() {
return woonplaatsId;
}
public void setWoonplaatsId( String woonplaatsId ) {
this.woonplaatsId = woonplaatsId;
}
public String getWoonplaatsNaam() {
return woonplaatsNaam;
}
public void setWoonplaatsNaam( String woonplaatsNaam ) {
this.woonplaatsNaam = woonplaatsNaam;
}
/**
* Geeft de NUMMERAANDUIDING bestaande uit de samenvoeging van:
* (huisnummer)(huisletter)(huisnummertoevoeging)
*
* @return De samengestelde nummeraanduiding.
*/
public String getNummeraanduiding() {
StringBuffer nummeraanduiding = new StringBuffer();
if( huisnummer != null ) {
nummeraanduiding.append( huisnummer );
}
if( huisletter != null ) {
nummeraanduiding.append( huisletter );
}
if( huisnummertoevoeging != null ) {
nummeraanduiding.append( huisnummertoevoeging );
}
return nummeraanduiding.toString();
}
@Override
public boolean equals( Object obj ) {
// Vergelijking met niks.
if( obj == null ) {
return false;
}
// Vergelijking met zichzelf.
if( this == obj ) {
return true;
}
if( obj instanceof BagAdres ) {
BagAdres adres = (BagAdres) obj;
// We gaan ervan uit dat de objecten gelijk zijn, totdat we zeker
// weten dat dit niet zo is.
boolean isEqual = true;
isEqual &= StringUtils.equalsIgnoreCase( gebruiksdoel, adres.getGebruiksdoel() );
isEqual &= StringUtils.equalsIgnoreCase( huisnummer, adres.getHuisnummer() );
isEqual &= StringUtils.equalsIgnoreCase( huisnummertoevoeging, adres.getHuisnummertoevoeging() );
isEqual &= StringUtils.equalsIgnoreCase( huisletter, adres.getHuisletter() );
isEqual &= StringUtils.equalsIgnoreCase( nummeraanduidingId, adres.getNummeraanduidingId() );
isEqual &= StringUtils.equalsIgnoreCase( openbareRuimteNaam, adres.getOpenbareRuimteNaam() );
isEqual &= StringUtils.equalsIgnoreCase( postcode, adres.getPostcode() );
isEqual &= StringUtils.equalsIgnoreCase( type, adres.getType() );
isEqual &= StringUtils.equalsIgnoreCase( woonplaatsId, adres.getWoonplaatsId() );
isEqual &= StringUtils.equalsIgnoreCase( woonplaatsNaam, adres.getWoonplaatsNaam() );
return isEqual;
}
return false;
}
@Override
public int hashCode() {
StringBuffer string = new StringBuffer();
string.append( gebruiksdoel );
string.append( huisnummer );
string.append( huisnummertoevoeging );
string.append( huisletter );
string.append( nummeraanduidingId );
string.append( openbareRuimteNaam );
string.append( postcode );
string.append( type );
string.append( woonplaatsId );
string.append( woonplaatsNaam );
return string.toString().hashCode();
}
@Override
public String toString() {
StringBuffer string = new StringBuffer();
string.append( nummeraanduidingId ).append( "," );
string.append( woonplaatsNaam ).append( " " ).append( woonplaatsId ).append( "," );
string.append( openbareRuimteNaam ).append( "," );
if( huisnummer != null ) {
string.append( huisnummer ).append( "," );
}
if( huisletter != null ) {
string.append( huisletter ).append( "," );
}
if( huisnummertoevoeging != null ) {
string.append( huisnummertoevoeging ).append( "," );
}
string.append( postcode ).append( "," );
string.append( type ).append( "," );
string.append( gebruiksdoel );
return string.toString();
}
}
| MinBZK/REVA | huidig-productie-reva/reva/reva-bag/reva-bag-triemap/src/main/java/nl/overheid/stelsel/gba/reva/bag/triemap/BagAdres.java | 2,670 | // We gaan ervan uit dat de objecten gelijk zijn, totdat we zeker | line_comment | nl | package nl.overheid.stelsel.gba.reva.bag.triemap;
import java.io.Serializable;
import org.apache.commons.lang.StringUtils;
public class BagAdres implements Serializable {
private static final long serialVersionUID = -733312179296502981L;
/**
* Een categorisering van de gebruiksdoelen van het betreffende
* VERBLIJFSOBJECT, zoals dit formeel door de overheid als zodanig is
* toegestaan. Een VERBLIJFSOBJECT is de kleinste binnen één of meerdere
* panden gelegen en voor woon -, bedrijfsmatige - of recreatieve doeleinden
* geschikte eenheid van gebruik, die ontsloten wordt via een eigen toegang
* vanaf de openbare weg, een erf of een gedeelde verkeersruimte en die
* onderwerp kan zijn van rechtshandelingen.
*/
private String gebruiksdoel;
/**
* Een door of namens het gemeentebestuur ten aanzien van een adresseerbaar
* object toegekende nummering.
*/
private String huisnummer;
/**
* Een door of namens het gemeentebestuur ten aanzien van een adresseerbaar
* object toegekende nadere toevoeging aan een huisnummer of een combinatie
* van huisnummer en huisletter.
*/
private String huisnummertoevoeging;
/**
* Een door of namens het gemeentebestuur ten aanzien van een adresseerbaar
* object toegekende toevoeging aan een huisnummer in de vorm van een
* alfanumeriek teken.
*/
private String huisletter;
/**
* De unieke aanduiding van een NUMMERAANDUIDING. Een NUMMERAANDUIDING is een
* door de gemeenteraad als zodanig toegekende aanduiding van een
* adresseerbaar object.
*/
private String nummeraanduidingId;
/**
* Een naam die aan een OPENBARE RUIMTE is toegekend in een daartoe strekkend
* formeel gemeentelijk besluit. Een OPENBARE RUIMTE is een door de
* gemeenteraad als zodanig aangewezen benaming van een binnen 1 woonplaats
* gelegen buitenruimte.
*
*/
private String openbareRuimteNaam;
/**
* De door TNT Post vastgestelde code behorende bij een bepaalde combinatie
* van een straatnaam en een huisnummer.
*/
private String postcode;
/**
* De aard van een als zodanig benoemde NUMMERAANDUIDING. Een NUMMERAANDUIDING
* is een door de gemeenteraad als zodanig toegekende aanduiding van een
* adresseerbaar object.
*/
private String type;
/**
* De landelijk unieke aanduiding van een WOONPLAATS, zoals vastgesteld door
* de beheerder van de landelijke tabel voor woonplaatsen. Een WOONPLAATS is
* een door de gemeenteraad als zodanig aangewezen gedeelte van het
* gemeentelijk grondgebied.
*/
private String woonplaatsId;
/**
* De benaming van een door het gemeentebestuur aangewezen WOONPLAATS. Een
* WOONPLAATS is een door de gemeenteraad als zodanig aangewezen gedeelte van
* het gemeentelijk grondgebied.
*/
private String woonplaatsNaam;
public BagAdres() {
// Lege constructor.
}
public String getGebruiksdoel() {
return gebruiksdoel;
}
public void setGebruiksdoel( String gebruiksdoel ) {
this.gebruiksdoel = gebruiksdoel;
}
public String getHuisnummer() {
return huisnummer;
}
public void setHuisnummer( String huisnummer ) {
this.huisnummer = huisnummer;
}
public String getHuisnummertoevoeging() {
return huisnummertoevoeging;
}
public void setHuisnummertoevoeging( String huisnummertoevoeging ) {
this.huisnummertoevoeging = huisnummertoevoeging;
}
public String getHuisletter() {
return huisletter;
}
public void setHuisletter( String huisletter ) {
this.huisletter = huisletter;
}
public String getNummeraanduidingId() {
return nummeraanduidingId;
}
public void setNummeraanduidingId( String nummeraanduidingId ) {
this.nummeraanduidingId = nummeraanduidingId;
}
public String getOpenbareRuimteNaam() {
return openbareRuimteNaam;
}
public void setOpenbareRuimteNaam( String openbareRuimteNaam ) {
this.openbareRuimteNaam = openbareRuimteNaam;
}
public String getPostcode() {
return postcode;
}
public void setPostcode( String postcode ) {
this.postcode = postcode;
}
public String getType() {
return type;
}
public void setType( String type ) {
this.type = type;
}
public String getWoonplaatsId() {
return woonplaatsId;
}
public void setWoonplaatsId( String woonplaatsId ) {
this.woonplaatsId = woonplaatsId;
}
public String getWoonplaatsNaam() {
return woonplaatsNaam;
}
public void setWoonplaatsNaam( String woonplaatsNaam ) {
this.woonplaatsNaam = woonplaatsNaam;
}
/**
* Geeft de NUMMERAANDUIDING bestaande uit de samenvoeging van:
* (huisnummer)(huisletter)(huisnummertoevoeging)
*
* @return De samengestelde nummeraanduiding.
*/
public String getNummeraanduiding() {
StringBuffer nummeraanduiding = new StringBuffer();
if( huisnummer != null ) {
nummeraanduiding.append( huisnummer );
}
if( huisletter != null ) {
nummeraanduiding.append( huisletter );
}
if( huisnummertoevoeging != null ) {
nummeraanduiding.append( huisnummertoevoeging );
}
return nummeraanduiding.toString();
}
@Override
public boolean equals( Object obj ) {
// Vergelijking met niks.
if( obj == null ) {
return false;
}
// Vergelijking met zichzelf.
if( this == obj ) {
return true;
}
if( obj instanceof BagAdres ) {
BagAdres adres = (BagAdres) obj;
// We gaan<SUF>
// weten dat dit niet zo is.
boolean isEqual = true;
isEqual &= StringUtils.equalsIgnoreCase( gebruiksdoel, adres.getGebruiksdoel() );
isEqual &= StringUtils.equalsIgnoreCase( huisnummer, adres.getHuisnummer() );
isEqual &= StringUtils.equalsIgnoreCase( huisnummertoevoeging, adres.getHuisnummertoevoeging() );
isEqual &= StringUtils.equalsIgnoreCase( huisletter, adres.getHuisletter() );
isEqual &= StringUtils.equalsIgnoreCase( nummeraanduidingId, adres.getNummeraanduidingId() );
isEqual &= StringUtils.equalsIgnoreCase( openbareRuimteNaam, adres.getOpenbareRuimteNaam() );
isEqual &= StringUtils.equalsIgnoreCase( postcode, adres.getPostcode() );
isEqual &= StringUtils.equalsIgnoreCase( type, adres.getType() );
isEqual &= StringUtils.equalsIgnoreCase( woonplaatsId, adres.getWoonplaatsId() );
isEqual &= StringUtils.equalsIgnoreCase( woonplaatsNaam, adres.getWoonplaatsNaam() );
return isEqual;
}
return false;
}
@Override
public int hashCode() {
StringBuffer string = new StringBuffer();
string.append( gebruiksdoel );
string.append( huisnummer );
string.append( huisnummertoevoeging );
string.append( huisletter );
string.append( nummeraanduidingId );
string.append( openbareRuimteNaam );
string.append( postcode );
string.append( type );
string.append( woonplaatsId );
string.append( woonplaatsNaam );
return string.toString().hashCode();
}
@Override
public String toString() {
StringBuffer string = new StringBuffer();
string.append( nummeraanduidingId ).append( "," );
string.append( woonplaatsNaam ).append( " " ).append( woonplaatsId ).append( "," );
string.append( openbareRuimteNaam ).append( "," );
if( huisnummer != null ) {
string.append( huisnummer ).append( "," );
}
if( huisletter != null ) {
string.append( huisletter ).append( "," );
}
if( huisnummertoevoeging != null ) {
string.append( huisnummertoevoeging ).append( "," );
}
string.append( postcode ).append( "," );
string.append( type ).append( "," );
string.append( gebruiksdoel );
return string.toString();
}
}
| True | 2,252 | 20 | 2,438 | 21 | 2,216 | 16 | 2,438 | 21 | 2,730 | 22 | false | false | false | false | false | true |
4,309 | 74044_10 | package sh.siava.pixelxpert.modpacks.systemui;
import static android.view.MotionEvent.ACTION_DOWN;
import static de.robv.android.xposed.XposedBridge.hookAllConstructors;
import static de.robv.android.xposed.XposedBridge.hookAllMethods;
import static de.robv.android.xposed.XposedHelpers.callMethod;
import static de.robv.android.xposed.XposedHelpers.findClass;
import static de.robv.android.xposed.XposedHelpers.findClassIfExists;
import static de.robv.android.xposed.XposedHelpers.getAdditionalInstanceField;
import static de.robv.android.xposed.XposedHelpers.getFloatField;
import static de.robv.android.xposed.XposedHelpers.getObjectField;
import static de.robv.android.xposed.XposedHelpers.setAdditionalInstanceField;
import static de.robv.android.xposed.XposedHelpers.setObjectField;
import static sh.siava.pixelxpert.modpacks.XPrefs.Xprefs;
import static sh.siava.pixelxpert.modpacks.utils.toolkit.ReflectionTools.tryHookAllMethods;
import android.content.Context;
import android.graphics.Point;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.callbacks.XC_LoadPackage;
import sh.siava.pixelxpert.modpacks.Constants;
import sh.siava.pixelxpert.modpacks.XPLauncher;
import sh.siava.pixelxpert.modpacks.XposedModPack;
import sh.siava.pixelxpert.modpacks.launcher.TaskbarActivator;
@SuppressWarnings("RedundantThrows")
public class GestureNavbarManager extends XposedModPack {
public static final String listenPackage = Constants.SYSTEM_UI_PACKAGE;
//region Back gesture
private static float backGestureHeightFractionLeft = 1f; // % of screen height. can be anything between 0 to 1
private static float backGestureHeightFractionRight = 1f; // % of screen height. can be anything between 0 to 1
private static boolean leftEnabled = true;
private static boolean rightEnabled = true;
float initialBackX = 0;
Object EdgeBackGestureHandler;
//endregion
//region pill size
private static int GesPillHeightFactor = 100;
private static float widthFactor = 1f;
private Object mNavigationBarInflaterView = null;
//endregion
//region pill color
private boolean colorReplaced = false;
private static boolean navPillColorAccent = false;
private static final int mLightColor = 0xEBFFFFFF, mDarkColor = 0x99000000; //original navbar colors
//endregion
public GestureNavbarManager(Context context) {
super(context);
}
public void updatePrefs(String... Key) {
if (Xprefs == null) return;
//region Back gesture
leftEnabled = Xprefs.getBoolean("BackFromLeft", true);
rightEnabled = Xprefs.getBoolean("BackFromRight", true);
backGestureHeightFractionLeft = Xprefs.getSliderInt( "BackLeftHeight", 100) / 100f;
backGestureHeightFractionRight = Xprefs.getSliderInt( "BackRightHeight", 100) / 100f;
//endregion
//region pill size
widthFactor = Xprefs.getSliderInt( "GesPillWidthModPos", 50) * .02f;
GesPillHeightFactor = Xprefs.getSliderInt( "GesPillHeightFactor", 100);
int taskbarMode = TaskbarActivator.TASKBAR_DEFAULT;
String taskbarModeStr = Xprefs.getString("taskBarMode", "0");
try {
taskbarMode = Integer.parseInt(taskbarModeStr);
} catch (Exception ignored) {
}
if (taskbarMode == TaskbarActivator.TASKBAR_ON || Xprefs.getBoolean("HideNavbar", false)) {
widthFactor = 0f;
}
if (Key.length > 0) {
refreshNavbar();
}
//endregion
//region pill color
navPillColorAccent = Xprefs.getBoolean("navPillColorAccent", false);
//endregion
}
//region pill size
private void refreshNavbar() {
try {
callMethod(mNavigationBarInflaterView, "onFinishInflate");
} catch (Throwable ignored) {}
}
//endregion
@Override
public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) throws Throwable {
if (!lpparam.packageName.equals(listenPackage)) return;
Class<?> NavigationBarInflaterViewClass = findClass("com.android.systemui.navigationbar.NavigationBarInflaterView", lpparam.classLoader);
Class<?> NavigationHandleClass = findClass("com.android.systemui.navigationbar.gestural.NavigationHandle", lpparam.classLoader);
Class<?> EdgeBackGestureHandlerClass = findClassIfExists("com.android.systemui.navigationbar.gestural.EdgeBackGestureHandler", lpparam.classLoader);
Class<?> NavigationBarEdgePanelClass = findClassIfExists("com.android.systemui.navigationbar.gestural.NavigationBarEdgePanel", lpparam.classLoader);
Class<?> BackPanelControllerClass = findClass("com.android.systemui.navigationbar.gestural.BackPanelController", lpparam.classLoader);
//region back gesture
//A14
hookAllConstructors(EdgeBackGestureHandlerClass, new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
EdgeBackGestureHandler = param.thisObject;
}
});
hookAllMethods(BackPanelControllerClass, "onMotionEvent", new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
MotionEvent ev = (MotionEvent) param.args[0];
if(ev.getActionMasked() == ACTION_DOWN) //down action is enough. once gesture is refused it won't accept further actions
{
if(notWithinInsets(ev.getX(),
ev.getY(),
(Point) getObjectField(EdgeBackGestureHandler, "mDisplaySize"),
getFloatField(EdgeBackGestureHandler, "mBottomGestureHeight")))
{
setObjectField(EdgeBackGestureHandler, "mAllowGesture", false); //act like the gesture was not good enough
param.setResult(null); //and stop the current method too
}
}
}
});
//Android 13
tryHookAllMethods(NavigationBarEdgePanelClass, "onMotionEvent", new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
MotionEvent event = (MotionEvent) param.args[0];
if(event.getAction() == ACTION_DOWN)
{
initialBackX = event.getX();
}
if (notWithinInsets(initialBackX, event.getY(), (Point) getObjectField(param.thisObject, "mDisplaySize"), 0)) {
//event.setAction(MotionEvent.ACTION_CANCEL);
param.setResult(null);
}
}
});
//endregion
//region pill color
hookAllMethods(NavigationHandleClass, "setDarkIntensity", new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
if (navPillColorAccent || colorReplaced) {
setObjectField(param.thisObject, "mLightColor", (navPillColorAccent) ? mContext.getResources().getColor(android.R.color.system_accent1_200, mContext.getTheme()) : mLightColor);
setObjectField(param.thisObject, "mDarkColor", (navPillColorAccent) ? mContext.getResources().getColor(android.R.color.system_accent1_600, mContext.getTheme()) : mDarkColor);
colorReplaced = true;
}
}
});
//endregion
//region pill size
hookAllMethods(NavigationHandleClass,
"setVertical", new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
if (widthFactor != 1f) {
View result = (View) param.thisObject;
ViewGroup.LayoutParams resultLayoutParams = result.getLayoutParams();
int originalWidth;
try {
originalWidth = (int) getAdditionalInstanceField(param.thisObject, "originalWidth");
} catch (Throwable ignored) {
originalWidth = resultLayoutParams.width;
setAdditionalInstanceField(param.thisObject, "originalWidth", originalWidth);
}
resultLayoutParams.width = Math.round(originalWidth * widthFactor);
}
}
});
hookAllMethods(NavigationHandleClass,
"onDraw", new XC_MethodHook() {
int mRadius = 0;
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
if (GesPillHeightFactor != 100) {
mRadius = Math.round((float) getObjectField(param.thisObject, "mRadius"));
setObjectField(param.thisObject, "mRadius", Math.round(mRadius * GesPillHeightFactor / 100f));
}
}
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
if (mRadius > 0) {
setObjectField(param.thisObject, "mRadius", mRadius);
}
}
});
hookAllConstructors(NavigationBarInflaterViewClass, new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
mNavigationBarInflaterView = param.thisObject;
refreshNavbar();
}
});
hookAllMethods(NavigationBarInflaterViewClass,
"createView", new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
if (widthFactor != 1f) {
String button = (String) callMethod(param.thisObject, "extractButton", param.args[0]);
if (!button.equals("home_handle")) return;
View result = (View) param.getResult();
ViewGroup.LayoutParams resultLayoutParams = result.getLayoutParams();
resultLayoutParams.width = Math.round(resultLayoutParams.width * widthFactor);
result.setLayoutParams(resultLayoutParams);
}
}
});
//endregion
}
//region Back gesture
private boolean notWithinInsets(float x, float y, Point mDisplaySize, float mBottomGestureHeight) {
boolean isLeftSide = x < (mDisplaySize.x / 3f);
if ((isLeftSide && !leftEnabled)
|| (!isLeftSide && !rightEnabled)) {
return true;
}
int mEdgeHeight = isLeftSide ?
Math.round(mDisplaySize.y * backGestureHeightFractionLeft) :
Math.round(mDisplaySize.y * backGestureHeightFractionRight);
return mEdgeHeight != 0
&& y < (mDisplaySize.y
- mBottomGestureHeight
- mEdgeHeight);
}
//endregion
@Override
public boolean listensTo(String packageName) {
return listenPackage.equals(packageName) && !XPLauncher.isChildProcess;
}
} | siavash79/PixelXpert | app/src/main/java/sh/siava/pixelxpert/modpacks/systemui/GestureNavbarManager.java | 3,245 | //region back gesture | line_comment | nl | package sh.siava.pixelxpert.modpacks.systemui;
import static android.view.MotionEvent.ACTION_DOWN;
import static de.robv.android.xposed.XposedBridge.hookAllConstructors;
import static de.robv.android.xposed.XposedBridge.hookAllMethods;
import static de.robv.android.xposed.XposedHelpers.callMethod;
import static de.robv.android.xposed.XposedHelpers.findClass;
import static de.robv.android.xposed.XposedHelpers.findClassIfExists;
import static de.robv.android.xposed.XposedHelpers.getAdditionalInstanceField;
import static de.robv.android.xposed.XposedHelpers.getFloatField;
import static de.robv.android.xposed.XposedHelpers.getObjectField;
import static de.robv.android.xposed.XposedHelpers.setAdditionalInstanceField;
import static de.robv.android.xposed.XposedHelpers.setObjectField;
import static sh.siava.pixelxpert.modpacks.XPrefs.Xprefs;
import static sh.siava.pixelxpert.modpacks.utils.toolkit.ReflectionTools.tryHookAllMethods;
import android.content.Context;
import android.graphics.Point;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.callbacks.XC_LoadPackage;
import sh.siava.pixelxpert.modpacks.Constants;
import sh.siava.pixelxpert.modpacks.XPLauncher;
import sh.siava.pixelxpert.modpacks.XposedModPack;
import sh.siava.pixelxpert.modpacks.launcher.TaskbarActivator;
@SuppressWarnings("RedundantThrows")
public class GestureNavbarManager extends XposedModPack {
public static final String listenPackage = Constants.SYSTEM_UI_PACKAGE;
//region Back gesture
private static float backGestureHeightFractionLeft = 1f; // % of screen height. can be anything between 0 to 1
private static float backGestureHeightFractionRight = 1f; // % of screen height. can be anything between 0 to 1
private static boolean leftEnabled = true;
private static boolean rightEnabled = true;
float initialBackX = 0;
Object EdgeBackGestureHandler;
//endregion
//region pill size
private static int GesPillHeightFactor = 100;
private static float widthFactor = 1f;
private Object mNavigationBarInflaterView = null;
//endregion
//region pill color
private boolean colorReplaced = false;
private static boolean navPillColorAccent = false;
private static final int mLightColor = 0xEBFFFFFF, mDarkColor = 0x99000000; //original navbar colors
//endregion
public GestureNavbarManager(Context context) {
super(context);
}
public void updatePrefs(String... Key) {
if (Xprefs == null) return;
//region Back gesture
leftEnabled = Xprefs.getBoolean("BackFromLeft", true);
rightEnabled = Xprefs.getBoolean("BackFromRight", true);
backGestureHeightFractionLeft = Xprefs.getSliderInt( "BackLeftHeight", 100) / 100f;
backGestureHeightFractionRight = Xprefs.getSliderInt( "BackRightHeight", 100) / 100f;
//endregion
//region pill size
widthFactor = Xprefs.getSliderInt( "GesPillWidthModPos", 50) * .02f;
GesPillHeightFactor = Xprefs.getSliderInt( "GesPillHeightFactor", 100);
int taskbarMode = TaskbarActivator.TASKBAR_DEFAULT;
String taskbarModeStr = Xprefs.getString("taskBarMode", "0");
try {
taskbarMode = Integer.parseInt(taskbarModeStr);
} catch (Exception ignored) {
}
if (taskbarMode == TaskbarActivator.TASKBAR_ON || Xprefs.getBoolean("HideNavbar", false)) {
widthFactor = 0f;
}
if (Key.length > 0) {
refreshNavbar();
}
//endregion
//region pill color
navPillColorAccent = Xprefs.getBoolean("navPillColorAccent", false);
//endregion
}
//region pill size
private void refreshNavbar() {
try {
callMethod(mNavigationBarInflaterView, "onFinishInflate");
} catch (Throwable ignored) {}
}
//endregion
@Override
public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) throws Throwable {
if (!lpparam.packageName.equals(listenPackage)) return;
Class<?> NavigationBarInflaterViewClass = findClass("com.android.systemui.navigationbar.NavigationBarInflaterView", lpparam.classLoader);
Class<?> NavigationHandleClass = findClass("com.android.systemui.navigationbar.gestural.NavigationHandle", lpparam.classLoader);
Class<?> EdgeBackGestureHandlerClass = findClassIfExists("com.android.systemui.navigationbar.gestural.EdgeBackGestureHandler", lpparam.classLoader);
Class<?> NavigationBarEdgePanelClass = findClassIfExists("com.android.systemui.navigationbar.gestural.NavigationBarEdgePanel", lpparam.classLoader);
Class<?> BackPanelControllerClass = findClass("com.android.systemui.navigationbar.gestural.BackPanelController", lpparam.classLoader);
//region back<SUF>
//A14
hookAllConstructors(EdgeBackGestureHandlerClass, new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
EdgeBackGestureHandler = param.thisObject;
}
});
hookAllMethods(BackPanelControllerClass, "onMotionEvent", new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
MotionEvent ev = (MotionEvent) param.args[0];
if(ev.getActionMasked() == ACTION_DOWN) //down action is enough. once gesture is refused it won't accept further actions
{
if(notWithinInsets(ev.getX(),
ev.getY(),
(Point) getObjectField(EdgeBackGestureHandler, "mDisplaySize"),
getFloatField(EdgeBackGestureHandler, "mBottomGestureHeight")))
{
setObjectField(EdgeBackGestureHandler, "mAllowGesture", false); //act like the gesture was not good enough
param.setResult(null); //and stop the current method too
}
}
}
});
//Android 13
tryHookAllMethods(NavigationBarEdgePanelClass, "onMotionEvent", new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
MotionEvent event = (MotionEvent) param.args[0];
if(event.getAction() == ACTION_DOWN)
{
initialBackX = event.getX();
}
if (notWithinInsets(initialBackX, event.getY(), (Point) getObjectField(param.thisObject, "mDisplaySize"), 0)) {
//event.setAction(MotionEvent.ACTION_CANCEL);
param.setResult(null);
}
}
});
//endregion
//region pill color
hookAllMethods(NavigationHandleClass, "setDarkIntensity", new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
if (navPillColorAccent || colorReplaced) {
setObjectField(param.thisObject, "mLightColor", (navPillColorAccent) ? mContext.getResources().getColor(android.R.color.system_accent1_200, mContext.getTheme()) : mLightColor);
setObjectField(param.thisObject, "mDarkColor", (navPillColorAccent) ? mContext.getResources().getColor(android.R.color.system_accent1_600, mContext.getTheme()) : mDarkColor);
colorReplaced = true;
}
}
});
//endregion
//region pill size
hookAllMethods(NavigationHandleClass,
"setVertical", new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
if (widthFactor != 1f) {
View result = (View) param.thisObject;
ViewGroup.LayoutParams resultLayoutParams = result.getLayoutParams();
int originalWidth;
try {
originalWidth = (int) getAdditionalInstanceField(param.thisObject, "originalWidth");
} catch (Throwable ignored) {
originalWidth = resultLayoutParams.width;
setAdditionalInstanceField(param.thisObject, "originalWidth", originalWidth);
}
resultLayoutParams.width = Math.round(originalWidth * widthFactor);
}
}
});
hookAllMethods(NavigationHandleClass,
"onDraw", new XC_MethodHook() {
int mRadius = 0;
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
if (GesPillHeightFactor != 100) {
mRadius = Math.round((float) getObjectField(param.thisObject, "mRadius"));
setObjectField(param.thisObject, "mRadius", Math.round(mRadius * GesPillHeightFactor / 100f));
}
}
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
if (mRadius > 0) {
setObjectField(param.thisObject, "mRadius", mRadius);
}
}
});
hookAllConstructors(NavigationBarInflaterViewClass, new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
mNavigationBarInflaterView = param.thisObject;
refreshNavbar();
}
});
hookAllMethods(NavigationBarInflaterViewClass,
"createView", new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
if (widthFactor != 1f) {
String button = (String) callMethod(param.thisObject, "extractButton", param.args[0]);
if (!button.equals("home_handle")) return;
View result = (View) param.getResult();
ViewGroup.LayoutParams resultLayoutParams = result.getLayoutParams();
resultLayoutParams.width = Math.round(resultLayoutParams.width * widthFactor);
result.setLayoutParams(resultLayoutParams);
}
}
});
//endregion
}
//region Back gesture
private boolean notWithinInsets(float x, float y, Point mDisplaySize, float mBottomGestureHeight) {
boolean isLeftSide = x < (mDisplaySize.x / 3f);
if ((isLeftSide && !leftEnabled)
|| (!isLeftSide && !rightEnabled)) {
return true;
}
int mEdgeHeight = isLeftSide ?
Math.round(mDisplaySize.y * backGestureHeightFractionLeft) :
Math.round(mDisplaySize.y * backGestureHeightFractionRight);
return mEdgeHeight != 0
&& y < (mDisplaySize.y
- mBottomGestureHeight
- mEdgeHeight);
}
//endregion
@Override
public boolean listensTo(String packageName) {
return listenPackage.equals(packageName) && !XPLauncher.isChildProcess;
}
} | False | 2,461 | 4 | 2,839 | 4 | 2,771 | 4 | 2,839 | 4 | 3,583 | 4 | false | false | false | false | false | true |
21 | 141870_0 | package view;
import java.awt.Color;
import java.awt.Graphics;
import java.util.HashMap;
import javax.swing.JPanel;
import logic.Counter;
/**
* maak een histogram aan
*/
public class Histogram extends JPanel
{
// hashmap die hoeveelheid per kleur bij houdt
private HashMap<Color, Counter> stats;
// hoogte van de histogram
private int height;
// breedte van de histogram
private int width;
// afstand tussen ieder balk
private final int SPACE = 40;
/**
* leeg constructor
*/
public Histogram()
{
}
/**
* stats wordt toegewezen
* @param stats populate stats
*/
public void stats(HashMap<Color, Counter> stats)
{
this.stats = stats;
}
/**
* bepaald de frame grote van de histogram
* @param width
* @param height
*/
public void setSize(int width, int height)
{
this.width = width;
this.height = height;
}
/**
* maak de histogram
* @param g Graphic component
*/
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// hoogte van de blok
int height;
// breedte van de blok
int width;
if (!stats.isEmpty())
{
width = this.width / stats.size();
}
else
{
width = 4;
}
// blok counter
int blok = 0;
// teken de blok
for (Color color : stats.keySet())
{
// bepaald de hoogte van de blok;
height = stats.get(color).getCount() / 5;
// kleurt de blok
g.setColor(color);
g.fillRect(width * blok + SPACE, this.height - height - SPACE, width - 1, height);
// paint de outline van de blok
g.setColor(Color.BLACK);
g.drawRect(width * blok + SPACE, this.height - height - SPACE, width - 1, height);
blok++;
}
}
} | 2ntense/foxes-and-rabbits-v2 | src/view/Histogram.java | 634 | /**
* maak een histogram aan
*/ | block_comment | nl | package view;
import java.awt.Color;
import java.awt.Graphics;
import java.util.HashMap;
import javax.swing.JPanel;
import logic.Counter;
/**
* maak een histogram<SUF>*/
public class Histogram extends JPanel
{
// hashmap die hoeveelheid per kleur bij houdt
private HashMap<Color, Counter> stats;
// hoogte van de histogram
private int height;
// breedte van de histogram
private int width;
// afstand tussen ieder balk
private final int SPACE = 40;
/**
* leeg constructor
*/
public Histogram()
{
}
/**
* stats wordt toegewezen
* @param stats populate stats
*/
public void stats(HashMap<Color, Counter> stats)
{
this.stats = stats;
}
/**
* bepaald de frame grote van de histogram
* @param width
* @param height
*/
public void setSize(int width, int height)
{
this.width = width;
this.height = height;
}
/**
* maak de histogram
* @param g Graphic component
*/
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// hoogte van de blok
int height;
// breedte van de blok
int width;
if (!stats.isEmpty())
{
width = this.width / stats.size();
}
else
{
width = 4;
}
// blok counter
int blok = 0;
// teken de blok
for (Color color : stats.keySet())
{
// bepaald de hoogte van de blok;
height = stats.get(color).getCount() / 5;
// kleurt de blok
g.setColor(color);
g.fillRect(width * blok + SPACE, this.height - height - SPACE, width - 1, height);
// paint de outline van de blok
g.setColor(Color.BLACK);
g.drawRect(width * blok + SPACE, this.height - height - SPACE, width - 1, height);
blok++;
}
}
} | True | 500 | 9 | 581 | 10 | 575 | 9 | 581 | 10 | 690 | 11 | false | false | false | false | false | true |
573 | 126690_6 | package be.intectbrussel;
public class Oefenreeks1 {
public static void main(String[] args) {
System.out.println("Operators - Oefenreeks - 1");
System.out.println("---- Oefening - 1 ----");
// 1. Declareer twee integer variabelen, "a" en "b", en geef ze de waarden 5 en 10.
int a = 5;
int b = 10;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("---- Oefening - 2 ----");
// 2. Gebruik de plus operator (+) om de som van "a" en "b" te berekenen en print het resultaat.
int res = a + b;
System.out.println("Som resultaat = " + res);
System.out.println("---- Oefening - 3 ----");
// 3. Gebruik de min operator (-) om het verschil tussen "a" en "b" te berekenen en print het resultaat.
res = a - b;
System.out.println("Aftrekking resultaat = " + res);
System.out.println("---- Oefening - 4 ----");
// 4. Gebruik de maal operator (*) om het product van "a" en "b" te berekenen en print het resultaat.
res = a * b;
System.out.println("Vermenigvuldiging resultaat = " + res);
System.out.println("---- Oefening - 5 ----");
// 5. Gebruik de gedeeld door operator (/) om het quotient van "a" en "b" te berekenen en print het resultaat.
res = a / b;
System.out.println("Deling resultaat = " + res);
System.out.println("---- Oefening - 6 ----");
// 6. Gebruik de modulo operator (%) om de rest van "a" gedeeld door "b" te berekenen en print het resultaat.
res = a % b;
System.out.println("Rest resultaat = " + res);
System.out.println("---- Oefening - 7 ----");
// 7. Gebruik de increment operator (++) om de waarde van "a" te verhogen met 1 en print het resultaat.
int inc = ++a;
System.out.println("Verhoogde resultaat = " + inc);
System.out.println("---- Oefening - 8 ----");
// 8. Gebruik de decrement operator (--) om de waarde van "a" te verlagen met 1 en print het resultaat.
int dec = --a;
System.out.println("Verlaagde resultaat = " + dec);
System.out.println("---- Oefening - 9 ----");
// 9. Gebruik de gelijk aan vergelijkingsoperator (==) om te controleren of "a" gelijk is aan "b" en print het resultaat.
Boolean boolRes = a == b;
System.out.println("Vergelijkingsresultaat = " + boolRes);
System.out.println("---- Oefening - 10 ----");
// 10. Gebruik de niet gelijk aan vergelijkingsoperator (!=) om te controleren of "a" ongelijk is aan "b" en print het resultaat.
boolRes = a != b;
System.out.println("Vergelijkingsresultaat = " + boolRes);
}
}
| Gabe-Alvess/OperatorsOefening | src/be/intectbrussel/Oefenreeks1.java | 888 | // 7. Gebruik de increment operator (++) om de waarde van "a" te verhogen met 1 en print het resultaat. | line_comment | nl | package be.intectbrussel;
public class Oefenreeks1 {
public static void main(String[] args) {
System.out.println("Operators - Oefenreeks - 1");
System.out.println("---- Oefening - 1 ----");
// 1. Declareer twee integer variabelen, "a" en "b", en geef ze de waarden 5 en 10.
int a = 5;
int b = 10;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("---- Oefening - 2 ----");
// 2. Gebruik de plus operator (+) om de som van "a" en "b" te berekenen en print het resultaat.
int res = a + b;
System.out.println("Som resultaat = " + res);
System.out.println("---- Oefening - 3 ----");
// 3. Gebruik de min operator (-) om het verschil tussen "a" en "b" te berekenen en print het resultaat.
res = a - b;
System.out.println("Aftrekking resultaat = " + res);
System.out.println("---- Oefening - 4 ----");
// 4. Gebruik de maal operator (*) om het product van "a" en "b" te berekenen en print het resultaat.
res = a * b;
System.out.println("Vermenigvuldiging resultaat = " + res);
System.out.println("---- Oefening - 5 ----");
// 5. Gebruik de gedeeld door operator (/) om het quotient van "a" en "b" te berekenen en print het resultaat.
res = a / b;
System.out.println("Deling resultaat = " + res);
System.out.println("---- Oefening - 6 ----");
// 6. Gebruik de modulo operator (%) om de rest van "a" gedeeld door "b" te berekenen en print het resultaat.
res = a % b;
System.out.println("Rest resultaat = " + res);
System.out.println("---- Oefening - 7 ----");
// 7. Gebruik<SUF>
int inc = ++a;
System.out.println("Verhoogde resultaat = " + inc);
System.out.println("---- Oefening - 8 ----");
// 8. Gebruik de decrement operator (--) om de waarde van "a" te verlagen met 1 en print het resultaat.
int dec = --a;
System.out.println("Verlaagde resultaat = " + dec);
System.out.println("---- Oefening - 9 ----");
// 9. Gebruik de gelijk aan vergelijkingsoperator (==) om te controleren of "a" gelijk is aan "b" en print het resultaat.
Boolean boolRes = a == b;
System.out.println("Vergelijkingsresultaat = " + boolRes);
System.out.println("---- Oefening - 10 ----");
// 10. Gebruik de niet gelijk aan vergelijkingsoperator (!=) om te controleren of "a" ongelijk is aan "b" en print het resultaat.
boolRes = a != b;
System.out.println("Vergelijkingsresultaat = " + boolRes);
}
}
| True | 792 | 33 | 850 | 32 | 828 | 28 | 850 | 32 | 927 | 34 | false | false | false | false | false | true |
440 | 7423_2 | import java.util.HashSet;
import java.util.Objects;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Hier mag je je code scrijven voor de hoofd-opdracht
/* deze regel mag je weg halen voor de bonus opdracht. Onderstaande code is voor de bonus opdracht.
HashSet<Integer> secretnumber = randomnumbergenerator();
String stringnumber = setToStringConverter(secretnumber);
System.out.println(stringnumber);
feedback();
deze regel mag je weg halen voor de bonus opdracht */
}
/*
Deze methode is voor de bonus opdracht.
*/
public static void feedback(String stringnumber) {
Scanner scanner = new Scanner(System.in);
StringBuilder feedback = new StringBuilder();
System.out.println("take a guess");
String guess = scanner.nextLine();
if (Objects.equals(guess, stringnumber)) {
System.out.println("gefeliciteerd je hebt het goed");
} else {
for (int i = 0; i < 4; i++) {
if (guess.substring(i, i + 1).equals(stringnumber.substring(i, i + 1))) {
feedback.append("+");
} else if (stringnumber.contains(guess.substring(i, i + 1))) {
feedback.append("0");
} else {
feedback.append("X");
}
}
}
System.out.println(feedback.toString());
}
}
| EAM26/Huiswerk-Les4 | src/Main.java | 415 | /*
Deze methode is voor de bonus opdracht.
*/ | block_comment | nl | import java.util.HashSet;
import java.util.Objects;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Hier mag je je code scrijven voor de hoofd-opdracht
/* deze regel mag je weg halen voor de bonus opdracht. Onderstaande code is voor de bonus opdracht.
HashSet<Integer> secretnumber = randomnumbergenerator();
String stringnumber = setToStringConverter(secretnumber);
System.out.println(stringnumber);
feedback();
deze regel mag je weg halen voor de bonus opdracht */
}
/*
Deze methode is<SUF>*/
public static void feedback(String stringnumber) {
Scanner scanner = new Scanner(System.in);
StringBuilder feedback = new StringBuilder();
System.out.println("take a guess");
String guess = scanner.nextLine();
if (Objects.equals(guess, stringnumber)) {
System.out.println("gefeliciteerd je hebt het goed");
} else {
for (int i = 0; i < 4; i++) {
if (guess.substring(i, i + 1).equals(stringnumber.substring(i, i + 1))) {
feedback.append("+");
} else if (stringnumber.contains(guess.substring(i, i + 1))) {
feedback.append("0");
} else {
feedback.append("X");
}
}
}
System.out.println(feedback.toString());
}
}
| False | 315 | 15 | 368 | 16 | 370 | 14 | 368 | 16 | 410 | 18 | false | false | false | false | false | true |
3,349 | 7466_19 | package classes;
import java.util.Arrays;
import java.util.Scanner;
import classes.ConsoleColors;
public class Game {
ConsoleColors consolecolor = new ConsoleColors();
public static void Play(String word)
{
Scanner input = new Scanner(System.in); // antwoord van gebruiker opvangen
int rounds=1; // start vanaf ronde
int max_rounds=10; // max aantal rondes van spel sessie
char[] wordC = word.toUpperCase().toCharArray(); // Te raden woord (opsplitsen in letters)
char[] existingC = {' ',' ',' ',' ',' '}; //Bijhouden geraden letters die in het woord voorkomen maar op een andere positie
char[] solutionC = {'*','*','*','*','*'};//Bijhouden geraden oplossing, letters op juiste plaats = woord
String exit = " "; // vergelijkt met exitWord
String exitWord ="stop"; // vergelijkt met exit
boolean win=false; //Spel beëndigen wanneer het woord is geraden
boolean existingCharCheck = false; //Bijhouden of minstens een letter van andere positie werd geraden voor sysout melding
char[] inputC = new char[5]; //gebruikers input opslitsen in letters voor verdere verwerking
//Welkom bericht
//System.out.println(ConsoleColors.BLUE_BOLD + word +" \n"); //Oplossing voor programma test
System.out.println(ConsoleColors.BLUE+"\n Raad het woord bestaande uit vijf letters"+ConsoleColors.RESET);
System.out.println(ConsoleColors.BLUE_BOLD+" * * * * * \n"+ConsoleColors.RESET);
do // zolang rondes (rounds) en niet gewonnen (win)
{
// Geef antwoord in
if(rounds==1)
{
System.out.print(ConsoleColors.PURPLE_BOLD +" | Type "+ConsoleColors.YELLOW_BACKGROUND_BRIGHT+"stop"+ConsoleColors.RESET+ConsoleColors.PURPLE_BOLD+" om het spel te verlaten\n"+ConsoleColors.RESET);
System.out.print(ConsoleColors.PURPLE_BOLD +" | Start met een woord van vijf letters. Je hebt "+max_rounds+" kansen om te raden\n : "+ConsoleColors.RESET);
}
else
{
String space;
if(rounds<10) {
space=" ";
}
else{
space="";
}
System.out.print(ConsoleColors.PURPLE_BOLD +"| Kans "+space+rounds+"/"+max_rounds+" | : "+ConsoleColors.RESET);
}
String inputString = (input.nextLine().toString().toUpperCase()); // Antwoord van gebruiker opvangen
exit = inputString.toLowerCase(); // wordt verder in programma vergeleken met variabele exitWord (stopwoord) om te verlaten
// Controleer string op lengte
while (inputString.length()!=5 && !exit.equals(exitWord)){ //indien antwoord geen vijf letters en niet is gelijk aan stop woord
System.out.println(ConsoleColors.PURPLE_BOLD + " | Voer een geldig vijf letter woord in: "+ConsoleColors.RESET);
inputString = (input.nextLine().toString().toUpperCase()); // Herhaald antwoord gebruiker opvangen indien vorig anwtoord ongeldig
exit = inputString.toLowerCase();// wordt verder in programma vergeleken met variabele exitWord (stopwoord) om te verlaten
}
if(!exit.equals(exitWord))
{
// Controleer antwoord
inputC = inputString.toCharArray();
for(int i = 0;i<wordC.length;i++)
{
if(inputC[i]==wordC[i])
{
solutionC[i]=wordC[i]; //Oplossing bijhouden
}
}
// Controleer of er bestaande letters in het woord zitten op een andere plaats
for(int i = 0;i<wordC.length;i++)
{
for(int j=0;j<wordC.length;j++)
{
if(inputC[i]==wordC[j])
{
if(inputC[i]!=solutionC[j])
{
existingC[i] = inputC[i];
existingCharCheck=true; //Bijhouden of minstens een letter van andere positie geraden voor sysout melding
}
}
}
}
if(Arrays.equals(solutionC, wordC))
{
win=true; // Gewonnen, doorbreek de while loop
}
else
{
Status(inputC,solutionC);
// Bestaande letters weergeven die in het woord voorkomen
if(existingCharCheck)//indien minstens letter bestaat die in het woord voorkomt op andere plaats
{
int spaceAfterChar=0;// formatting, bijhouden hoeveel spaties nodig zijn voor achter getoonde lettes
System.out.print(ConsoleColors.YELLOW_BOLD+" Andere plaats: ");
StringBuilder existingB = new StringBuilder(); // stringbuilder om de letters bij elkaar te zetten, ontdoen van hun array positie, om lege ruimtes te voorkomen bij print
for(int i=0;i<existingC.length;i++)
{
boolean check_double=false;
if(existingC[i]!=' ')// zorgen dat er geen lege ruimte komt tussen de letters, letters bij elkaar en spaties achteraan --> formatting
{
for(int j=0;j<i;j++)
{
if(existingC[j]==existingC[i])
{
check_double=true; // controle om de dubbele letters er uit te halen
}
}
if(!check_double) {
existingB.append(existingC[i]);
existingB.append(" ");// formatting, achter elke letter een spatie
}
else
{
spaceAfterChar=spaceAfterChar+2; // formatting, maak spaties achter de getoonde letters
}
}
else // spatie naar achter zetten --> formatting
{
if(inputC[i]!=solutionC[i])
{
spaceAfterChar=spaceAfterChar+2;
}
else
{
spaceAfterChar=spaceAfterChar+2;
}
}
}
// bestaande letters van andere plaats, lijst leegmaken
for(int i=0;i<existingC.length;i++)
{
existingC[i]=' ';
}
System.out.print(existingB.toString());
// formatting: dynamisch spaties toevoegen aan de hand van de getoonde letters
for(int i=0;i<spaceAfterChar;i++) // formatting, aantal bijgehouden spaties uitprinten voor achter alle getoonde letters
{
System.out.print(" ");
}
existingCharCheck=false; // terug op false zetten om volgende letter te controleren
}
else
{
System.out.print(ConsoleColors.GREEN_BOLD +" Andere plaats: geen "+ConsoleColors.RESET); // geen letters weer te geven die op andere positie in oplossing voorkomen
}
rounds++; // Gespeelde ronde
}
}
}
while(win!=true && rounds<=max_rounds && !exit.equals(exitWord));
// Weergeven gewonnen of verloren
if(!exit.equals(exitWord)) // negeren indien gebruiker stopwoord heeft ingetypt
{
if(win)
{
Status(inputC,solutionC);
System.out.println(ConsoleColors.BLUE_BOLD +"\n\n Proficiat, je hebt het woord: "+word+" volledig geraden"+ConsoleColors.RESET);
}
else
{
System.out.println(ConsoleColors.BLUE_BOLD +"\n\n Jammer, je hebt het woord: "+word+" niet geraden"+ConsoleColors.RESET);
}
System.out.println(ConsoleColors.PURPLE_BOLD +"\n **************************************************** "+ConsoleColors.RESET);
}
}
// FUNCTIE sysout --> Reeds geraden letters weergeven van de juiste oplossing
private static void Status(char[] inputC, char[] solutionC)
{
// letters van gebruikersinvoer printen
System.out.print(ConsoleColors.GREEN_BOLD+" | "+ConsoleColors.BLACK);
for(int i=0;i<inputC.length;i++)
{
System.out.print(inputC[i]+" ");
}
// oplossing printen
System.out.print(ConsoleColors.GREEN_BOLD+" | Geraden: ");
for(int i =0;i<solutionC.length;i++)
{
System.out.print(ConsoleColors.BLUE_BOLD+solutionC[i]+" "+ConsoleColors.RESET);
}
System.out.print(ConsoleColors.GREEN_BOLD + "|"+ConsoleColors.RESET);
}
}
| kennyverheyden/SpelLingo | src/classes/Game.java | 2,575 | // wordt verder in programma vergeleken met variabele exitWord (stopwoord) om te verlaten | line_comment | nl | package classes;
import java.util.Arrays;
import java.util.Scanner;
import classes.ConsoleColors;
public class Game {
ConsoleColors consolecolor = new ConsoleColors();
public static void Play(String word)
{
Scanner input = new Scanner(System.in); // antwoord van gebruiker opvangen
int rounds=1; // start vanaf ronde
int max_rounds=10; // max aantal rondes van spel sessie
char[] wordC = word.toUpperCase().toCharArray(); // Te raden woord (opsplitsen in letters)
char[] existingC = {' ',' ',' ',' ',' '}; //Bijhouden geraden letters die in het woord voorkomen maar op een andere positie
char[] solutionC = {'*','*','*','*','*'};//Bijhouden geraden oplossing, letters op juiste plaats = woord
String exit = " "; // vergelijkt met exitWord
String exitWord ="stop"; // vergelijkt met exit
boolean win=false; //Spel beëndigen wanneer het woord is geraden
boolean existingCharCheck = false; //Bijhouden of minstens een letter van andere positie werd geraden voor sysout melding
char[] inputC = new char[5]; //gebruikers input opslitsen in letters voor verdere verwerking
//Welkom bericht
//System.out.println(ConsoleColors.BLUE_BOLD + word +" \n"); //Oplossing voor programma test
System.out.println(ConsoleColors.BLUE+"\n Raad het woord bestaande uit vijf letters"+ConsoleColors.RESET);
System.out.println(ConsoleColors.BLUE_BOLD+" * * * * * \n"+ConsoleColors.RESET);
do // zolang rondes (rounds) en niet gewonnen (win)
{
// Geef antwoord in
if(rounds==1)
{
System.out.print(ConsoleColors.PURPLE_BOLD +" | Type "+ConsoleColors.YELLOW_BACKGROUND_BRIGHT+"stop"+ConsoleColors.RESET+ConsoleColors.PURPLE_BOLD+" om het spel te verlaten\n"+ConsoleColors.RESET);
System.out.print(ConsoleColors.PURPLE_BOLD +" | Start met een woord van vijf letters. Je hebt "+max_rounds+" kansen om te raden\n : "+ConsoleColors.RESET);
}
else
{
String space;
if(rounds<10) {
space=" ";
}
else{
space="";
}
System.out.print(ConsoleColors.PURPLE_BOLD +"| Kans "+space+rounds+"/"+max_rounds+" | : "+ConsoleColors.RESET);
}
String inputString = (input.nextLine().toString().toUpperCase()); // Antwoord van gebruiker opvangen
exit = inputString.toLowerCase(); // wordt verder in programma vergeleken met variabele exitWord (stopwoord) om te verlaten
// Controleer string op lengte
while (inputString.length()!=5 && !exit.equals(exitWord)){ //indien antwoord geen vijf letters en niet is gelijk aan stop woord
System.out.println(ConsoleColors.PURPLE_BOLD + " | Voer een geldig vijf letter woord in: "+ConsoleColors.RESET);
inputString = (input.nextLine().toString().toUpperCase()); // Herhaald antwoord gebruiker opvangen indien vorig anwtoord ongeldig
exit = inputString.toLowerCase();// wordt verder<SUF>
}
if(!exit.equals(exitWord))
{
// Controleer antwoord
inputC = inputString.toCharArray();
for(int i = 0;i<wordC.length;i++)
{
if(inputC[i]==wordC[i])
{
solutionC[i]=wordC[i]; //Oplossing bijhouden
}
}
// Controleer of er bestaande letters in het woord zitten op een andere plaats
for(int i = 0;i<wordC.length;i++)
{
for(int j=0;j<wordC.length;j++)
{
if(inputC[i]==wordC[j])
{
if(inputC[i]!=solutionC[j])
{
existingC[i] = inputC[i];
existingCharCheck=true; //Bijhouden of minstens een letter van andere positie geraden voor sysout melding
}
}
}
}
if(Arrays.equals(solutionC, wordC))
{
win=true; // Gewonnen, doorbreek de while loop
}
else
{
Status(inputC,solutionC);
// Bestaande letters weergeven die in het woord voorkomen
if(existingCharCheck)//indien minstens letter bestaat die in het woord voorkomt op andere plaats
{
int spaceAfterChar=0;// formatting, bijhouden hoeveel spaties nodig zijn voor achter getoonde lettes
System.out.print(ConsoleColors.YELLOW_BOLD+" Andere plaats: ");
StringBuilder existingB = new StringBuilder(); // stringbuilder om de letters bij elkaar te zetten, ontdoen van hun array positie, om lege ruimtes te voorkomen bij print
for(int i=0;i<existingC.length;i++)
{
boolean check_double=false;
if(existingC[i]!=' ')// zorgen dat er geen lege ruimte komt tussen de letters, letters bij elkaar en spaties achteraan --> formatting
{
for(int j=0;j<i;j++)
{
if(existingC[j]==existingC[i])
{
check_double=true; // controle om de dubbele letters er uit te halen
}
}
if(!check_double) {
existingB.append(existingC[i]);
existingB.append(" ");// formatting, achter elke letter een spatie
}
else
{
spaceAfterChar=spaceAfterChar+2; // formatting, maak spaties achter de getoonde letters
}
}
else // spatie naar achter zetten --> formatting
{
if(inputC[i]!=solutionC[i])
{
spaceAfterChar=spaceAfterChar+2;
}
else
{
spaceAfterChar=spaceAfterChar+2;
}
}
}
// bestaande letters van andere plaats, lijst leegmaken
for(int i=0;i<existingC.length;i++)
{
existingC[i]=' ';
}
System.out.print(existingB.toString());
// formatting: dynamisch spaties toevoegen aan de hand van de getoonde letters
for(int i=0;i<spaceAfterChar;i++) // formatting, aantal bijgehouden spaties uitprinten voor achter alle getoonde letters
{
System.out.print(" ");
}
existingCharCheck=false; // terug op false zetten om volgende letter te controleren
}
else
{
System.out.print(ConsoleColors.GREEN_BOLD +" Andere plaats: geen "+ConsoleColors.RESET); // geen letters weer te geven die op andere positie in oplossing voorkomen
}
rounds++; // Gespeelde ronde
}
}
}
while(win!=true && rounds<=max_rounds && !exit.equals(exitWord));
// Weergeven gewonnen of verloren
if(!exit.equals(exitWord)) // negeren indien gebruiker stopwoord heeft ingetypt
{
if(win)
{
Status(inputC,solutionC);
System.out.println(ConsoleColors.BLUE_BOLD +"\n\n Proficiat, je hebt het woord: "+word+" volledig geraden"+ConsoleColors.RESET);
}
else
{
System.out.println(ConsoleColors.BLUE_BOLD +"\n\n Jammer, je hebt het woord: "+word+" niet geraden"+ConsoleColors.RESET);
}
System.out.println(ConsoleColors.PURPLE_BOLD +"\n **************************************************** "+ConsoleColors.RESET);
}
}
// FUNCTIE sysout --> Reeds geraden letters weergeven van de juiste oplossing
private static void Status(char[] inputC, char[] solutionC)
{
// letters van gebruikersinvoer printen
System.out.print(ConsoleColors.GREEN_BOLD+" | "+ConsoleColors.BLACK);
for(int i=0;i<inputC.length;i++)
{
System.out.print(inputC[i]+" ");
}
// oplossing printen
System.out.print(ConsoleColors.GREEN_BOLD+" | Geraden: ");
for(int i =0;i<solutionC.length;i++)
{
System.out.print(ConsoleColors.BLUE_BOLD+solutionC[i]+" "+ConsoleColors.RESET);
}
System.out.print(ConsoleColors.GREEN_BOLD + "|"+ConsoleColors.RESET);
}
}
| True | 2,008 | 25 | 2,364 | 28 | 2,128 | 23 | 2,364 | 28 | 3,098 | 24 | false | false | false | false | false | true |
3,551 | 81263_13 | /*******************************************************************************
* Copyright (c) 2002-2013 (c) Devon and Warren Schudy
* Copyright (c) 2014 Devon and Warren Schudy, Mike Anderson
*******************************************************************************/
package simulation;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import Rendering.GBProjection;
import sides.Side;
//Maps FinePoints to screen locations
import support.FinePoint;
public abstract class GBObject {
FinePoint position;
FinePoint velocity;
public BufferedImage image;
protected double radius;
protected double mass;
public static final double kCollisionRepulsion = 0.02;
public static final double kCollisionRepulsionSpeed = 0.1;
public static final double kMaxOverlap = 0.04;
public static final short kMaxSquareMiniSize = 4;
// Some abstract functions aren't implemented by all descendants.
// Java hates this so they were made protected and given default behavior
// here.
protected void takeDamage(double amount, Side origin) {
}
protected double takeEnergy(double amount) {
return 0;
}
protected double giveEnergy(double amount) {
return 0;
}
protected double maxTakeEnergy() {
return 0;
}
protected double maxGiveEnergy() {
return 0;
}
// high-level actions
protected void think(GBWorld world) {
} // Not everything has a brain
public abstract void act(GBWorld world); // Everything can act
protected void collideWithWall() {
}
protected void collideWith(GBObject other) {
}
protected void collectStatistics(ScoreKeeper keeper) {
}
// high-level queries
public abstract GBObjectClass getObjectClass();
public Side getOwner() {
return null;
} // food is not owned by anyone
protected double getEnergy() {
return 0;
}
protected double getInterest() {
return 0;
} // how attractive to autocamera
public String getDetails() {
return "";
}
// evil antimodular drawing code
public abstract Color getColor();
public abstract void draw(Graphics g, GBProjection proj,
boolean detailed);
public void drawUnderlay(Graphics g, GBProjection proj,
boolean detailed) {
}
public void drawOverlay(Graphics g, GBProjection proj,
boolean detailed) {
}
public GBObject next;// references the next object; allows GBObject to act
// as a singly-linked list
public GBObject(FinePoint where, double r) {
position = where;
radius = r;
velocity = new FinePoint();
mass = 0;
next = null;
}
public GBObject(FinePoint where, double r, FinePoint vel) {
position = where;
radius = r;
velocity = vel;
mass = 0;
next = null;
}
public GBObject(FinePoint where, double r, double m) {
position = where;
radius = r;
velocity = new FinePoint();
mass = m;
next = null;
}
public GBObject(FinePoint where, double r, FinePoint vel, double m) {
position = where;
radius = r;
velocity = vel;
mass = m;
next = null;
}
public FinePoint getPosition() {
return position;
}
public void setPosition(FinePoint newPosition) {
position = newPosition;
}
public void moveBy(FinePoint delta) {
position = position.add(delta);
}
public void moveBy(double deltax, double deltay) {
position.x += deltax;
position.y += deltay;
}
public double getLeft() {
return position.x - radius;
}
public double getTop() {
return position.y + radius;
}
public double getRight() {
return position.x + radius;
}
public double getBottom() {
return position.y - radius;
}
public FinePoint getVelocity() {
return velocity;
}
public double getSpeed() {
return velocity.norm();
}
public void setVelocity(double sx, double sy) {
velocity.set(sx, sy);
}
public void setSpeed(double speed) {
velocity.setNorm(speed);
}
public void accelerate(FinePoint deltav) {
velocity = velocity.add(deltav);
}
public void drag(double friction, double linearCoeff, double quadraticCoeff) {
if (velocity.isZero())
return;
double speed = getSpeed();
speed -= speed * (speed * quadraticCoeff + linearCoeff);
if (speed > friction)
setSpeed(speed - friction);
else
setVelocity(0, 0);
}
public double getRadius() {
return radius;
}
public double getMass() {
return mass;
}
public boolean intersects(GBObject other) {
double r = radius + other.radius;
return other.position.x - position.x < r
&& position.x - other.position.x < r
&& other.position.y - position.y < r
&& position.y - other.position.y < r
&& position.inRange(other.position, r);
}
public double overlapFraction(GBObject other) {
if (radius == 0)
return 0;
// returns the fraction of our radius that other overlaps
double dist = (position.subtract(other.position)).norm(); // center-to-center
// dist
dist = Math.max(radius + other.radius - dist, 0); // overlap of edges
return Math.min(dist / radius, 1.0); // don't overlap more than 1
}
public void doBasicCollide(GBObject other) {
if (intersects(other)) {
collideWith(other);
other.collideWith(this);
}
}
public void doSolidCollide(GBObject other, double coefficient) {
if (intersects(other)) {
collideWith(other);
other.collideWith(this);
doElasticBounce(other, coefficient);
}
}
public void pushBy(FinePoint impulse) {
if (mass != 0)
velocity = velocity.add(impulse.divide(mass));
}
public void pushBy(double impulse, double dir) {
pushBy(FinePoint.makePolar(impulse, dir));
}
public void push(GBObject other, double impulse) {
FinePoint cc = other.position.subtract(position); // center-to-center
if (cc.normSquare() == 0)
return; // don't push if in same location
other.pushBy(cc.divide(cc.norm()).multiply(impulse));
}
public void doElasticBounce(GBObject other, double coefficient /*
* TODO:
* substitute
* default value
* if needed: =1
*/) {
double m1 = mass;
double m2 = other.mass;
if (m1 == 0 || m2 == 0)
return; // can't bounce massless objects
FinePoint cc = other.position.subtract(position); // center-to-center
if (cc.normSquare() == 0)
cc.set(1, 0); // if in same place, pick an arbitrary cc
double dist = cc.norm();
FinePoint rv1 = velocity.projection(cc); // radial component of velocity
FinePoint rv2 = other.velocity.projection(cc);
if (velocity.dotProduct(cc) - other.velocity.dotProduct(cc) > 0) {
// if still moving closer...
FinePoint center = (rv1.multiply(m1).add(rv2.multiply(m2)))
.divide((m1 + m2)); // velocity of center-of-mass
accelerate(rv2.subtract(center).multiply(m2 * coefficient)
.divide(m1).subtract(rv1.subtract(center)));
other.accelerate(rv1.subtract(center).multiply(m1 * coefficient)
.divide(m2).subtract(rv2.subtract(center)));
}
double totalr = radius + other.radius;
double overlap = totalr - dist;
if (overlap > kMaxOverlap) {
FinePoint away1 = cc.negate().divide(dist).multiply(m2)
.divide(m1 + m2);
FinePoint away2 = cc.divide(dist).multiply(m1).divide(m1 + m2);
moveBy(away1.multiply(kCollisionRepulsionSpeed));
other.moveBy(away2.multiply(kCollisionRepulsionSpeed));
accelerate(away1.multiply(kCollisionRepulsion));
other.accelerate(away2.multiply(kCollisionRepulsion));
}
}
public void move() {
position = position.add(velocity);
}
/**
* Returns a rectangle (approximately) representing the position of the
* rendered object on the screen.
*
* @param proj
* @return
*/
protected Rectangle getScreenRect(GBProjection proj) {
int oWidth = (int) Math.max(radius * proj.getScale() * 2, 1);
return new Rectangle(proj.toScreenX(getLeft()), proj.toScreenY(getTop()), oWidth, oWidth);
}
protected Ellipse2D.Double getScreenEllipse(GBProjection proj) {
double oWidth = Math.max(radius * proj.getScale() * 2, 1);
return new Ellipse2D.Double(proj.toScreenX(getLeft()), proj.toScreenY(getTop()), oWidth, oWidth);
}
public void drawShadow(Graphics g, GBProjection proj,
FinePoint offset, Color color) {
Graphics2D g2d = (Graphics2D) g;
Ellipse2D.Double where = getScreenEllipse(proj);
int scale = proj.getScale();
where.x += offset.x * scale;
where.y -= offset.y * scale;
g2d.setPaint(color);
g2d.fill(where);
}
protected void drawImage(Graphics g, GBProjection proj) {
if (image == null)
return;
int x1 = proj.toScreenX(getLeft());
int y1 = proj.toScreenY(getTop());
int x2 = proj.toScreenX(getRight());
int y2 = proj.toScreenY(getBottom());
if (x2 - x1 < 2)
x2 = x1 + 2;
if (y2 - y1 < 2)
y2 = y1 + 2;
((Graphics2D)g).setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(image, x1, y1, x2, y2, 0, 0, image.getWidth(),
image.getHeight(), null);
}
};
| manofsteel76667/Grobots_Java | src/simulation/GBObject.java | 3,093 | // don't overlap more than 1 | line_comment | nl | /*******************************************************************************
* Copyright (c) 2002-2013 (c) Devon and Warren Schudy
* Copyright (c) 2014 Devon and Warren Schudy, Mike Anderson
*******************************************************************************/
package simulation;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import Rendering.GBProjection;
import sides.Side;
//Maps FinePoints to screen locations
import support.FinePoint;
public abstract class GBObject {
FinePoint position;
FinePoint velocity;
public BufferedImage image;
protected double radius;
protected double mass;
public static final double kCollisionRepulsion = 0.02;
public static final double kCollisionRepulsionSpeed = 0.1;
public static final double kMaxOverlap = 0.04;
public static final short kMaxSquareMiniSize = 4;
// Some abstract functions aren't implemented by all descendants.
// Java hates this so they were made protected and given default behavior
// here.
protected void takeDamage(double amount, Side origin) {
}
protected double takeEnergy(double amount) {
return 0;
}
protected double giveEnergy(double amount) {
return 0;
}
protected double maxTakeEnergy() {
return 0;
}
protected double maxGiveEnergy() {
return 0;
}
// high-level actions
protected void think(GBWorld world) {
} // Not everything has a brain
public abstract void act(GBWorld world); // Everything can act
protected void collideWithWall() {
}
protected void collideWith(GBObject other) {
}
protected void collectStatistics(ScoreKeeper keeper) {
}
// high-level queries
public abstract GBObjectClass getObjectClass();
public Side getOwner() {
return null;
} // food is not owned by anyone
protected double getEnergy() {
return 0;
}
protected double getInterest() {
return 0;
} // how attractive to autocamera
public String getDetails() {
return "";
}
// evil antimodular drawing code
public abstract Color getColor();
public abstract void draw(Graphics g, GBProjection proj,
boolean detailed);
public void drawUnderlay(Graphics g, GBProjection proj,
boolean detailed) {
}
public void drawOverlay(Graphics g, GBProjection proj,
boolean detailed) {
}
public GBObject next;// references the next object; allows GBObject to act
// as a singly-linked list
public GBObject(FinePoint where, double r) {
position = where;
radius = r;
velocity = new FinePoint();
mass = 0;
next = null;
}
public GBObject(FinePoint where, double r, FinePoint vel) {
position = where;
radius = r;
velocity = vel;
mass = 0;
next = null;
}
public GBObject(FinePoint where, double r, double m) {
position = where;
radius = r;
velocity = new FinePoint();
mass = m;
next = null;
}
public GBObject(FinePoint where, double r, FinePoint vel, double m) {
position = where;
radius = r;
velocity = vel;
mass = m;
next = null;
}
public FinePoint getPosition() {
return position;
}
public void setPosition(FinePoint newPosition) {
position = newPosition;
}
public void moveBy(FinePoint delta) {
position = position.add(delta);
}
public void moveBy(double deltax, double deltay) {
position.x += deltax;
position.y += deltay;
}
public double getLeft() {
return position.x - radius;
}
public double getTop() {
return position.y + radius;
}
public double getRight() {
return position.x + radius;
}
public double getBottom() {
return position.y - radius;
}
public FinePoint getVelocity() {
return velocity;
}
public double getSpeed() {
return velocity.norm();
}
public void setVelocity(double sx, double sy) {
velocity.set(sx, sy);
}
public void setSpeed(double speed) {
velocity.setNorm(speed);
}
public void accelerate(FinePoint deltav) {
velocity = velocity.add(deltav);
}
public void drag(double friction, double linearCoeff, double quadraticCoeff) {
if (velocity.isZero())
return;
double speed = getSpeed();
speed -= speed * (speed * quadraticCoeff + linearCoeff);
if (speed > friction)
setSpeed(speed - friction);
else
setVelocity(0, 0);
}
public double getRadius() {
return radius;
}
public double getMass() {
return mass;
}
public boolean intersects(GBObject other) {
double r = radius + other.radius;
return other.position.x - position.x < r
&& position.x - other.position.x < r
&& other.position.y - position.y < r
&& position.y - other.position.y < r
&& position.inRange(other.position, r);
}
public double overlapFraction(GBObject other) {
if (radius == 0)
return 0;
// returns the fraction of our radius that other overlaps
double dist = (position.subtract(other.position)).norm(); // center-to-center
// dist
dist = Math.max(radius + other.radius - dist, 0); // overlap of edges
return Math.min(dist / radius, 1.0); // don't overlap<SUF>
}
public void doBasicCollide(GBObject other) {
if (intersects(other)) {
collideWith(other);
other.collideWith(this);
}
}
public void doSolidCollide(GBObject other, double coefficient) {
if (intersects(other)) {
collideWith(other);
other.collideWith(this);
doElasticBounce(other, coefficient);
}
}
public void pushBy(FinePoint impulse) {
if (mass != 0)
velocity = velocity.add(impulse.divide(mass));
}
public void pushBy(double impulse, double dir) {
pushBy(FinePoint.makePolar(impulse, dir));
}
public void push(GBObject other, double impulse) {
FinePoint cc = other.position.subtract(position); // center-to-center
if (cc.normSquare() == 0)
return; // don't push if in same location
other.pushBy(cc.divide(cc.norm()).multiply(impulse));
}
public void doElasticBounce(GBObject other, double coefficient /*
* TODO:
* substitute
* default value
* if needed: =1
*/) {
double m1 = mass;
double m2 = other.mass;
if (m1 == 0 || m2 == 0)
return; // can't bounce massless objects
FinePoint cc = other.position.subtract(position); // center-to-center
if (cc.normSquare() == 0)
cc.set(1, 0); // if in same place, pick an arbitrary cc
double dist = cc.norm();
FinePoint rv1 = velocity.projection(cc); // radial component of velocity
FinePoint rv2 = other.velocity.projection(cc);
if (velocity.dotProduct(cc) - other.velocity.dotProduct(cc) > 0) {
// if still moving closer...
FinePoint center = (rv1.multiply(m1).add(rv2.multiply(m2)))
.divide((m1 + m2)); // velocity of center-of-mass
accelerate(rv2.subtract(center).multiply(m2 * coefficient)
.divide(m1).subtract(rv1.subtract(center)));
other.accelerate(rv1.subtract(center).multiply(m1 * coefficient)
.divide(m2).subtract(rv2.subtract(center)));
}
double totalr = radius + other.radius;
double overlap = totalr - dist;
if (overlap > kMaxOverlap) {
FinePoint away1 = cc.negate().divide(dist).multiply(m2)
.divide(m1 + m2);
FinePoint away2 = cc.divide(dist).multiply(m1).divide(m1 + m2);
moveBy(away1.multiply(kCollisionRepulsionSpeed));
other.moveBy(away2.multiply(kCollisionRepulsionSpeed));
accelerate(away1.multiply(kCollisionRepulsion));
other.accelerate(away2.multiply(kCollisionRepulsion));
}
}
public void move() {
position = position.add(velocity);
}
/**
* Returns a rectangle (approximately) representing the position of the
* rendered object on the screen.
*
* @param proj
* @return
*/
protected Rectangle getScreenRect(GBProjection proj) {
int oWidth = (int) Math.max(radius * proj.getScale() * 2, 1);
return new Rectangle(proj.toScreenX(getLeft()), proj.toScreenY(getTop()), oWidth, oWidth);
}
protected Ellipse2D.Double getScreenEllipse(GBProjection proj) {
double oWidth = Math.max(radius * proj.getScale() * 2, 1);
return new Ellipse2D.Double(proj.toScreenX(getLeft()), proj.toScreenY(getTop()), oWidth, oWidth);
}
public void drawShadow(Graphics g, GBProjection proj,
FinePoint offset, Color color) {
Graphics2D g2d = (Graphics2D) g;
Ellipse2D.Double where = getScreenEllipse(proj);
int scale = proj.getScale();
where.x += offset.x * scale;
where.y -= offset.y * scale;
g2d.setPaint(color);
g2d.fill(where);
}
protected void drawImage(Graphics g, GBProjection proj) {
if (image == null)
return;
int x1 = proj.toScreenX(getLeft());
int y1 = proj.toScreenY(getTop());
int x2 = proj.toScreenX(getRight());
int y2 = proj.toScreenY(getBottom());
if (x2 - x1 < 2)
x2 = x1 + 2;
if (y2 - y1 < 2)
y2 = y1 + 2;
((Graphics2D)g).setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(image, x1, y1, x2, y2, 0, 0, image.getWidth(),
image.getHeight(), null);
}
};
| False | 2,338 | 8 | 2,856 | 8 | 2,794 | 9 | 2,856 | 8 | 3,397 | 9 | false | false | false | false | false | true |
2,678 | 102990_45 | /******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. *
* This program is free software, you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.BigDecimal;
import java.sql.Timestamp;
import org.compiere.util.KeyNamePair;
/** Generated Interface for PA_DashboardContent
* @author Adempiere (generated)
* @version Release 3.7.0LTS
*/
public interface I_PA_DashboardContent
{
/** TableName=PA_DashboardContent */
public static final String Table_Name = "PA_DashboardContent";
/** AD_Table_ID=50010 */
public static final int Table_ID = MTable.getTable_ID(Table_Name);
KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name);
/** AccessLevel = 6 - System - Client
*/
BigDecimal accessLevel = BigDecimal.valueOf(6);
/** Load Meta Data */
/** Column name AD_Client_ID */
public static final String COLUMNNAME_AD_Client_ID = "AD_Client_ID";
/** Get Client.
* Client/Tenant for this installation.
*/
public int getAD_Client_ID();
/** Column name AD_Org_ID */
public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID";
/** Set Organization.
* Organizational entity within client
*/
public void setAD_Org_ID (int AD_Org_ID);
/** Get Organization.
* Organizational entity within client
*/
public int getAD_Org_ID();
/** Column name AD_Window_ID */
public static final String COLUMNNAME_AD_Window_ID = "AD_Window_ID";
/** Set Window.
* Data entry or display window
*/
public void setAD_Window_ID (int AD_Window_ID);
/** Get Window.
* Data entry or display window
*/
public int getAD_Window_ID();
public org.compiere.model.I_AD_Window getAD_Window() throws RuntimeException;
/** Column name ColumnNo */
public static final String COLUMNNAME_ColumnNo = "ColumnNo";
/** Set Column No.
* Dashboard content column number
*/
public void setColumnNo (int ColumnNo);
/** Get Column No.
* Dashboard content column number
*/
public int getColumnNo();
/** Column name Created */
public static final String COLUMNNAME_Created = "Created";
/** Get Created.
* Date this record was created
*/
public Timestamp getCreated();
/** Column name CreatedBy */
public static final String COLUMNNAME_CreatedBy = "CreatedBy";
/** Get Created By.
* User who created this records
*/
public int getCreatedBy();
/** Column name Description */
public static final String COLUMNNAME_Description = "Description";
/** Set Description.
* Optional short description of the record
*/
public void setDescription (String Description);
/** Get Description.
* Optional short description of the record
*/
public String getDescription();
/** Column name GoalDisplay */
public static final String COLUMNNAME_GoalDisplay = "GoalDisplay";
/** Set Goal Display.
* Type of goal display on dashboard
*/
public void setGoalDisplay (String GoalDisplay);
/** Get Goal Display.
* Type of goal display on dashboard
*/
public String getGoalDisplay();
/** Column name HTML */
public static final String COLUMNNAME_HTML = "HTML";
/** Set HTML */
public void setHTML (String HTML);
/** Get HTML */
public String getHTML();
/** Column name IsActive */
public static final String COLUMNNAME_IsActive = "IsActive";
/** Set Active.
* The record is active in the system
*/
public void setIsActive (boolean IsActive);
/** Get Active.
* The record is active in the system
*/
public boolean isActive();
/** Column name IsCollapsible */
public static final String COLUMNNAME_IsCollapsible = "IsCollapsible";
/** Set Collapsible.
* Flag to indicate the state of the dashboard panel
*/
public void setIsCollapsible (boolean IsCollapsible);
/** Get Collapsible.
* Flag to indicate the state of the dashboard panel
*/
public boolean isCollapsible();
/** Column name IsOpenByDefault */
public static final String COLUMNNAME_IsOpenByDefault = "IsOpenByDefault";
/** Set Open By Default */
public void setIsOpenByDefault (boolean IsOpenByDefault);
/** Get Open By Default */
public boolean isOpenByDefault();
/** Column name Line */
public static final String COLUMNNAME_Line = "Line";
/** Set Line No.
* Unique line for this document
*/
public void setLine (BigDecimal Line);
/** Get Line No.
* Unique line for this document
*/
public BigDecimal getLine();
/** Column name Name */
public static final String COLUMNNAME_Name = "Name";
/** Set Name.
* Alphanumeric identifier of the entity
*/
public void setName (String Name);
/** Get Name.
* Alphanumeric identifier of the entity
*/
public String getName();
/** Column name PA_DashboardContent_ID */
public static final String COLUMNNAME_PA_DashboardContent_ID = "PA_DashboardContent_ID";
/** Set Dashboard Content */
public void setPA_DashboardContent_ID (int PA_DashboardContent_ID);
/** Get Dashboard Content */
public int getPA_DashboardContent_ID();
/** Column name PA_Goal_ID */
public static final String COLUMNNAME_PA_Goal_ID = "PA_Goal_ID";
/** Set Goal.
* Performance Goal
*/
public void setPA_Goal_ID (int PA_Goal_ID);
/** Get Goal.
* Performance Goal
*/
public int getPA_Goal_ID();
public org.compiere.model.I_PA_Goal getPA_Goal() throws RuntimeException;
/** Column name Updated */
public static final String COLUMNNAME_Updated = "Updated";
/** Get Updated.
* Date this record was updated
*/
public Timestamp getUpdated();
/** Column name UpdatedBy */
public static final String COLUMNNAME_UpdatedBy = "UpdatedBy";
/** Get Updated By.
* User who updated this records
*/
public int getUpdatedBy();
/** Column name ZulFilePath */
public static final String COLUMNNAME_ZulFilePath = "ZulFilePath";
/** Set ZUL File Path.
* Absolute path to zul file
*/
public void setZulFilePath (String ZulFilePath);
/** Get ZUL File Path.
* Absolute path to zul file
*/
public String getZulFilePath();
}
| erpcya/adempiere_370_Fork | base/src/org/compiere/model/I_PA_DashboardContent.java | 2,164 | /** Get Dashboard Content */ | block_comment | nl | /******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. *
* This program is free software, you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.BigDecimal;
import java.sql.Timestamp;
import org.compiere.util.KeyNamePair;
/** Generated Interface for PA_DashboardContent
* @author Adempiere (generated)
* @version Release 3.7.0LTS
*/
public interface I_PA_DashboardContent
{
/** TableName=PA_DashboardContent */
public static final String Table_Name = "PA_DashboardContent";
/** AD_Table_ID=50010 */
public static final int Table_ID = MTable.getTable_ID(Table_Name);
KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name);
/** AccessLevel = 6 - System - Client
*/
BigDecimal accessLevel = BigDecimal.valueOf(6);
/** Load Meta Data */
/** Column name AD_Client_ID */
public static final String COLUMNNAME_AD_Client_ID = "AD_Client_ID";
/** Get Client.
* Client/Tenant for this installation.
*/
public int getAD_Client_ID();
/** Column name AD_Org_ID */
public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID";
/** Set Organization.
* Organizational entity within client
*/
public void setAD_Org_ID (int AD_Org_ID);
/** Get Organization.
* Organizational entity within client
*/
public int getAD_Org_ID();
/** Column name AD_Window_ID */
public static final String COLUMNNAME_AD_Window_ID = "AD_Window_ID";
/** Set Window.
* Data entry or display window
*/
public void setAD_Window_ID (int AD_Window_ID);
/** Get Window.
* Data entry or display window
*/
public int getAD_Window_ID();
public org.compiere.model.I_AD_Window getAD_Window() throws RuntimeException;
/** Column name ColumnNo */
public static final String COLUMNNAME_ColumnNo = "ColumnNo";
/** Set Column No.
* Dashboard content column number
*/
public void setColumnNo (int ColumnNo);
/** Get Column No.
* Dashboard content column number
*/
public int getColumnNo();
/** Column name Created */
public static final String COLUMNNAME_Created = "Created";
/** Get Created.
* Date this record was created
*/
public Timestamp getCreated();
/** Column name CreatedBy */
public static final String COLUMNNAME_CreatedBy = "CreatedBy";
/** Get Created By.
* User who created this records
*/
public int getCreatedBy();
/** Column name Description */
public static final String COLUMNNAME_Description = "Description";
/** Set Description.
* Optional short description of the record
*/
public void setDescription (String Description);
/** Get Description.
* Optional short description of the record
*/
public String getDescription();
/** Column name GoalDisplay */
public static final String COLUMNNAME_GoalDisplay = "GoalDisplay";
/** Set Goal Display.
* Type of goal display on dashboard
*/
public void setGoalDisplay (String GoalDisplay);
/** Get Goal Display.
* Type of goal display on dashboard
*/
public String getGoalDisplay();
/** Column name HTML */
public static final String COLUMNNAME_HTML = "HTML";
/** Set HTML */
public void setHTML (String HTML);
/** Get HTML */
public String getHTML();
/** Column name IsActive */
public static final String COLUMNNAME_IsActive = "IsActive";
/** Set Active.
* The record is active in the system
*/
public void setIsActive (boolean IsActive);
/** Get Active.
* The record is active in the system
*/
public boolean isActive();
/** Column name IsCollapsible */
public static final String COLUMNNAME_IsCollapsible = "IsCollapsible";
/** Set Collapsible.
* Flag to indicate the state of the dashboard panel
*/
public void setIsCollapsible (boolean IsCollapsible);
/** Get Collapsible.
* Flag to indicate the state of the dashboard panel
*/
public boolean isCollapsible();
/** Column name IsOpenByDefault */
public static final String COLUMNNAME_IsOpenByDefault = "IsOpenByDefault";
/** Set Open By Default */
public void setIsOpenByDefault (boolean IsOpenByDefault);
/** Get Open By Default */
public boolean isOpenByDefault();
/** Column name Line */
public static final String COLUMNNAME_Line = "Line";
/** Set Line No.
* Unique line for this document
*/
public void setLine (BigDecimal Line);
/** Get Line No.
* Unique line for this document
*/
public BigDecimal getLine();
/** Column name Name */
public static final String COLUMNNAME_Name = "Name";
/** Set Name.
* Alphanumeric identifier of the entity
*/
public void setName (String Name);
/** Get Name.
* Alphanumeric identifier of the entity
*/
public String getName();
/** Column name PA_DashboardContent_ID */
public static final String COLUMNNAME_PA_DashboardContent_ID = "PA_DashboardContent_ID";
/** Set Dashboard Content */
public void setPA_DashboardContent_ID (int PA_DashboardContent_ID);
/** Get Dashboard Content<SUF>*/
public int getPA_DashboardContent_ID();
/** Column name PA_Goal_ID */
public static final String COLUMNNAME_PA_Goal_ID = "PA_Goal_ID";
/** Set Goal.
* Performance Goal
*/
public void setPA_Goal_ID (int PA_Goal_ID);
/** Get Goal.
* Performance Goal
*/
public int getPA_Goal_ID();
public org.compiere.model.I_PA_Goal getPA_Goal() throws RuntimeException;
/** Column name Updated */
public static final String COLUMNNAME_Updated = "Updated";
/** Get Updated.
* Date this record was updated
*/
public Timestamp getUpdated();
/** Column name UpdatedBy */
public static final String COLUMNNAME_UpdatedBy = "UpdatedBy";
/** Get Updated By.
* User who updated this records
*/
public int getUpdatedBy();
/** Column name ZulFilePath */
public static final String COLUMNNAME_ZulFilePath = "ZulFilePath";
/** Set ZUL File Path.
* Absolute path to zul file
*/
public void setZulFilePath (String ZulFilePath);
/** Get ZUL File Path.
* Absolute path to zul file
*/
public String getZulFilePath();
}
| False | 1,649 | 6 | 1,825 | 6 | 1,974 | 7 | 1,825 | 6 | 2,240 | 9 | false | false | false | false | false | true |
1,235 | 83873_6 | package be.kuleuven.candycrush;
import java.util.*;
import java.util.function.Function;
public class Board<T> {
private volatile Map<Position,T> map;
private volatile Map<T, List<Position>> reverseMap;
private volatile BoardSize boardsize;
public Board(BoardSize boardsize){
this.boardsize = boardsize;
map = new HashMap<>(boardsize.columns()* boardsize.rows());//map for your cells content
reverseMap = new HashMap<>(boardsize.columns()* boardsize.rows());
}
public BoardSize getBoardsize(){
return boardsize;
}
public synchronized T getCellAt(Position position){//om de cel op een gegeven positie van het bord op te vragen.
return this.map.get(position);
//return typeList.get(position.toIndex());
}
public synchronized void replaceCellAt(Position position, T newCell) {
T oldCellContent = map.get(position);
map.put(position, newCell);
List<Position> positions = reverseMap.get(oldCellContent);
if (positions != null) {
positions.remove(position);
if (positions.isEmpty()) {
reverseMap.remove(oldCellContent);
}
}
reverseMap.computeIfAbsent(newCell, k -> new ArrayList<>()).add(position);
}
public synchronized void fill(Function<Position, T> cellCreator){//om het hele bord te vullen. De fill-functie heeft als parameter een Function-object (cellCreator) die, gegeven een Positie-object, een nieuw cel-object teruggeeft.
map.clear();
reverseMap.clear();
// Clear the map first
for (int i = 0; i < this.boardsize.columns()*this.boardsize.rows(); i++){
// For every position put a random candy using cellCreator
Position positionIndex = Position.fromIndex(i,this.boardsize);
T cellContent = cellCreator.apply(positionIndex);
map.put(positionIndex, cellContent);
reverseMap.computeIfAbsent(cellContent, k -> new ArrayList<>()).add(positionIndex);
}
}
public synchronized void copyTo(Board<T> otherBoard)
{ // Die alle cellen van het huidige bord kopieert naar het meegegeven bord. Als het meegegeven bord niet dezelfde afmetingen heeft, gooit het een exception.
// Gooi exception als het lukt
if(!Objects.equals(boardsize.columns(), otherBoard.boardsize.columns()) && !Objects.equals(boardsize.rows(), otherBoard.boardsize.rows()))
{
throw new IllegalArgumentException("De boardsizes komen niet overeen.\r\nFunction -> copyTo");
}
else
{
for (Map.Entry<Position, T> entry : map.entrySet()) {
Position position = entry.getKey();
T value = entry.getValue();
otherBoard.map.put(new Position(position.rowOfIndex(), position.colOfIndex(), otherBoard.boardsize), value);
}
}
}
// Methode om alle posities van een element (cel) op te halen
public synchronized List<Position> getPositionsOfElement(T element) {
return reverseMap.getOrDefault(element, Collections.emptyList());
}
public void emptyBoard(){
map.clear();
}
} | OforiDarren/Candy_Crush_repo | candycrush/src/main/java/be/kuleuven/candycrush/Board.java | 885 | // Gooi exception als het lukt | line_comment | nl | package be.kuleuven.candycrush;
import java.util.*;
import java.util.function.Function;
public class Board<T> {
private volatile Map<Position,T> map;
private volatile Map<T, List<Position>> reverseMap;
private volatile BoardSize boardsize;
public Board(BoardSize boardsize){
this.boardsize = boardsize;
map = new HashMap<>(boardsize.columns()* boardsize.rows());//map for your cells content
reverseMap = new HashMap<>(boardsize.columns()* boardsize.rows());
}
public BoardSize getBoardsize(){
return boardsize;
}
public synchronized T getCellAt(Position position){//om de cel op een gegeven positie van het bord op te vragen.
return this.map.get(position);
//return typeList.get(position.toIndex());
}
public synchronized void replaceCellAt(Position position, T newCell) {
T oldCellContent = map.get(position);
map.put(position, newCell);
List<Position> positions = reverseMap.get(oldCellContent);
if (positions != null) {
positions.remove(position);
if (positions.isEmpty()) {
reverseMap.remove(oldCellContent);
}
}
reverseMap.computeIfAbsent(newCell, k -> new ArrayList<>()).add(position);
}
public synchronized void fill(Function<Position, T> cellCreator){//om het hele bord te vullen. De fill-functie heeft als parameter een Function-object (cellCreator) die, gegeven een Positie-object, een nieuw cel-object teruggeeft.
map.clear();
reverseMap.clear();
// Clear the map first
for (int i = 0; i < this.boardsize.columns()*this.boardsize.rows(); i++){
// For every position put a random candy using cellCreator
Position positionIndex = Position.fromIndex(i,this.boardsize);
T cellContent = cellCreator.apply(positionIndex);
map.put(positionIndex, cellContent);
reverseMap.computeIfAbsent(cellContent, k -> new ArrayList<>()).add(positionIndex);
}
}
public synchronized void copyTo(Board<T> otherBoard)
{ // Die alle cellen van het huidige bord kopieert naar het meegegeven bord. Als het meegegeven bord niet dezelfde afmetingen heeft, gooit het een exception.
// Gooi exception<SUF>
if(!Objects.equals(boardsize.columns(), otherBoard.boardsize.columns()) && !Objects.equals(boardsize.rows(), otherBoard.boardsize.rows()))
{
throw new IllegalArgumentException("De boardsizes komen niet overeen.\r\nFunction -> copyTo");
}
else
{
for (Map.Entry<Position, T> entry : map.entrySet()) {
Position position = entry.getKey();
T value = entry.getValue();
otherBoard.map.put(new Position(position.rowOfIndex(), position.colOfIndex(), otherBoard.boardsize), value);
}
}
}
// Methode om alle posities van een element (cel) op te halen
public synchronized List<Position> getPositionsOfElement(T element) {
return reverseMap.getOrDefault(element, Collections.emptyList());
}
public void emptyBoard(){
map.clear();
}
} | True | 687 | 9 | 793 | 10 | 812 | 8 | 793 | 10 | 872 | 8 | false | false | false | false | false | true |
2,874 | 5253_19 | package com.thealgorithms.io;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Mimics the actions of the Original buffered reader
* implements other actions, such as peek(n) to lookahead,
* block() to read a chunk of size {BUFFER SIZE}
* <p>
* Author: Kumaraswamy B.G (Xoma Dev)
*/
public class BufferedReader {
private static final int DEFAULT_BUFFER_SIZE = 5;
/**
* The maximum number of bytes the buffer can hold.
* Value is changed when encountered Eof to not
* cause overflow read of 0 bytes
*/
private int bufferSize;
private final byte[] buffer;
/**
* posRead -> indicates the next byte to read
*/
private int posRead = 0, bufferPos = 0;
private boolean foundEof = false;
private InputStream input;
public BufferedReader(byte[] input) throws IOException {
this(new ByteArrayInputStream(input));
}
public BufferedReader(InputStream input) throws IOException {
this(input, DEFAULT_BUFFER_SIZE);
}
public BufferedReader(InputStream input, int bufferSize) throws IOException {
this.input = input;
if (input.available() == -1) throw new IOException("Empty or already closed stream provided");
this.bufferSize = bufferSize;
buffer = new byte[bufferSize];
}
/**
* Reads a single byte from the stream
*/
public int read() throws IOException {
if (needsRefill()) {
if (foundEof) return -1;
// the buffer is empty, or the buffer has
// been completely read and needs to be refilled
refill();
}
return buffer[posRead++] & 0xff; // read and un-sign it
}
/**
* Number of bytes not yet been read
*/
public int available() throws IOException {
int available = input.available();
if (needsRefill())
// since the block is already empty,
// we have no responsibility yet
return available;
return bufferPos - posRead + available;
}
/**
* Returns the next character
*/
public int peek() throws IOException {
return peek(1);
}
/**
* Peeks and returns a value located at next {n}
*/
public int peek(int n) throws IOException {
int available = available();
if (n >= available) throw new IOException("Out of range, available %d, but trying with %d".formatted(available, n));
pushRefreshData();
if (n >= bufferSize) throw new IllegalAccessError("Cannot peek %s, maximum upto %s (Buffer Limit)".formatted(n, bufferSize));
return buffer[n];
}
/**
* Removes the already read bytes from the buffer
* in-order to make space for new bytes to be filled up.
* <p>
* This may also do the job to read first time data (the whole buffer is empty)
*/
private void pushRefreshData() throws IOException {
for (int i = posRead, j = 0; i < bufferSize; i++, j++) buffer[j] = buffer[i];
bufferPos -= posRead;
posRead = 0;
// fill out the spaces that we've
// emptied
justRefill();
}
/**
* Reads one complete block of size {bufferSize}
* if found eof, the total length of an array will
* be that of what's available
*
* @return a completed block
*/
public byte[] readBlock() throws IOException {
pushRefreshData();
byte[] cloned = new byte[bufferSize];
// arraycopy() function is better than clone()
if (bufferPos >= 0)
System.arraycopy(buffer, 0, cloned, 0,
// important to note that, bufferSize does not stay constant
// once the class is defined. See justRefill() function
bufferSize);
// we assume that already a chunk
// has been read
refill();
return cloned;
}
private boolean needsRefill() {
return bufferPos == 0 || posRead == bufferSize;
}
private void refill() throws IOException {
posRead = 0;
bufferPos = 0;
justRefill();
}
private void justRefill() throws IOException {
assertStreamOpen();
// try to fill in the maximum we can until
// we reach EOF
while (bufferPos < bufferSize) {
int read = input.read();
if (read == -1) {
// reached end-of-file, no more data left
// to be read
foundEof = true;
// rewrite the BUFFER_SIZE, to know that we've reached
// EOF when requested refill
bufferSize = bufferPos;
}
buffer[bufferPos++] = (byte) read;
}
}
private void assertStreamOpen() {
if (input == null) throw new IllegalStateException("Input Stream already closed!");
}
public void close() throws IOException {
if (input != null) {
try {
input.close();
} finally {
input = null;
}
}
}
}
| gutmox/AlgorithmsInJava | src/main/java/com/thealgorithms/io/BufferedReader.java | 1,358 | // has been read | line_comment | nl | package com.thealgorithms.io;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Mimics the actions of the Original buffered reader
* implements other actions, such as peek(n) to lookahead,
* block() to read a chunk of size {BUFFER SIZE}
* <p>
* Author: Kumaraswamy B.G (Xoma Dev)
*/
public class BufferedReader {
private static final int DEFAULT_BUFFER_SIZE = 5;
/**
* The maximum number of bytes the buffer can hold.
* Value is changed when encountered Eof to not
* cause overflow read of 0 bytes
*/
private int bufferSize;
private final byte[] buffer;
/**
* posRead -> indicates the next byte to read
*/
private int posRead = 0, bufferPos = 0;
private boolean foundEof = false;
private InputStream input;
public BufferedReader(byte[] input) throws IOException {
this(new ByteArrayInputStream(input));
}
public BufferedReader(InputStream input) throws IOException {
this(input, DEFAULT_BUFFER_SIZE);
}
public BufferedReader(InputStream input, int bufferSize) throws IOException {
this.input = input;
if (input.available() == -1) throw new IOException("Empty or already closed stream provided");
this.bufferSize = bufferSize;
buffer = new byte[bufferSize];
}
/**
* Reads a single byte from the stream
*/
public int read() throws IOException {
if (needsRefill()) {
if (foundEof) return -1;
// the buffer is empty, or the buffer has
// been completely read and needs to be refilled
refill();
}
return buffer[posRead++] & 0xff; // read and un-sign it
}
/**
* Number of bytes not yet been read
*/
public int available() throws IOException {
int available = input.available();
if (needsRefill())
// since the block is already empty,
// we have no responsibility yet
return available;
return bufferPos - posRead + available;
}
/**
* Returns the next character
*/
public int peek() throws IOException {
return peek(1);
}
/**
* Peeks and returns a value located at next {n}
*/
public int peek(int n) throws IOException {
int available = available();
if (n >= available) throw new IOException("Out of range, available %d, but trying with %d".formatted(available, n));
pushRefreshData();
if (n >= bufferSize) throw new IllegalAccessError("Cannot peek %s, maximum upto %s (Buffer Limit)".formatted(n, bufferSize));
return buffer[n];
}
/**
* Removes the already read bytes from the buffer
* in-order to make space for new bytes to be filled up.
* <p>
* This may also do the job to read first time data (the whole buffer is empty)
*/
private void pushRefreshData() throws IOException {
for (int i = posRead, j = 0; i < bufferSize; i++, j++) buffer[j] = buffer[i];
bufferPos -= posRead;
posRead = 0;
// fill out the spaces that we've
// emptied
justRefill();
}
/**
* Reads one complete block of size {bufferSize}
* if found eof, the total length of an array will
* be that of what's available
*
* @return a completed block
*/
public byte[] readBlock() throws IOException {
pushRefreshData();
byte[] cloned = new byte[bufferSize];
// arraycopy() function is better than clone()
if (bufferPos >= 0)
System.arraycopy(buffer, 0, cloned, 0,
// important to note that, bufferSize does not stay constant
// once the class is defined. See justRefill() function
bufferSize);
// we assume that already a chunk
// has been<SUF>
refill();
return cloned;
}
private boolean needsRefill() {
return bufferPos == 0 || posRead == bufferSize;
}
private void refill() throws IOException {
posRead = 0;
bufferPos = 0;
justRefill();
}
private void justRefill() throws IOException {
assertStreamOpen();
// try to fill in the maximum we can until
// we reach EOF
while (bufferPos < bufferSize) {
int read = input.read();
if (read == -1) {
// reached end-of-file, no more data left
// to be read
foundEof = true;
// rewrite the BUFFER_SIZE, to know that we've reached
// EOF when requested refill
bufferSize = bufferPos;
}
buffer[bufferPos++] = (byte) read;
}
}
private void assertStreamOpen() {
if (input == null) throw new IllegalStateException("Input Stream already closed!");
}
public void close() throws IOException {
if (input != null) {
try {
input.close();
} finally {
input = null;
}
}
}
}
| False | 1,116 | 4 | 1,154 | 4 | 1,295 | 4 | 1,154 | 4 | 1,379 | 4 | false | false | false | false | false | true |
1,882 | 32612_1 | package data;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.event.*;
public class GameLogic {
private int clickCount = 0; // Begin state
private int pairsMatched = 0;
private MainButton firstClickedButton = null;
private List<Integer> number = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8));
private String[] imagePaths = {
"data/images/apple.png", "data/images/avocado.png", "data/images/banana.png", "data/images/genipe.png",
"data/images/mandarin.png", "data/images/orange.png", "data/images/pumpkin.png", "data/images/watermelon.png"
};
private JPanel panel;
public GameLogic(JPanel panel) {
this.panel = panel;
Collections.shuffle(number);
initializeButtons();
}
private void initializeButtons() {
// Begin state voor de buttons
for (int buttonAmount = 0; buttonAmount < 16; buttonAmount++) {
int imageCount = number.get(buttonAmount) - 1;
MainButton button = new MainButton();
button.setFruitImage(imagePaths[imageCount]);
button.setName(Integer.toString(buttonAmount));
panel.add(button);
button.addActionListener(ac);
}
}
public void resetGame() {
clickCount = 0; // Begin state
pairsMatched = 0;
number.clear();
number.addAll(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8));
Collections.shuffle(number);
panel.removeAll();
initializeButtons();
panel.revalidate();
panel.repaint();
}
ActionListener ac = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
clickCount++;
System.out.println(clickCount);
MainButton button = (MainButton)e.getSource();
if (clickCount == 1) {
firstClickedButton = button;
button.setBgImage(button.getFruitImage());
}
if (clickCount == 2) {
button.setBgImage(button.getFruitImage());
if (firstClickedButton != button && button.getFruitImage().equals(firstClickedButton.getFruitImage())) {
// Als zee gelijk zijn worden de buttens gedisabled.
System.out.println("Dit klopt");
button.setEnabled(false);
firstClickedButton.setEnabled(false);
pairsMatched++;
if (pairsMatched == 8) { // Als alles gelijk is krijg je een succes message en word de game gereset.
JOptionPane.showMessageDialog(panel, "You won!");
resetGame();
}
clickCount = 0; // reset the clickcount als het 2 is
firstClickedButton = null;
} else {
// Timer met 2 sec delay
Timer t = new Timer(1000, event -> {
System.out.println("Dit klopt niet");
firstClickedButton.setBgImage(null);
button.setBgImage(null);
clickCount = 0;
firstClickedButton = null;
});
t.start();
t.setRepeats(false); // Zorgt ervoor dat de timer maar een keer word uitgevoerd
}
}
}
};
} | Woaby/Memory-game-java | data/GameLogic.java | 1,055 | // Als zee gelijk zijn worden de buttens gedisabled. | line_comment | nl | package data;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.event.*;
public class GameLogic {
private int clickCount = 0; // Begin state
private int pairsMatched = 0;
private MainButton firstClickedButton = null;
private List<Integer> number = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8));
private String[] imagePaths = {
"data/images/apple.png", "data/images/avocado.png", "data/images/banana.png", "data/images/genipe.png",
"data/images/mandarin.png", "data/images/orange.png", "data/images/pumpkin.png", "data/images/watermelon.png"
};
private JPanel panel;
public GameLogic(JPanel panel) {
this.panel = panel;
Collections.shuffle(number);
initializeButtons();
}
private void initializeButtons() {
// Begin state voor de buttons
for (int buttonAmount = 0; buttonAmount < 16; buttonAmount++) {
int imageCount = number.get(buttonAmount) - 1;
MainButton button = new MainButton();
button.setFruitImage(imagePaths[imageCount]);
button.setName(Integer.toString(buttonAmount));
panel.add(button);
button.addActionListener(ac);
}
}
public void resetGame() {
clickCount = 0; // Begin state
pairsMatched = 0;
number.clear();
number.addAll(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8));
Collections.shuffle(number);
panel.removeAll();
initializeButtons();
panel.revalidate();
panel.repaint();
}
ActionListener ac = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
clickCount++;
System.out.println(clickCount);
MainButton button = (MainButton)e.getSource();
if (clickCount == 1) {
firstClickedButton = button;
button.setBgImage(button.getFruitImage());
}
if (clickCount == 2) {
button.setBgImage(button.getFruitImage());
if (firstClickedButton != button && button.getFruitImage().equals(firstClickedButton.getFruitImage())) {
// Als zee<SUF>
System.out.println("Dit klopt");
button.setEnabled(false);
firstClickedButton.setEnabled(false);
pairsMatched++;
if (pairsMatched == 8) { // Als alles gelijk is krijg je een succes message en word de game gereset.
JOptionPane.showMessageDialog(panel, "You won!");
resetGame();
}
clickCount = 0; // reset the clickcount als het 2 is
firstClickedButton = null;
} else {
// Timer met 2 sec delay
Timer t = new Timer(1000, event -> {
System.out.println("Dit klopt niet");
firstClickedButton.setBgImage(null);
button.setBgImage(null);
clickCount = 0;
firstClickedButton = null;
});
t.start();
t.setRepeats(false); // Zorgt ervoor dat de timer maar een keer word uitgevoerd
}
}
}
};
} | True | 789 | 15 | 885 | 15 | 939 | 13 | 885 | 15 | 1,065 | 16 | false | false | false | false | false | true |
4,282 | 34059_1 | /**_x000D_
* LICENSE INFORMATION_x000D_
* _x000D_
* Copyright 2005-2008 by FZI (http://www.fzi.de). Licensed under a BSD license_x000D_
* (http://www.opensource.org/licenses/bsd-license.php) <OWNER> = Max Völkel_x000D_
* <ORGANIZATION> = FZI Forschungszentrum Informatik Karlsruhe, Karlsruhe,_x000D_
* Germany <YEAR> = 2010_x000D_
* _x000D_
* Further project information at http://semanticweb.org/wiki/RDF2Go_x000D_
*/_x000D_
_x000D_
package org.ontoware.rdf2go.model;_x000D_
_x000D_
import org.ontoware.aifbcommons.collection.ClosableIterator;_x000D_
import org.ontoware.rdf2go.exception.ModelRuntimeException;_x000D_
import org.ontoware.rdf2go.model.node.NodeOrVariable;_x000D_
import org.ontoware.rdf2go.model.node.ResourceOrVariable;_x000D_
import org.ontoware.rdf2go.model.node.UriOrVariable;_x000D_
_x000D_
_x000D_
/**_x000D_
* _x000D_
* @author voelkel_x000D_
*/_x000D_
public interface FindableModelSet {_x000D_
_x000D_
/**_x000D_
* Search across all existing models_x000D_
* _x000D_
* @param contextURI_x000D_
* @param subject_x000D_
* @param predicate_x000D_
* @param object_x000D_
* @return all matching statements in all models_x000D_
* @throws ModelRuntimeException_x000D_
*/_x000D_
ClosableIterator<Statement> findStatements(UriOrVariable contextURI,_x000D_
ResourceOrVariable subject, UriOrVariable predicate, NodeOrVariable object)_x000D_
throws ModelRuntimeException;_x000D_
_x000D_
/**_x000D_
* Search across all existing models_x000D_
* _x000D_
* @param pattern_x000D_
* @return all statements matching the quad pattern_x000D_
* @throws ModelRuntimeException_x000D_
*/_x000D_
ClosableIterator<Statement> findStatements(QuadPattern pattern) throws ModelRuntimeException;_x000D_
_x000D_
/**_x000D_
* @param contextURI_x000D_
* @param subject_x000D_
* @param predicate_x000D_
* @param object_x000D_
* @return true, if a Model named 'contextURI' contains the statement_x000D_
* (s,p,o)_x000D_
* @throws ModelRuntimeException_x000D_
*/_x000D_
boolean containsStatements(UriOrVariable contextURI, ResourceOrVariable subject,_x000D_
UriOrVariable predicate, NodeOrVariable object) throws ModelRuntimeException;_x000D_
_x000D_
/**_x000D_
* @param s a Statement_x000D_
* @return true if the modelset contains a model with context s.getContext()_x000D_
* which contains the statement s. If the context is null, the_x000D_
* default graph is checked._x000D_
* @throws ModelRuntimeException_x000D_
*/_x000D_
boolean contains(Statement s) throws ModelRuntimeException;_x000D_
_x000D_
/**_x000D_
* @param pattern_x000D_
* @return the number of statements matchingthe pattern. This is for all_x000D_
* graphs matching the context of the pattern (this is none, one or_x000D_
* all graphs). In matching graphs the number of matching statements_x000D_
* is accumulated and returned._x000D_
* @throws ModelRuntimeException_x000D_
*/_x000D_
long countStatements(QuadPattern pattern) throws ModelRuntimeException;_x000D_
_x000D_
/**_x000D_
* @param context_x000D_
* @param subject_x000D_
* @param predicate_x000D_
* @param object_x000D_
* @return a QuadPattern_x000D_
*/_x000D_
QuadPattern createQuadPattern(UriOrVariable context, ResourceOrVariable subject,_x000D_
UriOrVariable predicate, NodeOrVariable object);_x000D_
_x000D_
}_x000D_
| semweb4j/semweb4j | org.semweb4j.rdf2go.api/src/main/java/org/ontoware/rdf2go/model/FindableModelSet.java | 895 | /**_x000D_
* _x000D_
* @author voelkel_x000D_
*/ | block_comment | nl | /**_x000D_
* LICENSE INFORMATION_x000D_
* _x000D_
* Copyright 2005-2008 by FZI (http://www.fzi.de). Licensed under a BSD license_x000D_
* (http://www.opensource.org/licenses/bsd-license.php) <OWNER> = Max Völkel_x000D_
* <ORGANIZATION> = FZI Forschungszentrum Informatik Karlsruhe, Karlsruhe,_x000D_
* Germany <YEAR> = 2010_x000D_
* _x000D_
* Further project information at http://semanticweb.org/wiki/RDF2Go_x000D_
*/_x000D_
_x000D_
package org.ontoware.rdf2go.model;_x000D_
_x000D_
import org.ontoware.aifbcommons.collection.ClosableIterator;_x000D_
import org.ontoware.rdf2go.exception.ModelRuntimeException;_x000D_
import org.ontoware.rdf2go.model.node.NodeOrVariable;_x000D_
import org.ontoware.rdf2go.model.node.ResourceOrVariable;_x000D_
import org.ontoware.rdf2go.model.node.UriOrVariable;_x000D_
_x000D_
_x000D_
/**_x000D_
* _x000D_
* @author voelkel_x000D_
<SUF>*/_x000D_
public interface FindableModelSet {_x000D_
_x000D_
/**_x000D_
* Search across all existing models_x000D_
* _x000D_
* @param contextURI_x000D_
* @param subject_x000D_
* @param predicate_x000D_
* @param object_x000D_
* @return all matching statements in all models_x000D_
* @throws ModelRuntimeException_x000D_
*/_x000D_
ClosableIterator<Statement> findStatements(UriOrVariable contextURI,_x000D_
ResourceOrVariable subject, UriOrVariable predicate, NodeOrVariable object)_x000D_
throws ModelRuntimeException;_x000D_
_x000D_
/**_x000D_
* Search across all existing models_x000D_
* _x000D_
* @param pattern_x000D_
* @return all statements matching the quad pattern_x000D_
* @throws ModelRuntimeException_x000D_
*/_x000D_
ClosableIterator<Statement> findStatements(QuadPattern pattern) throws ModelRuntimeException;_x000D_
_x000D_
/**_x000D_
* @param contextURI_x000D_
* @param subject_x000D_
* @param predicate_x000D_
* @param object_x000D_
* @return true, if a Model named 'contextURI' contains the statement_x000D_
* (s,p,o)_x000D_
* @throws ModelRuntimeException_x000D_
*/_x000D_
boolean containsStatements(UriOrVariable contextURI, ResourceOrVariable subject,_x000D_
UriOrVariable predicate, NodeOrVariable object) throws ModelRuntimeException;_x000D_
_x000D_
/**_x000D_
* @param s a Statement_x000D_
* @return true if the modelset contains a model with context s.getContext()_x000D_
* which contains the statement s. If the context is null, the_x000D_
* default graph is checked._x000D_
* @throws ModelRuntimeException_x000D_
*/_x000D_
boolean contains(Statement s) throws ModelRuntimeException;_x000D_
_x000D_
/**_x000D_
* @param pattern_x000D_
* @return the number of statements matchingthe pattern. This is for all_x000D_
* graphs matching the context of the pattern (this is none, one or_x000D_
* all graphs). In matching graphs the number of matching statements_x000D_
* is accumulated and returned._x000D_
* @throws ModelRuntimeException_x000D_
*/_x000D_
long countStatements(QuadPattern pattern) throws ModelRuntimeException;_x000D_
_x000D_
/**_x000D_
* @param context_x000D_
* @param subject_x000D_
* @param predicate_x000D_
* @param object_x000D_
* @return a QuadPattern_x000D_
*/_x000D_
QuadPattern createQuadPattern(UriOrVariable context, ResourceOrVariable subject,_x000D_
UriOrVariable predicate, NodeOrVariable object);_x000D_
_x000D_
}_x000D_
| False | 1,228 | 29 | 1,350 | 33 | 1,389 | 33 | 1,350 | 33 | 1,468 | 33 | false | false | false | false | false | true |
1,710 | 94296_0 | package eu.theunitry.fabula.levels;
import eu.theunitry.fabula.UNGameEngine.graphics.UNGameScreen;
import eu.theunitry.fabula.UNGameEngine.graphics.UNColor;
import eu.theunitry.fabula.UNGameEngine.graphics.UNGraphicsObject;
import eu.theunitry.fabula.UNGameEngine.graphics.UNLevel;
import eu.theunitry.fabula.UNGameEngine.launcher.UNLauncher;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
/**
* Level 11.
* Jeroen Bronkhorst
*/
public class Level11 extends UNLevel
{
private Timer timer;
private UNGraphicsObject cashdesk;
private ArrayList<UNGraphicsObject> apples, pears, grapes, oranges, bananas;
private JButton button;
private int need, touch;
private UNColor color;
private String lastHelp;
/**
* Level 11
* @param gameScreen
* @param hudEnabled
*/
public Level11(UNGameScreen gameScreen, boolean hudEnabled)
{
super(gameScreen, hudEnabled);
this.need = 3 + new Random().nextInt(10);
this.setQuestion("Koop voor " + need + " euro aan fruit");
this.addHelp("Jammer! Je moet voor " + need + " euro aan fruit kopen");
this.addHelp("Helaas! Je moet voor " + need + " euro aan fruit inslaan");
this.setHelp("Sleep het aantal fruit wat je kan betalen naar de kassa");
this.setBackgroundImage(gameScreen.unResourceLoader.backgrounds.get("supermarket"));
this.setPlayerHasWon (false);
this.lastHelp = getHelp();
this.apples = new ArrayList<>();
this.pears = new ArrayList<>();
this.grapes = new ArrayList<>();
this.oranges = new ArrayList<>();
this.bananas = new ArrayList<>();
this.color = new UNColor();
this.cashdesk = new UNGraphicsObject(gameScreen.getWindow().getFrame(), 5, 280, gameScreen.unResourceLoader.sprites.get("2:11:3"), false, 270, 102);
this.addObject(cashdesk);
for (int i = 0; i < 5; i++){
apples.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 65 +
new Random().nextInt(50), 80 + new Random().nextInt(80), gameScreen.unResourceLoader.sprites.get("2:11:1"), true, 32, 32)
);
}
for (int i = 0; i < 5; i++){
pears.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 165 +
new Random().nextInt(50), 80 + new Random().nextInt(80), gameScreen.unResourceLoader.sprites.get("2:11:6"), true, 32, 32)
);
}
for (int i = 0; i < 5; i++){
grapes.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 470 +
new Random().nextInt(180), 70 + new Random().nextInt(45), gameScreen.unResourceLoader.sprites.get("2:11:4"), true, 32, 32)
);
}
for (int i = 0; i < 5; i++){
oranges.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 680 +
new Random().nextInt(30), 120 + new Random().nextInt(130), gameScreen.unResourceLoader.sprites.get("2:11:5"), true, 32, 32)
);
}
for (int i = 0; i < 5; i++){
bananas.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 430 +
new Random().nextInt(170), 180 + new Random().nextInt(50), gameScreen.unResourceLoader.sprites.get("2:11:2"), true, 32, 32)
);
}
for (UNGraphicsObject apple : apples) {
addObject(apple);
}
for (UNGraphicsObject pear : pears) {
addObject(pear);
}
for (UNGraphicsObject grape : grapes) {
addObject(grape);
}
for (UNGraphicsObject orange : oranges) {
addObject(orange);
}
for (UNGraphicsObject banana : bananas) {
addObject(banana);
}
this.button = new JButton("Betaal");
this.setLayout(null);
this.button.setBounds(275, 64, 150, 50);
this.button.setBackground(new Color(51, 51, 51));
this.button.setFont(new Font("Minecraftia", Font.PLAIN, 15));
this.button.setForeground(Color.white);
this.button.setOpaque(true);
/**
* Reset Default Styling
*/
this.button.setFocusPainted(false);
this.button.setBorderPainted(false);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (button.getText().equals("Doorgaan")) {
levelDone(11);
}
if (isHelperDoneTalking()) {
if (hasPlayerWon()) {
getHelper().setState(3);
setHelp("Puik rekenwerk! Ze zien er vers uit!");
for (UNGraphicsObject apple : apples) {
apple.setClickable(false);
}
for (UNGraphicsObject pear : pears) {
pear.setClickable(false);
}
for (UNGraphicsObject grape : grapes) {
grape.setClickable(false);
}
for (UNGraphicsObject orange : oranges) {
orange.setClickable(false);
}
for (UNGraphicsObject banana : bananas) {
banana.setClickable(false);
}
button.setText("Doorgaan");
} else {
addMistake();
if (getMistakes() < 3) {
getHelper().setState(4);
while(lastHelp.equals(getHelp())) {
setHelp(getHelpList().get(new Random().nextInt(getHelpList().size())));
}
lastHelp = getHelp();
} else {
getHelper().setState(4);
if (touch < need) {
setHelp("Jammer, je moest nog " + (need - touch) + " euro aan fruit kopen. Want " +
(need - touch) + " plus " + touch + " is " + need
);
} else {
setHelp("Jammer, je had " + (touch - need) + " euro aan fruit teveel gekocht. Want " +
touch + " min " + (touch - need) + " is " + need
);
}
for (UNGraphicsObject apple : apples) {
apple.setClickable(false);
}
for (UNGraphicsObject pear : pears) {
pear.setClickable(false);
}
for (UNGraphicsObject grape : grapes) {
grape.setClickable(false);
}
for (UNGraphicsObject orange : oranges) {
orange.setClickable(false);
}
for (UNGraphicsObject banana : bananas) {
banana.setClickable(false);
}
button.setText("Doorgaan");
}
}
}
}
});
this.getPanel().add(button);
timer = new Timer(1, e -> {
touch = 0;
for (UNGraphicsObject apple : apples) {
if (cashdesk.getHitbox().intersects(apple.getHitbox())) {
touch++;
}
}
for (UNGraphicsObject pear : pears) {
if (cashdesk.getHitbox().intersects(pear.getHitbox())) {
touch = touch + 3;
}
}
for (UNGraphicsObject grape : grapes) {
if (cashdesk.getHitbox().intersects(grape.getHitbox())) {
touch = touch + 4;
}
}
for (UNGraphicsObject orange : oranges) {
if (cashdesk.getHitbox().intersects(orange.getHitbox())) {
touch = touch + 4;
}
}
for (UNGraphicsObject banana : bananas) {
if (cashdesk.getHitbox().intersects(banana.getHitbox())) {
touch = touch + 2;
}
}
setPlayerHasWon(touch == need);
});
timer.start();
}
}
| The-Unitry/fabula | Fabula/src/eu/theunitry/fabula/levels/Level11.java | 2,482 | /**
* Level 11.
* Jeroen Bronkhorst
*/ | block_comment | nl | package eu.theunitry.fabula.levels;
import eu.theunitry.fabula.UNGameEngine.graphics.UNGameScreen;
import eu.theunitry.fabula.UNGameEngine.graphics.UNColor;
import eu.theunitry.fabula.UNGameEngine.graphics.UNGraphicsObject;
import eu.theunitry.fabula.UNGameEngine.graphics.UNLevel;
import eu.theunitry.fabula.UNGameEngine.launcher.UNLauncher;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
/**
* Level 11.
<SUF>*/
public class Level11 extends UNLevel
{
private Timer timer;
private UNGraphicsObject cashdesk;
private ArrayList<UNGraphicsObject> apples, pears, grapes, oranges, bananas;
private JButton button;
private int need, touch;
private UNColor color;
private String lastHelp;
/**
* Level 11
* @param gameScreen
* @param hudEnabled
*/
public Level11(UNGameScreen gameScreen, boolean hudEnabled)
{
super(gameScreen, hudEnabled);
this.need = 3 + new Random().nextInt(10);
this.setQuestion("Koop voor " + need + " euro aan fruit");
this.addHelp("Jammer! Je moet voor " + need + " euro aan fruit kopen");
this.addHelp("Helaas! Je moet voor " + need + " euro aan fruit inslaan");
this.setHelp("Sleep het aantal fruit wat je kan betalen naar de kassa");
this.setBackgroundImage(gameScreen.unResourceLoader.backgrounds.get("supermarket"));
this.setPlayerHasWon (false);
this.lastHelp = getHelp();
this.apples = new ArrayList<>();
this.pears = new ArrayList<>();
this.grapes = new ArrayList<>();
this.oranges = new ArrayList<>();
this.bananas = new ArrayList<>();
this.color = new UNColor();
this.cashdesk = new UNGraphicsObject(gameScreen.getWindow().getFrame(), 5, 280, gameScreen.unResourceLoader.sprites.get("2:11:3"), false, 270, 102);
this.addObject(cashdesk);
for (int i = 0; i < 5; i++){
apples.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 65 +
new Random().nextInt(50), 80 + new Random().nextInt(80), gameScreen.unResourceLoader.sprites.get("2:11:1"), true, 32, 32)
);
}
for (int i = 0; i < 5; i++){
pears.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 165 +
new Random().nextInt(50), 80 + new Random().nextInt(80), gameScreen.unResourceLoader.sprites.get("2:11:6"), true, 32, 32)
);
}
for (int i = 0; i < 5; i++){
grapes.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 470 +
new Random().nextInt(180), 70 + new Random().nextInt(45), gameScreen.unResourceLoader.sprites.get("2:11:4"), true, 32, 32)
);
}
for (int i = 0; i < 5; i++){
oranges.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 680 +
new Random().nextInt(30), 120 + new Random().nextInt(130), gameScreen.unResourceLoader.sprites.get("2:11:5"), true, 32, 32)
);
}
for (int i = 0; i < 5; i++){
bananas.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 430 +
new Random().nextInt(170), 180 + new Random().nextInt(50), gameScreen.unResourceLoader.sprites.get("2:11:2"), true, 32, 32)
);
}
for (UNGraphicsObject apple : apples) {
addObject(apple);
}
for (UNGraphicsObject pear : pears) {
addObject(pear);
}
for (UNGraphicsObject grape : grapes) {
addObject(grape);
}
for (UNGraphicsObject orange : oranges) {
addObject(orange);
}
for (UNGraphicsObject banana : bananas) {
addObject(banana);
}
this.button = new JButton("Betaal");
this.setLayout(null);
this.button.setBounds(275, 64, 150, 50);
this.button.setBackground(new Color(51, 51, 51));
this.button.setFont(new Font("Minecraftia", Font.PLAIN, 15));
this.button.setForeground(Color.white);
this.button.setOpaque(true);
/**
* Reset Default Styling
*/
this.button.setFocusPainted(false);
this.button.setBorderPainted(false);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (button.getText().equals("Doorgaan")) {
levelDone(11);
}
if (isHelperDoneTalking()) {
if (hasPlayerWon()) {
getHelper().setState(3);
setHelp("Puik rekenwerk! Ze zien er vers uit!");
for (UNGraphicsObject apple : apples) {
apple.setClickable(false);
}
for (UNGraphicsObject pear : pears) {
pear.setClickable(false);
}
for (UNGraphicsObject grape : grapes) {
grape.setClickable(false);
}
for (UNGraphicsObject orange : oranges) {
orange.setClickable(false);
}
for (UNGraphicsObject banana : bananas) {
banana.setClickable(false);
}
button.setText("Doorgaan");
} else {
addMistake();
if (getMistakes() < 3) {
getHelper().setState(4);
while(lastHelp.equals(getHelp())) {
setHelp(getHelpList().get(new Random().nextInt(getHelpList().size())));
}
lastHelp = getHelp();
} else {
getHelper().setState(4);
if (touch < need) {
setHelp("Jammer, je moest nog " + (need - touch) + " euro aan fruit kopen. Want " +
(need - touch) + " plus " + touch + " is " + need
);
} else {
setHelp("Jammer, je had " + (touch - need) + " euro aan fruit teveel gekocht. Want " +
touch + " min " + (touch - need) + " is " + need
);
}
for (UNGraphicsObject apple : apples) {
apple.setClickable(false);
}
for (UNGraphicsObject pear : pears) {
pear.setClickable(false);
}
for (UNGraphicsObject grape : grapes) {
grape.setClickable(false);
}
for (UNGraphicsObject orange : oranges) {
orange.setClickable(false);
}
for (UNGraphicsObject banana : bananas) {
banana.setClickable(false);
}
button.setText("Doorgaan");
}
}
}
}
});
this.getPanel().add(button);
timer = new Timer(1, e -> {
touch = 0;
for (UNGraphicsObject apple : apples) {
if (cashdesk.getHitbox().intersects(apple.getHitbox())) {
touch++;
}
}
for (UNGraphicsObject pear : pears) {
if (cashdesk.getHitbox().intersects(pear.getHitbox())) {
touch = touch + 3;
}
}
for (UNGraphicsObject grape : grapes) {
if (cashdesk.getHitbox().intersects(grape.getHitbox())) {
touch = touch + 4;
}
}
for (UNGraphicsObject orange : oranges) {
if (cashdesk.getHitbox().intersects(orange.getHitbox())) {
touch = touch + 4;
}
}
for (UNGraphicsObject banana : bananas) {
if (cashdesk.getHitbox().intersects(banana.getHitbox())) {
touch = touch + 2;
}
}
setPlayerHasWon(touch == need);
});
timer.start();
}
}
| False | 1,873 | 17 | 2,130 | 20 | 2,191 | 17 | 2,130 | 20 | 2,498 | 19 | false | false | false | false | false | true |
3,193 | 37362_29 | package jmri.jmrix.sprog.simulator;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import jmri.jmrix.sprog.SprogCommandStation;
import jmri.jmrix.sprog.SprogConstants.SprogMode;
import jmri.jmrix.sprog.SprogMessage;
import jmri.jmrix.sprog.SprogPortController; // no special xSimulatorController
import jmri.jmrix.sprog.SprogReply;
import jmri.jmrix.sprog.SprogSystemConnectionMemo;
import jmri.jmrix.sprog.SprogTrafficController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provide access to a simulated SPROG system.
* <p>
* Can be loaded as either a Programmer or Command Station.
* The SPROG SimulatorAdapter reacts to commands sent from the user interface
* with an appropriate reply message.
* <p>
* Based on jmri.jmrix.lenz.xnetsimulator.XNetSimulatorAdapter / DCCppSimulatorAdapter 2017
*
* @author Paul Bender, Copyright (C) 2009-2010
* @author Mark Underwood, Copyright (C) 2015
* @author Egbert Broerse, Copyright (C) 2018
*/
public class SimulatorAdapter extends SprogPortController implements Runnable {
// private control members
private boolean opened = false;
private Thread sourceThread;
private SprogTrafficController control;
private boolean outputBufferEmpty = true;
private boolean checkBuffer = true;
private boolean trackPowerState = false;
private SprogMode operatingMode = SprogMode.SERVICE;
// Simulator responses
String SPR_OK = "OK";
String SPR_NO = "No Ack";
String SPR_PR = "\nP> "; // prompt
public SimulatorAdapter() {
super(new SprogSystemConnectionMemo(SprogMode.SERVICE)); // use default user name
// starts as SERVICE mode (Programmer); may be set to OPS (Command Station) from connection option
setManufacturer(jmri.jmrix.sprog.SprogConnectionTypeList.SPROG);
this.getSystemConnectionMemo().setUserName(Bundle.getMessage("SprogSimulatorTitle"));
// create the traffic controller
control = new SprogTrafficController(this.getSystemConnectionMemo());
this.getSystemConnectionMemo().setSprogTrafficController(control);
options.put("OperatingMode", // NOI18N
new Option(Bundle.getMessage("MakeLabel", Bundle.getMessage("SprogSimOption")), // NOI18N
new String[]{Bundle.getMessage("SprogProgrammerTitle"),
Bundle.getMessage("SprogCSTitle")}, true));
}
@Override
public String openPort(String portName, String appName) {
try {
PipedOutputStream tempPipeI = new PipedOutputStream();
log.debug("tempPipeI created");
pout = new DataOutputStream(tempPipeI);
inpipe = new DataInputStream(new PipedInputStream(tempPipeI));
log.debug("inpipe created {}", inpipe != null);
PipedOutputStream tempPipeO = new PipedOutputStream();
outpipe = new DataOutputStream(tempPipeO);
pin = new DataInputStream(new PipedInputStream(tempPipeO));
} catch (java.io.IOException e) {
log.error("init (pipe): Exception: " + e.toString());
}
opened = true;
return null; // indicates OK return
}
/**
* Set if the output buffer is empty or full. This should only be set to
* false by external processes.
*
* @param s true if output buffer is empty; false otherwise
*/
synchronized public void setOutputBufferEmpty(boolean s) {
outputBufferEmpty = s;
}
/**
* Can the port accept additional characters? The state of CTS determines
* this, as there seems to be no way to check the number of queued bytes and
* buffer length. This might go false for short intervals, but it might also
* stick off if something goes wrong.
*
* @return true if port can accept additional characters; false otherwise
*/
public boolean okToSend() {
if (checkBuffer) {
log.debug("Buffer Empty: " + outputBufferEmpty);
return (outputBufferEmpty);
} else {
log.debug("No Flow Control or Buffer Check");
return (true);
}
}
/**
* Set up all of the other objects to operate with a Sprog Simulator.
*/
@Override
public void configure() {
// connect to the traffic controller
this.getSystemConnectionMemo().getSprogTrafficController().connectPort(this);
if (getOptionState("OperatingMode") != null && getOptionState("OperatingMode").equals(Bundle.getMessage("SprogProgrammerTitle"))) {
operatingMode = SprogMode.SERVICE;
} else { // default, also used after Locale change
operatingMode = SprogMode.OPS;
}
this.getSystemConnectionMemo().setSprogMode(operatingMode); // first update mode in memo
this.getSystemConnectionMemo().configureCommandStation(); // CS only if in OPS mode, memo will take care of that
this.getSystemConnectionMemo().configureManagers(); // wait for mode to be correct
if (getOptionState("TrackPowerState") != null && getOptionState("TrackPowerState").equals(Bundle.getMessage("PowerStateOn"))) {
try {
this.getSystemConnectionMemo().getPowerManager().setPower(jmri.PowerManager.ON);
} catch (jmri.JmriException e) {
log.error(e.toString());
}
}
// start the simulator
sourceThread = new Thread(this);
sourceThread.setName("SPROG Simulator");
sourceThread.setPriority(Thread.MIN_PRIORITY);
sourceThread.start();
}
/**
* {@inheritDoc}
*/
@Override
public void connect() throws java.io.IOException {
log.debug("connect called");
super.connect();
}
// Base class methods for the SprogPortController simulated interface
@Override
public DataInputStream getInputStream() {
if (!opened || pin == null) {
log.error("getInputStream called before load(), stream not available");
}
log.debug("DataInputStream pin returned");
return pin;
}
@Override
public DataOutputStream getOutputStream() {
if (!opened || pout == null) {
log.error("getOutputStream called before load(), stream not available");
}
log.debug("DataOutputStream pout returned");
return pout;
}
@Override
public boolean status() {
return (pout != null && pin != null);
}
/**
* Get an array of valid baud rates.
*
* @return null
*/
@Override
public String[] validBaudRates() {
log.debug("validBaudRates should not have been invoked");
return null;
}
@Override
public String getCurrentBaudRate() {
return "";
}
@Override
public void run() { // start a new thread
// This thread has one task. It repeatedly reads from the input pipe
// and writes an appropriate response to the output pipe. This is the heart
// of the SPROG command station simulation.
log.info("SPROG Simulator Started");
while (true) {
try {
synchronized (this) {
wait(50);
}
} catch (InterruptedException e) {
log.debug("interrupted, ending");
return;
}
SprogMessage m = readMessage();
SprogReply r;
if (log.isDebugEnabled()) {
StringBuffer buf = new StringBuffer();
buf.append("SPROG Simulator Thread received message: ");
if (m != null) {
buf.append(m);
} else {
buf.append("null message buffer");
}
//log.debug(buf.toString()); // generates a lot of output
}
if (m != null) {
r = generateReply(m);
writeReply(r);
if (log.isDebugEnabled() && r != null) {
log.debug("Simulator Thread sent Reply: \"{}\"", r);
}
}
}
}
/**
* Read one incoming message from the buffer
* and set outputBufferEmpty to true.
*/
private SprogMessage readMessage() {
SprogMessage msg = null;
// log.debug("Simulator reading message");
try {
if (inpipe != null && inpipe.available() > 0) {
msg = loadChars();
}
} catch (java.io.IOException e) {
// should do something meaningful here.
}
setOutputBufferEmpty(true);
return (msg);
}
/**
* This is the heart of the simulation. It translates an
* incoming SprogMessage into an outgoing SprogReply.
*
* Based on SPROG information from A. Crosland.
* @see jmri.jmrix.sprog.SprogReply#value()
*/
@SuppressWarnings("fallthrough")
private SprogReply generateReply(SprogMessage msg) {
log.debug("Generate Reply to message type {} (string = {})", msg.toString().charAt(0), msg.toString());
SprogReply reply = new SprogReply();
int i = 0;
char command = msg.toString().charAt(0);
log.debug("Message type = " + command);
switch (command) {
case 'I':
log.debug("CurrentQuery detected");
reply = new SprogReply("= h3E7\n"); // reply fictionary current (decimal 999mA)
break;
case 'C':
case 'V':
log.debug("Read/Write CV detected");
reply = new SprogReply("= " + msg.toString().substring(2) + "\n"); // echo CV value (hex)
break;
case 'O':
log.debug("Send packet command detected");
reply = new SprogReply("= " + msg.toString().substring(2) + "\n"); // echo command (hex)
break;
case 'A':
log.debug("Address (open Throttle) command detected");
reply = new SprogReply(msg.toString().substring(2) + "\n"); // echo address (decimal)
break;
case '>':
log.debug("Set speed (Throttle) command detected");
reply = new SprogReply(msg.toString().substring(1) + "\n"); // echo speed (decimal)
break;
case '+':
log.debug("TRACK_POWER_ON detected");
trackPowerState = true;
//reply = new SprogReply(SPR_PR);
break;
case '-':
log.debug("TRACK_POWER_OFF detected");
trackPowerState = false;
//reply = new SprogReply(SPR_PR);
break;
case '?':
log.debug("Read_Sprog_Version detected");
String replyString = "\nSPROG II Ver 4.3\n";
reply = new SprogReply(replyString);
break;
case 'M':
log.debug("Mode Word detected");
reply = new SprogReply("P>M=h800\n"); // default mode reply
break;
case 'S':
log.debug("getStatus detected");
reply = new SprogReply("S\n");
break;
default:
log.debug("non-reply message detected: {}", msg.toString());
reply = new SprogReply("!E\n"); // SPROG error reply
}
i = reply.toString().length();
reply.setElement(i++, 'P'); // add prompt to all replies
reply.setElement(i++, '>');
reply.setElement(i++, ' ');
log.debug("Reply generated = \"{}\"", reply.toString());
return reply;
}
/**
* Write reply to output.
* <p>
* Copied from jmri.jmrix.nce.simulator.SimulatorAdapter,
* adapted for {@link jmri.jmrix.sprog.SprogTrafficController#handleOneIncomingReply()}.
*
* @param r reply on message
*/
private void writeReply(SprogReply r) {
if (r == null) {
return; // there is no reply to be sent
}
int len = r.getNumDataElements();
for (int i = 0; i < len; i++) {
try {
outpipe.writeByte((byte) r.getElement(i));
log.debug("{} of {} bytes written to outpipe", i + 1, len);
if (pin.available() > 0) {
control.handleOneIncomingReply();
}
} catch (java.io.IOException ex) {
}
}
try {
outpipe.flush();
} catch (java.io.IOException ex) {
}
}
/**
* Get characters from the input source.
* <p>
* Only used in the Receive thread.
*
* @returns filled message, only when the message is complete.
* @throws IOException when presented by the input source.
*/
private SprogMessage loadChars() throws java.io.IOException {
// code copied from EasyDcc/NCE Simulator
int nchars;
byte[] rcvBuffer = new byte[32];
nchars = inpipe.read(rcvBuffer, 0, 32);
//log.debug("new message received");
SprogMessage msg = new SprogMessage(nchars);
for (int i = 0; i < nchars; i++) {
msg.setElement(i, rcvBuffer[i] & 0xFF);
}
return msg;
}
// streams to share with user class
private DataOutputStream pout = null; // this is provided to classes who want to write to us
private DataInputStream pin = null; // this is provided to classes who want data from us
// internal ends of the pipes
private DataOutputStream outpipe = null; // feed pin
private DataInputStream inpipe = null; // feed pout
private final static Logger log = LoggerFactory.getLogger(SimulatorAdapter.class);
}
| jdubrule/JMRI | java/src/jmri/jmrix/sprog/simulator/SimulatorAdapter.java | 3,934 | // echo CV value (hex) | line_comment | nl | package jmri.jmrix.sprog.simulator;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import jmri.jmrix.sprog.SprogCommandStation;
import jmri.jmrix.sprog.SprogConstants.SprogMode;
import jmri.jmrix.sprog.SprogMessage;
import jmri.jmrix.sprog.SprogPortController; // no special xSimulatorController
import jmri.jmrix.sprog.SprogReply;
import jmri.jmrix.sprog.SprogSystemConnectionMemo;
import jmri.jmrix.sprog.SprogTrafficController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provide access to a simulated SPROG system.
* <p>
* Can be loaded as either a Programmer or Command Station.
* The SPROG SimulatorAdapter reacts to commands sent from the user interface
* with an appropriate reply message.
* <p>
* Based on jmri.jmrix.lenz.xnetsimulator.XNetSimulatorAdapter / DCCppSimulatorAdapter 2017
*
* @author Paul Bender, Copyright (C) 2009-2010
* @author Mark Underwood, Copyright (C) 2015
* @author Egbert Broerse, Copyright (C) 2018
*/
public class SimulatorAdapter extends SprogPortController implements Runnable {
// private control members
private boolean opened = false;
private Thread sourceThread;
private SprogTrafficController control;
private boolean outputBufferEmpty = true;
private boolean checkBuffer = true;
private boolean trackPowerState = false;
private SprogMode operatingMode = SprogMode.SERVICE;
// Simulator responses
String SPR_OK = "OK";
String SPR_NO = "No Ack";
String SPR_PR = "\nP> "; // prompt
public SimulatorAdapter() {
super(new SprogSystemConnectionMemo(SprogMode.SERVICE)); // use default user name
// starts as SERVICE mode (Programmer); may be set to OPS (Command Station) from connection option
setManufacturer(jmri.jmrix.sprog.SprogConnectionTypeList.SPROG);
this.getSystemConnectionMemo().setUserName(Bundle.getMessage("SprogSimulatorTitle"));
// create the traffic controller
control = new SprogTrafficController(this.getSystemConnectionMemo());
this.getSystemConnectionMemo().setSprogTrafficController(control);
options.put("OperatingMode", // NOI18N
new Option(Bundle.getMessage("MakeLabel", Bundle.getMessage("SprogSimOption")), // NOI18N
new String[]{Bundle.getMessage("SprogProgrammerTitle"),
Bundle.getMessage("SprogCSTitle")}, true));
}
@Override
public String openPort(String portName, String appName) {
try {
PipedOutputStream tempPipeI = new PipedOutputStream();
log.debug("tempPipeI created");
pout = new DataOutputStream(tempPipeI);
inpipe = new DataInputStream(new PipedInputStream(tempPipeI));
log.debug("inpipe created {}", inpipe != null);
PipedOutputStream tempPipeO = new PipedOutputStream();
outpipe = new DataOutputStream(tempPipeO);
pin = new DataInputStream(new PipedInputStream(tempPipeO));
} catch (java.io.IOException e) {
log.error("init (pipe): Exception: " + e.toString());
}
opened = true;
return null; // indicates OK return
}
/**
* Set if the output buffer is empty or full. This should only be set to
* false by external processes.
*
* @param s true if output buffer is empty; false otherwise
*/
synchronized public void setOutputBufferEmpty(boolean s) {
outputBufferEmpty = s;
}
/**
* Can the port accept additional characters? The state of CTS determines
* this, as there seems to be no way to check the number of queued bytes and
* buffer length. This might go false for short intervals, but it might also
* stick off if something goes wrong.
*
* @return true if port can accept additional characters; false otherwise
*/
public boolean okToSend() {
if (checkBuffer) {
log.debug("Buffer Empty: " + outputBufferEmpty);
return (outputBufferEmpty);
} else {
log.debug("No Flow Control or Buffer Check");
return (true);
}
}
/**
* Set up all of the other objects to operate with a Sprog Simulator.
*/
@Override
public void configure() {
// connect to the traffic controller
this.getSystemConnectionMemo().getSprogTrafficController().connectPort(this);
if (getOptionState("OperatingMode") != null && getOptionState("OperatingMode").equals(Bundle.getMessage("SprogProgrammerTitle"))) {
operatingMode = SprogMode.SERVICE;
} else { // default, also used after Locale change
operatingMode = SprogMode.OPS;
}
this.getSystemConnectionMemo().setSprogMode(operatingMode); // first update mode in memo
this.getSystemConnectionMemo().configureCommandStation(); // CS only if in OPS mode, memo will take care of that
this.getSystemConnectionMemo().configureManagers(); // wait for mode to be correct
if (getOptionState("TrackPowerState") != null && getOptionState("TrackPowerState").equals(Bundle.getMessage("PowerStateOn"))) {
try {
this.getSystemConnectionMemo().getPowerManager().setPower(jmri.PowerManager.ON);
} catch (jmri.JmriException e) {
log.error(e.toString());
}
}
// start the simulator
sourceThread = new Thread(this);
sourceThread.setName("SPROG Simulator");
sourceThread.setPriority(Thread.MIN_PRIORITY);
sourceThread.start();
}
/**
* {@inheritDoc}
*/
@Override
public void connect() throws java.io.IOException {
log.debug("connect called");
super.connect();
}
// Base class methods for the SprogPortController simulated interface
@Override
public DataInputStream getInputStream() {
if (!opened || pin == null) {
log.error("getInputStream called before load(), stream not available");
}
log.debug("DataInputStream pin returned");
return pin;
}
@Override
public DataOutputStream getOutputStream() {
if (!opened || pout == null) {
log.error("getOutputStream called before load(), stream not available");
}
log.debug("DataOutputStream pout returned");
return pout;
}
@Override
public boolean status() {
return (pout != null && pin != null);
}
/**
* Get an array of valid baud rates.
*
* @return null
*/
@Override
public String[] validBaudRates() {
log.debug("validBaudRates should not have been invoked");
return null;
}
@Override
public String getCurrentBaudRate() {
return "";
}
@Override
public void run() { // start a new thread
// This thread has one task. It repeatedly reads from the input pipe
// and writes an appropriate response to the output pipe. This is the heart
// of the SPROG command station simulation.
log.info("SPROG Simulator Started");
while (true) {
try {
synchronized (this) {
wait(50);
}
} catch (InterruptedException e) {
log.debug("interrupted, ending");
return;
}
SprogMessage m = readMessage();
SprogReply r;
if (log.isDebugEnabled()) {
StringBuffer buf = new StringBuffer();
buf.append("SPROG Simulator Thread received message: ");
if (m != null) {
buf.append(m);
} else {
buf.append("null message buffer");
}
//log.debug(buf.toString()); // generates a lot of output
}
if (m != null) {
r = generateReply(m);
writeReply(r);
if (log.isDebugEnabled() && r != null) {
log.debug("Simulator Thread sent Reply: \"{}\"", r);
}
}
}
}
/**
* Read one incoming message from the buffer
* and set outputBufferEmpty to true.
*/
private SprogMessage readMessage() {
SprogMessage msg = null;
// log.debug("Simulator reading message");
try {
if (inpipe != null && inpipe.available() > 0) {
msg = loadChars();
}
} catch (java.io.IOException e) {
// should do something meaningful here.
}
setOutputBufferEmpty(true);
return (msg);
}
/**
* This is the heart of the simulation. It translates an
* incoming SprogMessage into an outgoing SprogReply.
*
* Based on SPROG information from A. Crosland.
* @see jmri.jmrix.sprog.SprogReply#value()
*/
@SuppressWarnings("fallthrough")
private SprogReply generateReply(SprogMessage msg) {
log.debug("Generate Reply to message type {} (string = {})", msg.toString().charAt(0), msg.toString());
SprogReply reply = new SprogReply();
int i = 0;
char command = msg.toString().charAt(0);
log.debug("Message type = " + command);
switch (command) {
case 'I':
log.debug("CurrentQuery detected");
reply = new SprogReply("= h3E7\n"); // reply fictionary current (decimal 999mA)
break;
case 'C':
case 'V':
log.debug("Read/Write CV detected");
reply = new SprogReply("= " + msg.toString().substring(2) + "\n"); // echo CV<SUF>
break;
case 'O':
log.debug("Send packet command detected");
reply = new SprogReply("= " + msg.toString().substring(2) + "\n"); // echo command (hex)
break;
case 'A':
log.debug("Address (open Throttle) command detected");
reply = new SprogReply(msg.toString().substring(2) + "\n"); // echo address (decimal)
break;
case '>':
log.debug("Set speed (Throttle) command detected");
reply = new SprogReply(msg.toString().substring(1) + "\n"); // echo speed (decimal)
break;
case '+':
log.debug("TRACK_POWER_ON detected");
trackPowerState = true;
//reply = new SprogReply(SPR_PR);
break;
case '-':
log.debug("TRACK_POWER_OFF detected");
trackPowerState = false;
//reply = new SprogReply(SPR_PR);
break;
case '?':
log.debug("Read_Sprog_Version detected");
String replyString = "\nSPROG II Ver 4.3\n";
reply = new SprogReply(replyString);
break;
case 'M':
log.debug("Mode Word detected");
reply = new SprogReply("P>M=h800\n"); // default mode reply
break;
case 'S':
log.debug("getStatus detected");
reply = new SprogReply("S\n");
break;
default:
log.debug("non-reply message detected: {}", msg.toString());
reply = new SprogReply("!E\n"); // SPROG error reply
}
i = reply.toString().length();
reply.setElement(i++, 'P'); // add prompt to all replies
reply.setElement(i++, '>');
reply.setElement(i++, ' ');
log.debug("Reply generated = \"{}\"", reply.toString());
return reply;
}
/**
* Write reply to output.
* <p>
* Copied from jmri.jmrix.nce.simulator.SimulatorAdapter,
* adapted for {@link jmri.jmrix.sprog.SprogTrafficController#handleOneIncomingReply()}.
*
* @param r reply on message
*/
private void writeReply(SprogReply r) {
if (r == null) {
return; // there is no reply to be sent
}
int len = r.getNumDataElements();
for (int i = 0; i < len; i++) {
try {
outpipe.writeByte((byte) r.getElement(i));
log.debug("{} of {} bytes written to outpipe", i + 1, len);
if (pin.available() > 0) {
control.handleOneIncomingReply();
}
} catch (java.io.IOException ex) {
}
}
try {
outpipe.flush();
} catch (java.io.IOException ex) {
}
}
/**
* Get characters from the input source.
* <p>
* Only used in the Receive thread.
*
* @returns filled message, only when the message is complete.
* @throws IOException when presented by the input source.
*/
private SprogMessage loadChars() throws java.io.IOException {
// code copied from EasyDcc/NCE Simulator
int nchars;
byte[] rcvBuffer = new byte[32];
nchars = inpipe.read(rcvBuffer, 0, 32);
//log.debug("new message received");
SprogMessage msg = new SprogMessage(nchars);
for (int i = 0; i < nchars; i++) {
msg.setElement(i, rcvBuffer[i] & 0xFF);
}
return msg;
}
// streams to share with user class
private DataOutputStream pout = null; // this is provided to classes who want to write to us
private DataInputStream pin = null; // this is provided to classes who want data from us
// internal ends of the pipes
private DataOutputStream outpipe = null; // feed pin
private DataInputStream inpipe = null; // feed pout
private final static Logger log = LoggerFactory.getLogger(SimulatorAdapter.class);
}
| False | 3,062 | 7 | 3,233 | 7 | 3,492 | 7 | 3,238 | 7 | 3,819 | 7 | false | false | false | false | false | true |
2,374 | 149097_2 | /*
* Copyright (c) 2009-2010 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.bullet.joints;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.math.Matrix3f;
import com.jme3.math.Vector3f;
import com.jme3.bullet.joints.motors.RotationalLimitMotor;
import com.jme3.bullet.joints.motors.TranslationalLimitMotor;
import com.jme3.bullet.objects.PhysicsRigidBody;
import com.jme3.export.InputCapsule;
import com.jme3.export.OutputCapsule;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* <i>From bullet manual:</i><br>
* This generic constraint can emulate a variety of standard constraints,
* by configuring each of the 6 degrees of freedom (dof).
* The first 3 dof axis are linear axis, which represent translation of rigidbodies,
* and the latter 3 dof axis represent the angular motion. Each axis can be either locked,
* free or limited. On construction of a new btGeneric6DofConstraint, all axis are locked.
* Afterwards the axis can be reconfigured. Note that several combinations that
* include free and/or limited angular degrees of freedom are undefined.
* @author normenhansen
*/
public class SixDofSpringJoint extends SixDofJoint {
final boolean springEnabled[] = new boolean[6];
final float equilibriumPoint[] = new float[6];
final float springStiffness[] = new float[6];
final float springDamping[] = new float[6]; // between 0 and 1 (1 == no damping)
public SixDofSpringJoint() {
}
/**
* @param pivotA local translation of the joint connection point in node A
* @param pivotB local translation of the joint connection point in node B
*/
public SixDofSpringJoint(PhysicsRigidBody nodeA, PhysicsRigidBody nodeB, Vector3f pivotA, Vector3f pivotB, Matrix3f rotA, Matrix3f rotB, boolean useLinearReferenceFrameA) {
super(nodeA, nodeB, pivotA, pivotB, rotA, rotB, useLinearReferenceFrameA);
}
public void enableSpring(int index, boolean onOff) {
enableSpring(objectId, index, onOff);
}
native void enableSpring(long objctId, int index, boolean onOff);
public void setStiffness(int index, float stiffness) {
setStiffness(objectId, index, stiffness);
}
native void setStiffness(long objctId, int index, float stiffness);
public void setDamping(int index, float damping) {
setDamping(objectId, index, damping);
}
native void setDamping(long objctId, int index, float damping);
public void setEquilibriumPoint() { // set the current constraint position/orientation as an equilibrium point for all DOF
setEquilibriumPoint(objectId);
}
native void setEquilibriumPoint(long objctId);
public void setEquilibriumPoint(int index){ // set the current constraint position/orientation as an equilibrium point for given DOF
setEquilibriumPoint(objectId, index);
}
native void setEquilibriumPoint(long objctId, int index);
@Override
native long createJoint(long objectIdA, long objectIdB, Vector3f pivotA, Matrix3f rotA, Vector3f pivotB, Matrix3f rotB, boolean useLinearReferenceFrameA);
}
| chototsu/MikuMikuStudio | engine/src/bullet/com/jme3/bullet/joints/SixDofSpringJoint.java | 1,426 | // between 0 and 1 (1 == no damping) | line_comment | nl | /*
* Copyright (c) 2009-2010 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.bullet.joints;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.math.Matrix3f;
import com.jme3.math.Vector3f;
import com.jme3.bullet.joints.motors.RotationalLimitMotor;
import com.jme3.bullet.joints.motors.TranslationalLimitMotor;
import com.jme3.bullet.objects.PhysicsRigidBody;
import com.jme3.export.InputCapsule;
import com.jme3.export.OutputCapsule;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* <i>From bullet manual:</i><br>
* This generic constraint can emulate a variety of standard constraints,
* by configuring each of the 6 degrees of freedom (dof).
* The first 3 dof axis are linear axis, which represent translation of rigidbodies,
* and the latter 3 dof axis represent the angular motion. Each axis can be either locked,
* free or limited. On construction of a new btGeneric6DofConstraint, all axis are locked.
* Afterwards the axis can be reconfigured. Note that several combinations that
* include free and/or limited angular degrees of freedom are undefined.
* @author normenhansen
*/
public class SixDofSpringJoint extends SixDofJoint {
final boolean springEnabled[] = new boolean[6];
final float equilibriumPoint[] = new float[6];
final float springStiffness[] = new float[6];
final float springDamping[] = new float[6]; // between 0<SUF>
public SixDofSpringJoint() {
}
/**
* @param pivotA local translation of the joint connection point in node A
* @param pivotB local translation of the joint connection point in node B
*/
public SixDofSpringJoint(PhysicsRigidBody nodeA, PhysicsRigidBody nodeB, Vector3f pivotA, Vector3f pivotB, Matrix3f rotA, Matrix3f rotB, boolean useLinearReferenceFrameA) {
super(nodeA, nodeB, pivotA, pivotB, rotA, rotB, useLinearReferenceFrameA);
}
public void enableSpring(int index, boolean onOff) {
enableSpring(objectId, index, onOff);
}
native void enableSpring(long objctId, int index, boolean onOff);
public void setStiffness(int index, float stiffness) {
setStiffness(objectId, index, stiffness);
}
native void setStiffness(long objctId, int index, float stiffness);
public void setDamping(int index, float damping) {
setDamping(objectId, index, damping);
}
native void setDamping(long objctId, int index, float damping);
public void setEquilibriumPoint() { // set the current constraint position/orientation as an equilibrium point for all DOF
setEquilibriumPoint(objectId);
}
native void setEquilibriumPoint(long objctId);
public void setEquilibriumPoint(int index){ // set the current constraint position/orientation as an equilibrium point for given DOF
setEquilibriumPoint(objectId, index);
}
native void setEquilibriumPoint(long objctId, int index);
@Override
native long createJoint(long objectIdA, long objectIdB, Vector3f pivotA, Matrix3f rotA, Vector3f pivotB, Matrix3f rotB, boolean useLinearReferenceFrameA);
}
| False | 1,106 | 13 | 1,223 | 14 | 1,231 | 13 | 1,223 | 14 | 1,508 | 15 | false | false | false | false | false | true |
2,281 | 22436_1 | package projectd;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class Item {
private int xCoordinate;
private int yCoordinate;
protected int width;
protected int height;
private JLabel sprite = null;
private BufferedImage myPicture = null;
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getxCoordinate() {
return xCoordinate;
}
public void setxCoordinate(int _xCoordinate) {//verplaatsen naar view
this.xCoordinate = _xCoordinate;
sprite.setLocation(xCoordinate, yCoordinate + 100);
sprite.setBounds(xCoordinate, yCoordinate + 100, width, height);
}
public int getyCoordinate() {
return yCoordinate;
}
public void setyCoordinate(int _yCoordinate) {
this.yCoordinate = _yCoordinate;
sprite.setLocation(xCoordinate, yCoordinate + 100);
sprite.setBounds(xCoordinate, yCoordinate + 100, width, height);
}
public JLabel getSprite() {
return sprite;
}
public void setSprite(String path) throws IOException {
myPicture = ImageIO.read(new File(path));
sprite = new JLabel(new ImageIcon(myPicture));
}
public boolean isColliding(Item i) {//Doordat we werken met velden en zonder soepele bewegingen
//this collider
int r1 = (int) (getxCoordinate() + width);
int l1 = (int) (getxCoordinate());
int t1 = (int) (getyCoordinate() + width);
int b1 = (int) (getyCoordinate());
//the other collider
int r2 = (int) (i.getxCoordinate() + i.getWidth());
int l2 = (int) (i.getxCoordinate());
int t2 = (int) (i.getyCoordinate() + i.getHeight());
int b2 = (int) (i.getyCoordinate());
if (r1 < l2 || l1 > r2 || t1 < b2 || b1 > t2) {
return false;
} else {
return true;
}
}
}
| bootv2/ProjectD_9e | project/ProjectD/src/projectd/Item.java | 715 | //Doordat we werken met velden en zonder soepele bewegingen | line_comment | nl | package projectd;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class Item {
private int xCoordinate;
private int yCoordinate;
protected int width;
protected int height;
private JLabel sprite = null;
private BufferedImage myPicture = null;
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getxCoordinate() {
return xCoordinate;
}
public void setxCoordinate(int _xCoordinate) {//verplaatsen naar view
this.xCoordinate = _xCoordinate;
sprite.setLocation(xCoordinate, yCoordinate + 100);
sprite.setBounds(xCoordinate, yCoordinate + 100, width, height);
}
public int getyCoordinate() {
return yCoordinate;
}
public void setyCoordinate(int _yCoordinate) {
this.yCoordinate = _yCoordinate;
sprite.setLocation(xCoordinate, yCoordinate + 100);
sprite.setBounds(xCoordinate, yCoordinate + 100, width, height);
}
public JLabel getSprite() {
return sprite;
}
public void setSprite(String path) throws IOException {
myPicture = ImageIO.read(new File(path));
sprite = new JLabel(new ImageIcon(myPicture));
}
public boolean isColliding(Item i) {//Doordat we<SUF>
//this collider
int r1 = (int) (getxCoordinate() + width);
int l1 = (int) (getxCoordinate());
int t1 = (int) (getyCoordinate() + width);
int b1 = (int) (getyCoordinate());
//the other collider
int r2 = (int) (i.getxCoordinate() + i.getWidth());
int l2 = (int) (i.getxCoordinate());
int t2 = (int) (i.getyCoordinate() + i.getHeight());
int b2 = (int) (i.getyCoordinate());
if (r1 < l2 || l1 > r2 || t1 < b2 || b1 > t2) {
return false;
} else {
return true;
}
}
}
| True | 549 | 19 | 613 | 21 | 649 | 14 | 613 | 21 | 734 | 20 | false | false | false | false | false | true |
3,530 | 1689_3 | package com.busenzo.domein;
import java.time.LocalDateTime;
public class Rit {
private LocalDateTime verwachteAankomstTijd;
private LocalDateTime aankomstTijd;
private Bus bus;
private Lijn lijn;
private String ID;
/**
* Maak een rit aan op een bepaalde lijn
* @param verwachtteAankomstTijd De verwachtte aankomsttijd bij de eindhalte
* @param lijn: De lijn waarbij deze rit hoort, nooit null
*/
public Rit(LocalDateTime verwachtteAankomstTijd, Lijn lijn, String ritID) {
this.lijn = lijn;
this.verwachteAankomstTijd = verwachtteAankomstTijd;
this.ID = ritID;
}
/**
* Haal de bus op die deze rit rijdt.
* @return De bus die deze rit rijdt. Kan null zijn als de rit nog niet vertrokken is
*/
public Bus getBus() {
return this.bus;
}
public String getRitID()
{
return this.ID;
}
public void setAankomstTijd(LocalDateTime aankomstTijd)
{
this.aankomstTijd = aankomstTijd;
}
/**
* Haal de lijn op waarbij deze rit hoort
* @return De lijn waarop deze rit rijdt
*/
public Lijn getLijn() {
return this.lijn;
}
/**
* Haal de verwachtte aankomsttijd bij de eindhalte op
* @return de verwachtte aankomsttijd bij de eindhalte
*/
public LocalDateTime getVerwachteAankomstTijd() {
return verwachteAankomstTijd;
}
/**
* Vraag de verwachtte aankomsttijd op bij de volgende halte
* @return De verwachtte aankomsttijd bij de volgende halte
*/
public LocalDateTime getAankomstTijd() {
return aankomstTijd;
}
/**
* Voeg een bus toe welke deze rit gaat rijden.
* @param bus : De bus die deze rit gaat rijden, mag niet null zijn
*/
public void setBus(Bus bus) {
this.bus = bus;
}
} | maartenpeels/Bus-Tracker | src/com/busenzo/domein/Rit.java | 618 | /**
* Haal de verwachtte aankomsttijd bij de eindhalte op
* @return de verwachtte aankomsttijd bij de eindhalte
*/ | block_comment | nl | package com.busenzo.domein;
import java.time.LocalDateTime;
public class Rit {
private LocalDateTime verwachteAankomstTijd;
private LocalDateTime aankomstTijd;
private Bus bus;
private Lijn lijn;
private String ID;
/**
* Maak een rit aan op een bepaalde lijn
* @param verwachtteAankomstTijd De verwachtte aankomsttijd bij de eindhalte
* @param lijn: De lijn waarbij deze rit hoort, nooit null
*/
public Rit(LocalDateTime verwachtteAankomstTijd, Lijn lijn, String ritID) {
this.lijn = lijn;
this.verwachteAankomstTijd = verwachtteAankomstTijd;
this.ID = ritID;
}
/**
* Haal de bus op die deze rit rijdt.
* @return De bus die deze rit rijdt. Kan null zijn als de rit nog niet vertrokken is
*/
public Bus getBus() {
return this.bus;
}
public String getRitID()
{
return this.ID;
}
public void setAankomstTijd(LocalDateTime aankomstTijd)
{
this.aankomstTijd = aankomstTijd;
}
/**
* Haal de lijn op waarbij deze rit hoort
* @return De lijn waarop deze rit rijdt
*/
public Lijn getLijn() {
return this.lijn;
}
/**
* Haal de verwachtte<SUF>*/
public LocalDateTime getVerwachteAankomstTijd() {
return verwachteAankomstTijd;
}
/**
* Vraag de verwachtte aankomsttijd op bij de volgende halte
* @return De verwachtte aankomsttijd bij de volgende halte
*/
public LocalDateTime getAankomstTijd() {
return aankomstTijd;
}
/**
* Voeg een bus toe welke deze rit gaat rijden.
* @param bus : De bus die deze rit gaat rijden, mag niet null zijn
*/
public void setBus(Bus bus) {
this.bus = bus;
}
} | True | 563 | 46 | 603 | 44 | 547 | 35 | 603 | 44 | 649 | 45 | false | false | false | false | false | true |
589 | 83985_13 | /**
* %HEADER%
*/
package net.sf.genomeview.gui.viztracks.hts;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.JWindow;
import javax.swing.border.Border;
import javax.swing.text.Document;
import javax.swing.text.html.HTMLEditorKit;
import net.sf.genomeview.core.Configuration;
import net.sf.genomeview.data.Model;
import net.sf.genomeview.data.provider.ShortReadProvider;
import net.sf.genomeview.gui.Convert;
import net.sf.genomeview.gui.MessageManager;
import net.sf.genomeview.gui.viztracks.Track;
import net.sf.genomeview.gui.viztracks.TrackCommunicationModel;
import net.sf.jannot.DataKey;
import net.sf.jannot.Location;
import net.sf.samtools.SAMRecord;
/**
*
* @author Thomas Abeel
*
*/
public class ShortReadTrack extends Track {
private srtRender render;
// private ShortReadProvider provider;
private ShortReadTrackConfig srtc;
public ShortReadTrack(DataKey key, ShortReadProvider provider, Model model) {
super(key, model, true, new ShortReadTrackConfig(model, key));
this.srtc = (ShortReadTrackConfig) config;
// this.provider = provider;
render = new srtRender(model, provider, srtc, key);
}
private InsertionTooltip tooltip = new InsertionTooltip();
private ReadInfo readinfo = new ReadInfo();
private static class InsertionTooltip extends JWindow {
private static final long serialVersionUID = -7416732151483650659L;
private JLabel floater = new JLabel();
public InsertionTooltip() {
floater.setBackground(Color.GRAY);
floater.setForeground(Color.BLACK);
Border emptyBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
Border colorBorder = BorderFactory.createLineBorder(Color.BLACK);
floater.setBorder(BorderFactory.createCompoundBorder(colorBorder, emptyBorder));
add(floater);
pack();
}
public void set(MouseEvent e, ShortReadInsertion sri) {
if (sri == null)
return;
StringBuffer text = new StringBuffer();
text.append("<html>");
if (sri != null) {
text.append(MessageManager.getString("shortreadtrack.insertion") + " ");
byte[] bases = sri.esr.getReadBases();
for (int i = sri.start; i < sri.start + sri.len; i++) {
text.append((char) bases[i]);
}
text.append("<br/>");
}
text.append("</html>");
if (!text.toString().equals(floater.getText())) {
floater.setText(text.toString());
this.pack();
}
setLocation(e.getXOnScreen() + 5, e.getYOnScreen() + 5);
if (!isVisible()) {
setVisible(true);
}
}
}
private static class ReadInfo extends JWindow {
private static final long serialVersionUID = -7416732151483650659L;
private JLabel floater = new JLabel();
public ReadInfo() {
floater.setBackground(Color.GRAY);
floater.setForeground(Color.BLACK);
Border emptyBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
Border colorBorder = BorderFactory.createLineBorder(Color.BLACK);
floater.setBorder(BorderFactory.createCompoundBorder(colorBorder, emptyBorder));
add(floater);
pack();
}
public void set(MouseEvent e, SAMRecord sr) {
if (sr == null)
return;
StringBuffer text = new StringBuffer();
text.append("<html>");
if (sr != null) {
text.append(MessageManager.getString("shortreadtrack.name") + " " + sr.getReadName() + "<br/>");
text.append(MessageManager.getString("shortreadtrack.len") + " " + sr.getReadLength() + "<br/>");
text.append(MessageManager.getString("shortreadtrack.cigar") + " " + sr.getCigarString() + "<br/>");
text.append(MessageManager.getString("shortreadtrack.sequence") + " " + rerun(sr.getReadString()) + "<br/>");
text.append(MessageManager.getString("shortreadtrack.paired") + " " + sr.getReadPairedFlag() + "<br/>");
if (sr.getReadPairedFlag()) {
if (!sr.getMateUnmappedFlag())
text.append(MessageManager.getString("shortreadtrack.mate") + " " + sr.getMateReferenceName() + ":" + sr.getMateAlignmentStart()
+ "<br/>");
else
text.append(MessageManager.getString("shortreadtrack.mate_missing") + "<br/>");
text.append(MessageManager.getString("shortreadtrack.second") + " " + sr.getFirstOfPairFlag());
}
// text.append("<br/>");
}
text.append("</html>");
if (!text.toString().equals(floater.getText())) {
floater.setText(text.toString());
this.pack();
}
setLocation(e.getXOnScreen() + 5, e.getYOnScreen() + 5);
if (!isVisible()) {
setVisible(true);
}
}
public void textual() {
if(!isVisible())
return;
// create jeditorpane
JEditorPane jEditorPane = new JEditorPane();
// make it read-only
jEditorPane.setEditable(false);
// create a scrollpane; modify its attributes as desired
JScrollPane scrollPane = new JScrollPane(jEditorPane);
// add an html editor kit
HTMLEditorKit kit = new HTMLEditorKit();
jEditorPane.setEditorKit(kit);
Document doc = kit.createDefaultDocument();
jEditorPane.setDocument(doc);
jEditorPane.setText(floater.getText());
// now add it all to a frame
JFrame j = new JFrame("Read information");
j.getContentPane().add(scrollPane, BorderLayout.CENTER);
// make it easy to close the application
j.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// display the frame
j.setSize(new Dimension(300, 200));
// pack it, if you prefer
// j.pack();
// center the jframe, then make it visible
j.setLocationRelativeTo(null);
j.setVisible(true);
}
}
private static String rerun(String arg) {
StringBuffer out = new StringBuffer();
int i = 0;
for (; i < arg.length() - 80; i += 80)
out.append(arg.substring(i, i + 80) + "<br/>");
out.append(arg.substring(i, arg.length()));
return out.toString();
}
@Override
public boolean mouseExited(int x, int y, MouseEvent source) {
tooltip.setVisible(false);
readinfo.setVisible(false);
return false;
}
@Override
public boolean mouseClicked(int x, int y, MouseEvent source) {
super.mouseClicked(x, y, source);
if (source.isConsumed())
return true;
// System.out.println("Click: " + x + " " + y);
if (source.getClickCount() > 1) {
for (java.util.Map.Entry<Rectangle, SAMRecord> e : render.meta().hitMap.entrySet()) {
if (e.getKey().contains(x, y)) {
System.out.println("2*Click: " + e.getValue());
if (e.getValue().getReadPairedFlag() && !e.getValue().getMateUnmappedFlag())
model.vlm.center(e.getValue().getMateAlignmentStart());
}
}
} else {
readinfo.textual();
}
return false;
}
@Override
public boolean mouseDragged(int x, int y, MouseEvent source) {
tooltip.setVisible(false);
readinfo.setVisible(false);
return false;
}
@Override
public boolean mouseMoved(int x, int y, MouseEvent source) {
if (model.vlm.getAnnotationLocationVisible().length() < Configuration.getInt("geneStructureNucleotideWindow")) {
ShortReadInsertion sri = null;
for (java.util.Map.Entry<Rectangle, ShortReadInsertion> e : render.meta().paintedBlocks.entrySet()) {
if (e.getKey().contains(x, y)) {
sri = e.getValue();
break;
}
}
if (sri != null) {
if (!tooltip.isVisible())
tooltip.setVisible(true);
tooltip.set(source, sri);
} else {
if (tooltip.isVisible())
tooltip.setVisible(false);
}
//
// System.out.println("Moved: " + x + " " + y);
for (java.util.Map.Entry<Rectangle, SAMRecord> e : render.meta().hitMap.entrySet()) {
if (e.getKey().contains(x, y)) {
// System.out.println("Prijs: " + e.getValue());
readinfo.set(source, e.getValue());
}
}
//
return false;
} else {
if (tooltip.isVisible())
tooltip.setVisible(false);
}
return false;
}
@Override
public int paintTrack(Graphics2D gGlobal, int yOffset, double screenWidth, JViewport view, TrackCommunicationModel tcm) {
// Location bufferedLocation = render.location();
// Location visible = model.vlm.getVisibleLocation();
// int x = 0;
// if (bufferedLocation != null)
// x = Convert.translateGenomeToScreen(bufferedLocation.start, visible, screenWidth);
gGlobal.drawImage(render.buffer(), 0, yOffset, null);
return render.buffer().getHeight();
}
}
| GenomeView/genomeview | src/net/sf/genomeview/gui/viztracks/hts/ShortReadTrack.java | 2,934 | // System.out.println("Prijs: " + e.getValue()); | line_comment | nl | /**
* %HEADER%
*/
package net.sf.genomeview.gui.viztracks.hts;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.JWindow;
import javax.swing.border.Border;
import javax.swing.text.Document;
import javax.swing.text.html.HTMLEditorKit;
import net.sf.genomeview.core.Configuration;
import net.sf.genomeview.data.Model;
import net.sf.genomeview.data.provider.ShortReadProvider;
import net.sf.genomeview.gui.Convert;
import net.sf.genomeview.gui.MessageManager;
import net.sf.genomeview.gui.viztracks.Track;
import net.sf.genomeview.gui.viztracks.TrackCommunicationModel;
import net.sf.jannot.DataKey;
import net.sf.jannot.Location;
import net.sf.samtools.SAMRecord;
/**
*
* @author Thomas Abeel
*
*/
public class ShortReadTrack extends Track {
private srtRender render;
// private ShortReadProvider provider;
private ShortReadTrackConfig srtc;
public ShortReadTrack(DataKey key, ShortReadProvider provider, Model model) {
super(key, model, true, new ShortReadTrackConfig(model, key));
this.srtc = (ShortReadTrackConfig) config;
// this.provider = provider;
render = new srtRender(model, provider, srtc, key);
}
private InsertionTooltip tooltip = new InsertionTooltip();
private ReadInfo readinfo = new ReadInfo();
private static class InsertionTooltip extends JWindow {
private static final long serialVersionUID = -7416732151483650659L;
private JLabel floater = new JLabel();
public InsertionTooltip() {
floater.setBackground(Color.GRAY);
floater.setForeground(Color.BLACK);
Border emptyBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
Border colorBorder = BorderFactory.createLineBorder(Color.BLACK);
floater.setBorder(BorderFactory.createCompoundBorder(colorBorder, emptyBorder));
add(floater);
pack();
}
public void set(MouseEvent e, ShortReadInsertion sri) {
if (sri == null)
return;
StringBuffer text = new StringBuffer();
text.append("<html>");
if (sri != null) {
text.append(MessageManager.getString("shortreadtrack.insertion") + " ");
byte[] bases = sri.esr.getReadBases();
for (int i = sri.start; i < sri.start + sri.len; i++) {
text.append((char) bases[i]);
}
text.append("<br/>");
}
text.append("</html>");
if (!text.toString().equals(floater.getText())) {
floater.setText(text.toString());
this.pack();
}
setLocation(e.getXOnScreen() + 5, e.getYOnScreen() + 5);
if (!isVisible()) {
setVisible(true);
}
}
}
private static class ReadInfo extends JWindow {
private static final long serialVersionUID = -7416732151483650659L;
private JLabel floater = new JLabel();
public ReadInfo() {
floater.setBackground(Color.GRAY);
floater.setForeground(Color.BLACK);
Border emptyBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
Border colorBorder = BorderFactory.createLineBorder(Color.BLACK);
floater.setBorder(BorderFactory.createCompoundBorder(colorBorder, emptyBorder));
add(floater);
pack();
}
public void set(MouseEvent e, SAMRecord sr) {
if (sr == null)
return;
StringBuffer text = new StringBuffer();
text.append("<html>");
if (sr != null) {
text.append(MessageManager.getString("shortreadtrack.name") + " " + sr.getReadName() + "<br/>");
text.append(MessageManager.getString("shortreadtrack.len") + " " + sr.getReadLength() + "<br/>");
text.append(MessageManager.getString("shortreadtrack.cigar") + " " + sr.getCigarString() + "<br/>");
text.append(MessageManager.getString("shortreadtrack.sequence") + " " + rerun(sr.getReadString()) + "<br/>");
text.append(MessageManager.getString("shortreadtrack.paired") + " " + sr.getReadPairedFlag() + "<br/>");
if (sr.getReadPairedFlag()) {
if (!sr.getMateUnmappedFlag())
text.append(MessageManager.getString("shortreadtrack.mate") + " " + sr.getMateReferenceName() + ":" + sr.getMateAlignmentStart()
+ "<br/>");
else
text.append(MessageManager.getString("shortreadtrack.mate_missing") + "<br/>");
text.append(MessageManager.getString("shortreadtrack.second") + " " + sr.getFirstOfPairFlag());
}
// text.append("<br/>");
}
text.append("</html>");
if (!text.toString().equals(floater.getText())) {
floater.setText(text.toString());
this.pack();
}
setLocation(e.getXOnScreen() + 5, e.getYOnScreen() + 5);
if (!isVisible()) {
setVisible(true);
}
}
public void textual() {
if(!isVisible())
return;
// create jeditorpane
JEditorPane jEditorPane = new JEditorPane();
// make it read-only
jEditorPane.setEditable(false);
// create a scrollpane; modify its attributes as desired
JScrollPane scrollPane = new JScrollPane(jEditorPane);
// add an html editor kit
HTMLEditorKit kit = new HTMLEditorKit();
jEditorPane.setEditorKit(kit);
Document doc = kit.createDefaultDocument();
jEditorPane.setDocument(doc);
jEditorPane.setText(floater.getText());
// now add it all to a frame
JFrame j = new JFrame("Read information");
j.getContentPane().add(scrollPane, BorderLayout.CENTER);
// make it easy to close the application
j.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// display the frame
j.setSize(new Dimension(300, 200));
// pack it, if you prefer
// j.pack();
// center the jframe, then make it visible
j.setLocationRelativeTo(null);
j.setVisible(true);
}
}
private static String rerun(String arg) {
StringBuffer out = new StringBuffer();
int i = 0;
for (; i < arg.length() - 80; i += 80)
out.append(arg.substring(i, i + 80) + "<br/>");
out.append(arg.substring(i, arg.length()));
return out.toString();
}
@Override
public boolean mouseExited(int x, int y, MouseEvent source) {
tooltip.setVisible(false);
readinfo.setVisible(false);
return false;
}
@Override
public boolean mouseClicked(int x, int y, MouseEvent source) {
super.mouseClicked(x, y, source);
if (source.isConsumed())
return true;
// System.out.println("Click: " + x + " " + y);
if (source.getClickCount() > 1) {
for (java.util.Map.Entry<Rectangle, SAMRecord> e : render.meta().hitMap.entrySet()) {
if (e.getKey().contains(x, y)) {
System.out.println("2*Click: " + e.getValue());
if (e.getValue().getReadPairedFlag() && !e.getValue().getMateUnmappedFlag())
model.vlm.center(e.getValue().getMateAlignmentStart());
}
}
} else {
readinfo.textual();
}
return false;
}
@Override
public boolean mouseDragged(int x, int y, MouseEvent source) {
tooltip.setVisible(false);
readinfo.setVisible(false);
return false;
}
@Override
public boolean mouseMoved(int x, int y, MouseEvent source) {
if (model.vlm.getAnnotationLocationVisible().length() < Configuration.getInt("geneStructureNucleotideWindow")) {
ShortReadInsertion sri = null;
for (java.util.Map.Entry<Rectangle, ShortReadInsertion> e : render.meta().paintedBlocks.entrySet()) {
if (e.getKey().contains(x, y)) {
sri = e.getValue();
break;
}
}
if (sri != null) {
if (!tooltip.isVisible())
tooltip.setVisible(true);
tooltip.set(source, sri);
} else {
if (tooltip.isVisible())
tooltip.setVisible(false);
}
//
// System.out.println("Moved: " + x + " " + y);
for (java.util.Map.Entry<Rectangle, SAMRecord> e : render.meta().hitMap.entrySet()) {
if (e.getKey().contains(x, y)) {
// System.out.println("Prijs: "<SUF>
readinfo.set(source, e.getValue());
}
}
//
return false;
} else {
if (tooltip.isVisible())
tooltip.setVisible(false);
}
return false;
}
@Override
public int paintTrack(Graphics2D gGlobal, int yOffset, double screenWidth, JViewport view, TrackCommunicationModel tcm) {
// Location bufferedLocation = render.location();
// Location visible = model.vlm.getVisibleLocation();
// int x = 0;
// if (bufferedLocation != null)
// x = Convert.translateGenomeToScreen(bufferedLocation.start, visible, screenWidth);
gGlobal.drawImage(render.buffer(), 0, yOffset, null);
return render.buffer().getHeight();
}
}
| False | 2,167 | 13 | 2,657 | 16 | 2,606 | 15 | 2,657 | 16 | 3,265 | 17 | false | false | false | false | false | true |
3,310 | 172963_2 | package timeutil;
import java.util.LinkedList;
import java.util.List;
/**
* Deze klasse maakt het mogelijk om opeenvolgende tijdsperiodes een naam te
* geven, deze op te slaan en deze daarna te printen (via toString).
*
* Tijdsperiodes worden bepaald door een begintijd en een eindtijd.
*
* begintijd van een periode kan gezet worden door setBegin, de eindtijd kan
* gezet worden door de methode setEind.
*
* Zowel bij de begin- als eindtijd van ee periode kan een String meegegeven
* worden die voor de gebruiker een betekenisvolle aanduiding toevoegt aan dat
* tijdstip. Indien geen string meegegeven wordt, wordt een teller gebruikt, die
* automatisch opgehoogd wordt.
*
* Na het opgeven van een begintijdstip (via setBegin of eenmalig via init ) kan
* t.o.v. dit begintijdstip steeds een eindtijdstip opgegeven worden. Zodoende
* kun je vanaf 1 begintijdstip, meerdere eindtijden opgeven.
*
* Een andere mogelijkheid is om een eindtijdstip direct te laten fungeren als
* begintijdstip voor een volgende periode. Dit kan d.m.v. SetEndBegin of seb.
*
* alle tijdsperiodes kunnen gereset worden dmv init()
*
* @author erik
*
*/
public class TimeStamp {
private static long counter = 0;
private long curBegin;
private String curBeginS;
private List<Period> list;
public TimeStamp() {
TimeStamp.counter = 0;
this.init();
}
/**
* initialiseer klasse. begin met geen tijdsperiodes.
*/
public void init() {
this.curBegin = 0;
this.curBeginS = null;
this.list = new LinkedList();
}
/**
* zet begintijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/
public void setBegin() {
this.setBegin(String.valueOf(TimeStamp.counter++));
}
/**
* zet begintijdstip
*
* @param timepoint betekenisvolle identificatie van begintijdstip
*/
public void setBegin(String timepoint) {
this.curBegin = System.currentTimeMillis();
this.curBeginS = timepoint;
}
/**
* zet eindtijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/
public void setEnd() {
this.setEnd(String.valueOf(TimeStamp.counter++));
}
/**
* zet eindtijdstip
*
* @param timepoint betekenisvolle identificatie vanhet eindtijdstip
*/
public void setEnd(String timepoint) {
this.list.add(new Period(this.curBegin, this.curBeginS, System.currentTimeMillis(), timepoint));
}
/**
* zet eindtijdstip plus begintijdstip
*
* @param timepoint identificatie van het eind- en begintijdstip.
*/
public void setEndBegin(String timepoint) {
this.setEnd(timepoint);
this.setBegin(timepoint);
}
/**
* verkorte versie van setEndBegin
*
* @param timepoint
*/
public void seb(String timepoint) {
this.setEndBegin(timepoint);
}
/**
* interne klasse voor bijhouden van periodes.
*
* @author erik
*
*/
private class Period {
long begin;
String beginS;
long end;
String endS;
public Period(long b, String sb, long e, String se) {
this.setBegin(b, sb);
this.setEnd(e, se);
}
private void setBegin(long b, String sb) {
this.begin = b;
this.beginS = sb;
}
private void setEnd(long e, String se) {
this.end = e;
this.endS = se;
}
@Override
public String toString() {
return "From '" + this.beginS + "' till '" + this.endS + "' is " + (this.end - this.begin) + " mSec.";
}
}
/**
* override van toString methode. Geeft alle tijdsperiode weer.
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
for (Period p : this.list) {
buffer.append(p.toString());
buffer.append('\n');
}
return buffer.toString();
}
} | jussihailu1/Rat-in-a-maze-Backtracking | FUN-Algorithm/src/main/java/TimeStamp.java | 1,266 | /**
* zet begintijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/ | block_comment | nl | package timeutil;
import java.util.LinkedList;
import java.util.List;
/**
* Deze klasse maakt het mogelijk om opeenvolgende tijdsperiodes een naam te
* geven, deze op te slaan en deze daarna te printen (via toString).
*
* Tijdsperiodes worden bepaald door een begintijd en een eindtijd.
*
* begintijd van een periode kan gezet worden door setBegin, de eindtijd kan
* gezet worden door de methode setEind.
*
* Zowel bij de begin- als eindtijd van ee periode kan een String meegegeven
* worden die voor de gebruiker een betekenisvolle aanduiding toevoegt aan dat
* tijdstip. Indien geen string meegegeven wordt, wordt een teller gebruikt, die
* automatisch opgehoogd wordt.
*
* Na het opgeven van een begintijdstip (via setBegin of eenmalig via init ) kan
* t.o.v. dit begintijdstip steeds een eindtijdstip opgegeven worden. Zodoende
* kun je vanaf 1 begintijdstip, meerdere eindtijden opgeven.
*
* Een andere mogelijkheid is om een eindtijdstip direct te laten fungeren als
* begintijdstip voor een volgende periode. Dit kan d.m.v. SetEndBegin of seb.
*
* alle tijdsperiodes kunnen gereset worden dmv init()
*
* @author erik
*
*/
public class TimeStamp {
private static long counter = 0;
private long curBegin;
private String curBeginS;
private List<Period> list;
public TimeStamp() {
TimeStamp.counter = 0;
this.init();
}
/**
* initialiseer klasse. begin met geen tijdsperiodes.
*/
public void init() {
this.curBegin = 0;
this.curBeginS = null;
this.list = new LinkedList();
}
/**
* zet begintijdstip. gebruik<SUF>*/
public void setBegin() {
this.setBegin(String.valueOf(TimeStamp.counter++));
}
/**
* zet begintijdstip
*
* @param timepoint betekenisvolle identificatie van begintijdstip
*/
public void setBegin(String timepoint) {
this.curBegin = System.currentTimeMillis();
this.curBeginS = timepoint;
}
/**
* zet eindtijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/
public void setEnd() {
this.setEnd(String.valueOf(TimeStamp.counter++));
}
/**
* zet eindtijdstip
*
* @param timepoint betekenisvolle identificatie vanhet eindtijdstip
*/
public void setEnd(String timepoint) {
this.list.add(new Period(this.curBegin, this.curBeginS, System.currentTimeMillis(), timepoint));
}
/**
* zet eindtijdstip plus begintijdstip
*
* @param timepoint identificatie van het eind- en begintijdstip.
*/
public void setEndBegin(String timepoint) {
this.setEnd(timepoint);
this.setBegin(timepoint);
}
/**
* verkorte versie van setEndBegin
*
* @param timepoint
*/
public void seb(String timepoint) {
this.setEndBegin(timepoint);
}
/**
* interne klasse voor bijhouden van periodes.
*
* @author erik
*
*/
private class Period {
long begin;
String beginS;
long end;
String endS;
public Period(long b, String sb, long e, String se) {
this.setBegin(b, sb);
this.setEnd(e, se);
}
private void setBegin(long b, String sb) {
this.begin = b;
this.beginS = sb;
}
private void setEnd(long e, String se) {
this.end = e;
this.endS = se;
}
@Override
public String toString() {
return "From '" + this.beginS + "' till '" + this.endS + "' is " + (this.end - this.begin) + " mSec.";
}
}
/**
* override van toString methode. Geeft alle tijdsperiode weer.
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
for (Period p : this.list) {
buffer.append(p.toString());
buffer.append('\n');
}
return buffer.toString();
}
} | True | 1,079 | 32 | 1,173 | 30 | 1,115 | 25 | 1,173 | 30 | 1,286 | 32 | false | false | false | false | false | true |
2,985 | 51838_0 | package nl.novi.Structural.Adapter.holes;
public class SquarePegAdapter extends RoundPeg{
public SquarePeg peg;
public SquarePegAdapter(SquarePeg peg) {
super(0); // wat je hier invult is niet belangrijk
this.peg = peg;
}
public int getRadius(){
return (int) (peg.getWidth() * Math.sqrt(2)/2);
}
}
| hogeschoolnovi/design-patterns-voorbeelden | src/main/java/nl/novi/Structural/Adapter/holes/SquarePegAdapter.java | 111 | // wat je hier invult is niet belangrijk | line_comment | nl | package nl.novi.Structural.Adapter.holes;
public class SquarePegAdapter extends RoundPeg{
public SquarePeg peg;
public SquarePegAdapter(SquarePeg peg) {
super(0); // wat je<SUF>
this.peg = peg;
}
public int getRadius(){
return (int) (peg.getWidth() * Math.sqrt(2)/2);
}
}
| True | 92 | 10 | 103 | 13 | 99 | 9 | 103 | 13 | 119 | 10 | false | false | false | false | false | true |
694 | 127922_0 | class Student {
// STRINGS ==============================================
// Schrijf een functie "String repeat(String str, int n)" die een nieuwe string construeert
// door n keer de string str te herhalen. Je mag ervan uitgaan dat n niet negatief is.
//
// E.g. repeat("abc", 3) returns "abcabcabc"
} | Het-Didactische-Hulpmiddelen-Team/MJQuestions | 04-strings/repeat/Student.java | 96 | // Schrijf een functie "String repeat(String str, int n)" die een nieuwe string construeert | line_comment | nl | class Student {
// STRINGS ==============================================
// Schrijf een<SUF>
// door n keer de string str te herhalen. Je mag ervan uitgaan dat n niet negatief is.
//
// E.g. repeat("abc", 3) returns "abcabcabc"
} | True | 85 | 23 | 89 | 26 | 89 | 22 | 89 | 26 | 101 | 26 | false | false | false | false | false | true |
756 | 53303_7 | /*_x000D_
* Copyright (C) 2016 Dienst voor het kadaster en de openbare registers_x000D_
* _x000D_
* This file is part of Imvertor._x000D_
*_x000D_
* Imvertor is free software: you can redistribute it and/or modify_x000D_
* it under the terms of the GNU General Public License as published by_x000D_
* the Free Software Foundation, either version 3 of the License, or_x000D_
* (at your option) any later version._x000D_
*_x000D_
* Imvertor is distributed in the hope that it will be useful,_x000D_
* but WITHOUT ANY WARRANTY; without even the implied warranty of_x000D_
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the_x000D_
* GNU General Public License for more details._x000D_
*_x000D_
* You should have received a copy of the GNU General Public License_x000D_
* along with Imvertor. If not, see <http://www.gnu.org/licenses/>._x000D_
*_x000D_
*/_x000D_
_x000D_
package nl.imvertor.EpCompiler;_x000D_
_x000D_
import java.io.IOException;_x000D_
_x000D_
import org.apache.log4j.Logger;_x000D_
_x000D_
import nl.imvertor.common.Configurator;_x000D_
import nl.imvertor.common.Step;_x000D_
import nl.imvertor.common.Transformer;_x000D_
import nl.imvertor.common.exceptions.ConfiguratorException;_x000D_
import nl.imvertor.common.file.AnyFile;_x000D_
import nl.imvertor.common.file.AnyFolder;_x000D_
import nl.imvertor.common.file.XmlFile;_x000D_
_x000D_
// see also https://github.com/Imvertor/Imvertor-Maven/issues/56_x000D_
_x000D_
public class EpCompiler extends Step {_x000D_
_x000D_
protected static final Logger logger = Logger.getLogger(EpCompiler.class);_x000D_
_x000D_
public static final String STEP_NAME = "EpCompiler";_x000D_
public static final String VC_IDENTIFIER = "$Id: $";_x000D_
_x000D_
/**_x000D_
* run the main translation_x000D_
*/_x000D_
public boolean run() throws Exception{_x000D_
_x000D_
// set up the configuration for this step_x000D_
configurator.setActiveStepName(STEP_NAME);_x000D_
prepare();_x000D_
_x000D_
runner.info(logger,"Compiling EP");_x000D_
_x000D_
generate();_x000D_
_x000D_
configurator.setStepDone(STEP_NAME);_x000D_
_x000D_
// save any changes to the work configuration for report and future steps_x000D_
configurator.save();_x000D_
_x000D_
report();_x000D_
_x000D_
return runner.succeeds();_x000D_
}_x000D_
_x000D_
/**_x000D_
* Generate EP file suited for Kadaster and OGC Json schema._x000D_
* _x000D_
* @throws Exception_x000D_
*/_x000D_
public boolean generate() throws Exception {_x000D_
_x000D_
// create a transformer_x000D_
Transformer transformer = new Transformer();_x000D_
_x000D_
boolean succeeds = true;_x000D_
_x000D_
runner.debug(logger,"CHAIN","Generating EP");_x000D_
_x000D_
String epSchema = (requiresMIM() ? "EP2.xsd" : "EP.xsd");_x000D_
_x000D_
transformer.setXslParm("ep-schema-path","xsd/" + epSchema); _x000D_
_x000D_
// Create EP_x000D_
if (requiresMIM()) {_x000D_
// check of MIM resultaat beschikbaar is _x000D_
succeeds = succeeds && AnyFile.exists(configurator.getXParm("properties/WORK_MIMFORMAT_XMLPATH",false));_x000D_
// verwerk MIM naar EP_x000D_
succeeds = succeeds && transformer.transformStep("properties/WORK_MIMFORMAT_XMLPATH","properties/WORK_EP_XMLPATH_PRE", "properties/IMVERTOR_EP2_XSLPATH_PRE");_x000D_
succeeds = succeeds && transformer.transformStep("properties/WORK_EP_XMLPATH_PRE","properties/WORK_EP_XMLPATH_CORE", "properties/IMVERTOR_EP2_XSLPATH_CORE");_x000D_
succeeds = succeeds && transformer.transformStep("properties/WORK_EP_XMLPATH_CORE","properties/WORK_EP_XMLPATH_FINAL", "properties/IMVERTOR_EP2_XSLPATH_POST");_x000D_
} else _x000D_
succeeds = succeeds && transformer.transformStep("properties/WORK_EMBELLISH_FILE","properties/WORK_EP_XMLPATH_FINAL", "properties/IMVERTOR_EP_XSLPATH");_x000D_
_x000D_
_x000D_
// if this succeeds, copy the EP schema to the app and validate_x000D_
if (succeeds) {_x000D_
AnyFolder workAppFolder = new AnyFolder(Configurator.getInstance().getXParm("system/work-app-folder-path"));_x000D_
_x000D_
XmlFile resultEpFile = new XmlFile(configurator.getXParm("properties/WORK_EP_XMLPATH_FINAL"));_x000D_
XmlFile targetEpFile = new XmlFile(workAppFolder.getCanonicalPath() + "/ep/ep.xml"); // TODO nette naam, bepaald door gebruiker oid._x000D_
resultEpFile.copyFile(targetEpFile);_x000D_
_x000D_
XmlFile managedSchemaFile = new XmlFile(Configurator.getInstance().getBaseFolder().getCanonicalPath() + "/etc/xsd/EP/" + epSchema);_x000D_
XmlFile targetSchemaFile = new XmlFile(workAppFolder.getCanonicalPath() + "/ep/xsd/" + epSchema);_x000D_
managedSchemaFile.copyFile(targetSchemaFile);_x000D_
_x000D_
// Debug: test if EP is okay_x000D_
succeeds = succeeds && resultEpFile.isValid();_x000D_
}_x000D_
configurator.setXParm("system/ep-schema-created",succeeds);_x000D_
configurator.setXParm("system/ep-schema-version",requiresMIM() ? "2" : "1"); // when MIM based, generated EP version 2_x000D_
_x000D_
return succeeds;_x000D_
}_x000D_
_x000D_
public static Boolean requiresMIM() throws IOException, ConfiguratorException {_x000D_
// bepaal of hier de MIM schema variant moet worden gebruikt_x000D_
String jsonschemasource = Configurator.getInstance().getXParm("cli/jsonschemasource",false);_x000D_
return (jsonschemasource == null || jsonschemasource.equals("MIM"));_x000D_
} _x000D_
_x000D_
}_x000D_
| Imvertor/Imvertor-Maven | src/main/java/nl/imvertor/EpCompiler/EpCompiler.java | 1,599 | // check of MIM resultaat beschikbaar is _x000D_ | line_comment | nl | /*_x000D_
* Copyright (C) 2016 Dienst voor het kadaster en de openbare registers_x000D_
* _x000D_
* This file is part of Imvertor._x000D_
*_x000D_
* Imvertor is free software: you can redistribute it and/or modify_x000D_
* it under the terms of the GNU General Public License as published by_x000D_
* the Free Software Foundation, either version 3 of the License, or_x000D_
* (at your option) any later version._x000D_
*_x000D_
* Imvertor is distributed in the hope that it will be useful,_x000D_
* but WITHOUT ANY WARRANTY; without even the implied warranty of_x000D_
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the_x000D_
* GNU General Public License for more details._x000D_
*_x000D_
* You should have received a copy of the GNU General Public License_x000D_
* along with Imvertor. If not, see <http://www.gnu.org/licenses/>._x000D_
*_x000D_
*/_x000D_
_x000D_
package nl.imvertor.EpCompiler;_x000D_
_x000D_
import java.io.IOException;_x000D_
_x000D_
import org.apache.log4j.Logger;_x000D_
_x000D_
import nl.imvertor.common.Configurator;_x000D_
import nl.imvertor.common.Step;_x000D_
import nl.imvertor.common.Transformer;_x000D_
import nl.imvertor.common.exceptions.ConfiguratorException;_x000D_
import nl.imvertor.common.file.AnyFile;_x000D_
import nl.imvertor.common.file.AnyFolder;_x000D_
import nl.imvertor.common.file.XmlFile;_x000D_
_x000D_
// see also https://github.com/Imvertor/Imvertor-Maven/issues/56_x000D_
_x000D_
public class EpCompiler extends Step {_x000D_
_x000D_
protected static final Logger logger = Logger.getLogger(EpCompiler.class);_x000D_
_x000D_
public static final String STEP_NAME = "EpCompiler";_x000D_
public static final String VC_IDENTIFIER = "$Id: $";_x000D_
_x000D_
/**_x000D_
* run the main translation_x000D_
*/_x000D_
public boolean run() throws Exception{_x000D_
_x000D_
// set up the configuration for this step_x000D_
configurator.setActiveStepName(STEP_NAME);_x000D_
prepare();_x000D_
_x000D_
runner.info(logger,"Compiling EP");_x000D_
_x000D_
generate();_x000D_
_x000D_
configurator.setStepDone(STEP_NAME);_x000D_
_x000D_
// save any changes to the work configuration for report and future steps_x000D_
configurator.save();_x000D_
_x000D_
report();_x000D_
_x000D_
return runner.succeeds();_x000D_
}_x000D_
_x000D_
/**_x000D_
* Generate EP file suited for Kadaster and OGC Json schema._x000D_
* _x000D_
* @throws Exception_x000D_
*/_x000D_
public boolean generate() throws Exception {_x000D_
_x000D_
// create a transformer_x000D_
Transformer transformer = new Transformer();_x000D_
_x000D_
boolean succeeds = true;_x000D_
_x000D_
runner.debug(logger,"CHAIN","Generating EP");_x000D_
_x000D_
String epSchema = (requiresMIM() ? "EP2.xsd" : "EP.xsd");_x000D_
_x000D_
transformer.setXslParm("ep-schema-path","xsd/" + epSchema); _x000D_
_x000D_
// Create EP_x000D_
if (requiresMIM()) {_x000D_
// check of<SUF>
succeeds = succeeds && AnyFile.exists(configurator.getXParm("properties/WORK_MIMFORMAT_XMLPATH",false));_x000D_
// verwerk MIM naar EP_x000D_
succeeds = succeeds && transformer.transformStep("properties/WORK_MIMFORMAT_XMLPATH","properties/WORK_EP_XMLPATH_PRE", "properties/IMVERTOR_EP2_XSLPATH_PRE");_x000D_
succeeds = succeeds && transformer.transformStep("properties/WORK_EP_XMLPATH_PRE","properties/WORK_EP_XMLPATH_CORE", "properties/IMVERTOR_EP2_XSLPATH_CORE");_x000D_
succeeds = succeeds && transformer.transformStep("properties/WORK_EP_XMLPATH_CORE","properties/WORK_EP_XMLPATH_FINAL", "properties/IMVERTOR_EP2_XSLPATH_POST");_x000D_
} else _x000D_
succeeds = succeeds && transformer.transformStep("properties/WORK_EMBELLISH_FILE","properties/WORK_EP_XMLPATH_FINAL", "properties/IMVERTOR_EP_XSLPATH");_x000D_
_x000D_
_x000D_
// if this succeeds, copy the EP schema to the app and validate_x000D_
if (succeeds) {_x000D_
AnyFolder workAppFolder = new AnyFolder(Configurator.getInstance().getXParm("system/work-app-folder-path"));_x000D_
_x000D_
XmlFile resultEpFile = new XmlFile(configurator.getXParm("properties/WORK_EP_XMLPATH_FINAL"));_x000D_
XmlFile targetEpFile = new XmlFile(workAppFolder.getCanonicalPath() + "/ep/ep.xml"); // TODO nette naam, bepaald door gebruiker oid._x000D_
resultEpFile.copyFile(targetEpFile);_x000D_
_x000D_
XmlFile managedSchemaFile = new XmlFile(Configurator.getInstance().getBaseFolder().getCanonicalPath() + "/etc/xsd/EP/" + epSchema);_x000D_
XmlFile targetSchemaFile = new XmlFile(workAppFolder.getCanonicalPath() + "/ep/xsd/" + epSchema);_x000D_
managedSchemaFile.copyFile(targetSchemaFile);_x000D_
_x000D_
// Debug: test if EP is okay_x000D_
succeeds = succeeds && resultEpFile.isValid();_x000D_
}_x000D_
configurator.setXParm("system/ep-schema-created",succeeds);_x000D_
configurator.setXParm("system/ep-schema-version",requiresMIM() ? "2" : "1"); // when MIM based, generated EP version 2_x000D_
_x000D_
return succeeds;_x000D_
}_x000D_
_x000D_
public static Boolean requiresMIM() throws IOException, ConfiguratorException {_x000D_
// bepaal of hier de MIM schema variant moet worden gebruikt_x000D_
String jsonschemasource = Configurator.getInstance().getXParm("cli/jsonschemasource",false);_x000D_
return (jsonschemasource == null || jsonschemasource.equals("MIM"));_x000D_
} _x000D_
_x000D_
}_x000D_
| True | 1,942 | 18 | 2,171 | 19 | 2,183 | 14 | 2,171 | 19 | 2,475 | 19 | false | false | false | false | false | true |
4,296 | 140637_15 | package org.xmlvm.ios;
import java.util.*;
import org.xmlvm.XMLVMSkeletonOnly;
@XMLVMSkeletonOnly
public class CMTimeRange {
/*
* Variables
*/
public CMTime start;
public CMTime duration;
/*
* Static methods
*/
/**
* CMTimeRange CMTimeRangeFromTimeToTime( CMTime start, CMTime end ) ;
*/
public static CMTimeRange fromTimeToTime(CMTime start, CMTime end){
throw new RuntimeException("Stub");
}
/**
* CMTimeRange CMTimeRangeMakeFromDictionary( CFDictionaryRef dict) ;
*/
public static CMTimeRange makeFromDictionary(CFDictionary dict){
throw new RuntimeException("Stub");
}
/**
* CFStringRef CMTimeRangeCopyDescription( CFAllocatorRef allocator, CMTimeRange range) ;
*/
public static String copyDescription(CFAllocator allocator, CMTimeRange range){
throw new RuntimeException("Stub");
}
/*
* Constructors
*/
/**
* CMTimeRange CMTimeRangeMake( CMTime start, CMTime duration) ;
*/
public CMTimeRange(CMTime start, CMTime duration) {}
/** Default constructor */
CMTimeRange() {}
/*
* Instance methods
*/
/**
* CMTimeRange CMTimeRangeGetUnion( CMTimeRange range1, CMTimeRange range2) ;
*/
public CMTimeRange getUnion(CMTimeRange range2){
throw new RuntimeException("Stub");
}
/**
* CMTimeRange CMTimeRangeGetIntersection( CMTimeRange range1, CMTimeRange range2) ;
*/
public CMTimeRange getIntersection(CMTimeRange range2){
throw new RuntimeException("Stub");
}
/**
* Boolean CMTimeRangeEqual( CMTimeRange range1, CMTimeRange range2) ;
*/
public byte equal(CMTimeRange range2){
throw new RuntimeException("Stub");
}
/**
* Boolean CMTimeRangeContainsTime( CMTimeRange range, CMTime time) ;
*/
public byte containsTime(CMTime time){
throw new RuntimeException("Stub");
}
/**
* Boolean CMTimeRangeContainsTimeRange( CMTimeRange range1, CMTimeRange range2) ;
*/
public byte containsTimeRange(CMTimeRange range2){
throw new RuntimeException("Stub");
}
/**
* CMTime CMTimeRangeGetEnd( CMTimeRange range) ;
*/
public CMTime getEnd(){
throw new RuntimeException("Stub");
}
/**
* CFDictionaryRef CMTimeRangeCopyAsDictionary( CMTimeRange range, CFAllocatorRef allocator) ;
*/
public CFDictionary copyAsDictionary(CFAllocator allocator){
throw new RuntimeException("Stub");
}
/**
* void CMTimeRangeShow( CMTimeRange range) ;
*/
public void show(){
throw new RuntimeException("Stub");
}
}
| shannah/cn1 | Ports/iOSPort/xmlvm/src/ios/org/xmlvm/ios/CMTimeRange.java | 783 | /**
* void CMTimeRangeShow( CMTimeRange range) ;
*/ | block_comment | nl | package org.xmlvm.ios;
import java.util.*;
import org.xmlvm.XMLVMSkeletonOnly;
@XMLVMSkeletonOnly
public class CMTimeRange {
/*
* Variables
*/
public CMTime start;
public CMTime duration;
/*
* Static methods
*/
/**
* CMTimeRange CMTimeRangeFromTimeToTime( CMTime start, CMTime end ) ;
*/
public static CMTimeRange fromTimeToTime(CMTime start, CMTime end){
throw new RuntimeException("Stub");
}
/**
* CMTimeRange CMTimeRangeMakeFromDictionary( CFDictionaryRef dict) ;
*/
public static CMTimeRange makeFromDictionary(CFDictionary dict){
throw new RuntimeException("Stub");
}
/**
* CFStringRef CMTimeRangeCopyDescription( CFAllocatorRef allocator, CMTimeRange range) ;
*/
public static String copyDescription(CFAllocator allocator, CMTimeRange range){
throw new RuntimeException("Stub");
}
/*
* Constructors
*/
/**
* CMTimeRange CMTimeRangeMake( CMTime start, CMTime duration) ;
*/
public CMTimeRange(CMTime start, CMTime duration) {}
/** Default constructor */
CMTimeRange() {}
/*
* Instance methods
*/
/**
* CMTimeRange CMTimeRangeGetUnion( CMTimeRange range1, CMTimeRange range2) ;
*/
public CMTimeRange getUnion(CMTimeRange range2){
throw new RuntimeException("Stub");
}
/**
* CMTimeRange CMTimeRangeGetIntersection( CMTimeRange range1, CMTimeRange range2) ;
*/
public CMTimeRange getIntersection(CMTimeRange range2){
throw new RuntimeException("Stub");
}
/**
* Boolean CMTimeRangeEqual( CMTimeRange range1, CMTimeRange range2) ;
*/
public byte equal(CMTimeRange range2){
throw new RuntimeException("Stub");
}
/**
* Boolean CMTimeRangeContainsTime( CMTimeRange range, CMTime time) ;
*/
public byte containsTime(CMTime time){
throw new RuntimeException("Stub");
}
/**
* Boolean CMTimeRangeContainsTimeRange( CMTimeRange range1, CMTimeRange range2) ;
*/
public byte containsTimeRange(CMTimeRange range2){
throw new RuntimeException("Stub");
}
/**
* CMTime CMTimeRangeGetEnd( CMTimeRange range) ;
*/
public CMTime getEnd(){
throw new RuntimeException("Stub");
}
/**
* CFDictionaryRef CMTimeRangeCopyAsDictionary( CMTimeRange range, CFAllocatorRef allocator) ;
*/
public CFDictionary copyAsDictionary(CFAllocator allocator){
throw new RuntimeException("Stub");
}
/**
* void CMTimeRangeShow( CMTimeRange<SUF>*/
public void show(){
throw new RuntimeException("Stub");
}
}
| False | 621 | 17 | 690 | 17 | 734 | 19 | 690 | 17 | 845 | 21 | false | false | false | false | false | true |
2,672 | 18882_3 | package org.waag.ah.model.json;
import java.math.BigDecimal;
import java.util.Set;
import org.codehaus.jackson.annotate.JsonProperty;
import org.waag.ah.model.rdf.VenueType;
public abstract class VenueJson extends AHRDFObjectJson {
// ah:attachment [http] ah:venues/0669e8c5-75b2-47ce-bef3-f1cfd2acc192/attachments/1 [http] -
// ah:attachment [http] ah:venues/0669e8c5-75b2-47ce-bef3-f1cfd2acc192/attachments/2 [http] -
// ah:cidn [http] "0669e8c5-75b2-47ce-bef3-f1cfd2acc192"^^<xsd:string> -
// ah:disabilityInformation [http] "Bereikbaarheid: er is een trein/metro/tram/bus in de buurt van de locatie (binnen 500 m), voorrijden bij entree is toegestaan.<BR> Toegankelijkheid:naast hoofdingang zijn er ook alternatieven ingangen, deurbreedte is minimaal 80 cm, lift aanwezig, zaal/zalen bereikbaar via lift.<BR> Speciale voorzieningen: rolstoelplaatsen aanwezig in zaal/zalen, locatie is geheel rookvrij."@nl -
// ah:openingHours [http] "Kassa open een uur voor aanvang"@nl -
// ah:publicTransportInformation [http] "(tram) 3; (bus) 35; (parkeren) parkeerterrein op de pieren vlakbij theater"@nl -
// ah:room [http] ah:venues/0669e8c5-75b2-47ce-bef3-f1cfd2acc192/rooms/veemcaf%C3%A9 [http] -
// ah:shortDescription [http] "Een productiehuis voor mime, beeldend theater en dans en presenteert daarnaast gastvoorstellingen uit binnen- en buitenland. Het is gevestigd op de 3e verdieping van een gerenoveerd 19e eeuws pakhuis met een schitterend uitzicht op het IJ."@nl -
// ah:venueType [http] ah:VenueTypeTheater [http] -
// dc:created [http] "2012-03-03T19:11:10Z"^^<xsd:string> -
// dc:description [http] "Een productiehuis voor mime, beeldend theater en dans en presenteert daarnaast gastvoorstellingen uit binnen- en buitenland. Het is gevestigd op de 3e verdieping van een gerenoveerd 19e eeuws pakhuis met een schitterend uitzicht op het IJ."@nl -
// dc:title [http] "veem theater"@nl -
// rdf:type [http] ah:Venue [http] -
// owl:sameAs [http] nub:locations/0669e8c5-75b2-47ce-bef3-f1cfd2acc192 [http] -
// geo:lat [http] "52.3902473"^^<xsd:decimal> -
// geo:long [http] "4.8862872"^^<xsd:decimal> -
// vcard:locality [http] "Amsterdam" -
// vcard:postal-code [http] "1013 CR" -
// vcard:street-address [http] "Van Diemenstraat 410" -
// foaf:homepage [http]
@JsonProperty()
public abstract String getURI();
@JsonProperty
public abstract String getCidn();
@JsonProperty
public abstract String getTitle();
@JsonProperty
public abstract String getDescription();
@JsonProperty
public abstract String getShortDescription();
@JsonProperty
public abstract String getLocality();
@JsonProperty
public abstract String getPostalCode();
@JsonProperty
public abstract String getStreetAddress();
@JsonProperty
public abstract String getHomepage();
@JsonProperty
public abstract Set<RoomJson> getRooms();
@JsonProperty
public abstract Set<AttachmentJson> getAttachments();
@JsonProperty
public abstract BigDecimal getLatitude();
@JsonProperty
public abstract BigDecimal getLongitude();
@JsonProperty
public abstract Set<String> getTags();
@JsonProperty
public abstract VenueType getVenueType();
}
| erfgoed-en-locatie/artsholland-platform | artsholland-core/src/main/java/org/waag/ah/model/json/VenueJson.java | 1,244 | // ah:disabilityInformation [http] "Bereikbaarheid: er is een trein/metro/tram/bus in de buurt van de locatie (binnen 500 m), voorrijden bij entree is toegestaan.<BR> Toegankelijkheid:naast hoofdingang zijn er ook alternatieven ingangen, deurbreedte is minimaal 80 cm, lift aanwezig, zaal/zalen bereikbaar via lift.<BR> Speciale voorzieningen: rolstoelplaatsen aanwezig in zaal/zalen, locatie is geheel rookvrij."@nl - | line_comment | nl | package org.waag.ah.model.json;
import java.math.BigDecimal;
import java.util.Set;
import org.codehaus.jackson.annotate.JsonProperty;
import org.waag.ah.model.rdf.VenueType;
public abstract class VenueJson extends AHRDFObjectJson {
// ah:attachment [http] ah:venues/0669e8c5-75b2-47ce-bef3-f1cfd2acc192/attachments/1 [http] -
// ah:attachment [http] ah:venues/0669e8c5-75b2-47ce-bef3-f1cfd2acc192/attachments/2 [http] -
// ah:cidn [http] "0669e8c5-75b2-47ce-bef3-f1cfd2acc192"^^<xsd:string> -
// ah:disabilityInformation [http]<SUF>
// ah:openingHours [http] "Kassa open een uur voor aanvang"@nl -
// ah:publicTransportInformation [http] "(tram) 3; (bus) 35; (parkeren) parkeerterrein op de pieren vlakbij theater"@nl -
// ah:room [http] ah:venues/0669e8c5-75b2-47ce-bef3-f1cfd2acc192/rooms/veemcaf%C3%A9 [http] -
// ah:shortDescription [http] "Een productiehuis voor mime, beeldend theater en dans en presenteert daarnaast gastvoorstellingen uit binnen- en buitenland. Het is gevestigd op de 3e verdieping van een gerenoveerd 19e eeuws pakhuis met een schitterend uitzicht op het IJ."@nl -
// ah:venueType [http] ah:VenueTypeTheater [http] -
// dc:created [http] "2012-03-03T19:11:10Z"^^<xsd:string> -
// dc:description [http] "Een productiehuis voor mime, beeldend theater en dans en presenteert daarnaast gastvoorstellingen uit binnen- en buitenland. Het is gevestigd op de 3e verdieping van een gerenoveerd 19e eeuws pakhuis met een schitterend uitzicht op het IJ."@nl -
// dc:title [http] "veem theater"@nl -
// rdf:type [http] ah:Venue [http] -
// owl:sameAs [http] nub:locations/0669e8c5-75b2-47ce-bef3-f1cfd2acc192 [http] -
// geo:lat [http] "52.3902473"^^<xsd:decimal> -
// geo:long [http] "4.8862872"^^<xsd:decimal> -
// vcard:locality [http] "Amsterdam" -
// vcard:postal-code [http] "1013 CR" -
// vcard:street-address [http] "Van Diemenstraat 410" -
// foaf:homepage [http]
@JsonProperty()
public abstract String getURI();
@JsonProperty
public abstract String getCidn();
@JsonProperty
public abstract String getTitle();
@JsonProperty
public abstract String getDescription();
@JsonProperty
public abstract String getShortDescription();
@JsonProperty
public abstract String getLocality();
@JsonProperty
public abstract String getPostalCode();
@JsonProperty
public abstract String getStreetAddress();
@JsonProperty
public abstract String getHomepage();
@JsonProperty
public abstract Set<RoomJson> getRooms();
@JsonProperty
public abstract Set<AttachmentJson> getAttachments();
@JsonProperty
public abstract BigDecimal getLatitude();
@JsonProperty
public abstract BigDecimal getLongitude();
@JsonProperty
public abstract Set<String> getTags();
@JsonProperty
public abstract VenueType getVenueType();
}
| False | 1,077 | 143 | 1,218 | 162 | 1,136 | 123 | 1,222 | 164 | 1,295 | 149 | false | false | false | false | false | true |
1,852 | 44930_0 | package org.imec.ivlab.core.kmehr.model;
import java.io.Serializable;
import java.util.Objects;
public enum FrequencyCode implements Serializable {
UH("UH", Frequency.HOUR, 0.5, "Om het half uur", true),
U("U", Frequency.HOUR, 1, "Om het uur", true),
UT("UT", Frequency.HOUR, 2, "Om de twee uren", true),
UD("UD", Frequency.HOUR, 3, "Om de 3 uren", true),
UV("UV", Frequency.HOUR, 4, "om de 4 uren", true),
UQ("UQ", Frequency.HOUR, 5, "om de 5 uren", true), // niet toegelaten in medicatieschema
UZ("UZ", Frequency.HOUR, 6, "om de 6 uren", true),
US("US", Frequency.HOUR, 7, "om de 7 uren", true), // niet toegelaten in medicatieschema
UA("UA", Frequency.HOUR, 8, "om de 8 uren", true),
UN("UN", Frequency.HOUR, 9, "om de 9 uren", true), // niet toegelaten in medicatieschema
UX("UX", Frequency.HOUR, 10, "om de 10 uren", true),// niet toegelaten in medicatieschema
UE("UE", Frequency.HOUR, 11, "om de 11 uren", true),// niet toegelaten in medicatieschema
UW("UW", Frequency.HOUR, 12, "om de 12 uren", true),
D("D", Frequency.DAY, 1, "Dagelijks", true),
O1("O1", Frequency.DAY, 2, "Om de 2 dagen", true), // TODO: uit te klaren. Volgens kmehr: om de dag, volgens medicatie schema cookbook om de 2 dagen
DT("DT", Frequency.DAY, 2, "om de 2 dagen", true),
DD("DD", Frequency.DAY, 3, "Om de 3 dagen", true),
DV("DV", Frequency.DAY, 4, "Om de 4 dagen", true),
DQ("DQ", Frequency.DAY, 5, "Om de 5 dagen", true),
DZ("DZ", Frequency.DAY, 6, "Om de 6 dagen", true),
DA("DA", Frequency.DAY, 8, "Om de 8 dagen", true),
DN("DN", Frequency.DAY, 9, "Om de 9 dagen", true),
DX("DX", Frequency.DAY, 10, "Om de 10 dagen", true),
DE("DE", Frequency.DAY, 11, "Om de 11 dagen", true),
DW("DW", Frequency.DAY, 12, "Om de 12 dagen", true),
W("W", Frequency.WEEK, 1, "Wekelijks", true),
WT("WT", Frequency.WEEK, 2, "Om de 2 weken", true),
WD("WD", Frequency.WEEK, 3, "Om de 3 weken", true),
WV("WV", Frequency.WEEK, 4, "Om de 4 weken", true),
WQ("WQ", Frequency.WEEK, 5, "Om de 5 weken", true),
WZ("WZ", Frequency.WEEK, 6, "Om de 6 weken", true),
WS("WS", Frequency.WEEK, 7, "Om de 7 weken", true),
WA("WA", Frequency.WEEK, 8, "Om de 8 weken", true),
WN("WN", Frequency.WEEK, 9, "Om de 9 weken", true),
WX("WX", Frequency.WEEK, 10, "Om de 10 weken", true),
WE("WE", Frequency.WEEK, 11, "Om de 11 weken", true),
WW("WW", Frequency.WEEK, 12, "Om de 12 weken", true),
WP("WP", Frequency.WEEK, 24, "Om de 24 weken", true),
M("M", Frequency.MONTH, 1, "Maandelijks", true),
MT("MT", Frequency.MONTH, 2, "Om de 2 maanden", true),
MD("MD", Frequency.MONTH, 3, "Om de 3 maanden", true),
MV("MV", Frequency.MONTH, 4, "Om de 4 maanden", true),
MQ("MQ", Frequency.MONTH, 5, "Om de 5 maanden", true),
MZ2("MZ2", Frequency.MONTH, 6, "Om de 6 maanden", true),
MS("MS", Frequency.MONTH, 7, "Om de 7 maanden", true),
MA("MA", Frequency.MONTH, 8, "Om de 8 maanden", true),
MN("MN", Frequency.MONTH, 9, "Om de 9 maanden", true),
MX("MX", Frequency.MONTH, 10, "Om de 10 maanden", true),
ME("ME", Frequency.MONTH, 11, "Om de 11 maanden", true),
MC("MC", Frequency.MONTH, 18, "Om de 18 maanden", true),
JH2("JH2", Frequency.MONTH, 6, "Halfjaarlijks", true), // YEAR, 0.5 in specs
J("J", Frequency.YEAR, 1, "Jaarlijks", true),
JT("JT", Frequency.YEAR, 2, "Om de 2 jaar", true),
JD("JD", Frequency.YEAR, 3, "Om de 3 jaar", true),
JV("JV", Frequency.YEAR, 4, "Om de 4 jaar", true),
JQ("JQ", Frequency.YEAR, 5, "Om de 5 jaar", true),
JZ("JZ", Frequency.YEAR, 6, "Om de 6 jaar", true),
ONDEMAND("ondemand", null, 0, "Op aanvraag", false);
private Frequency frequency;
private Double multiplier;
private String translation;
private boolean supportedByVitalink;
private String value;
FrequencyCode(String value, Frequency frequency, int multiplier, String translation, boolean supportedByVitalink) {
this(value, frequency, Double.valueOf(multiplier), translation, supportedByVitalink);
}
FrequencyCode(String value, Frequency frequency, Double multiplier, String translation, boolean supportedByVitalink) {
this.value = value;
this.frequency = frequency;
this.multiplier = multiplier;
this.translation = translation;
this.supportedByVitalink = supportedByVitalink;
}
public Double getMultiplier() {
return multiplier;
}
public Frequency getFrequency() {
return frequency;
}
public String getTranslation() {
return translation;
}
public boolean hasFrequency(Frequency frequency) {
return Objects.equals(this.frequency, frequency);
}
public boolean isSupportedByVitalink() {
return supportedByVitalink;
}
public static FrequencyCode fromValue(String input) {
for (FrequencyCode frequencyCode : values()) {
if (frequencyCode.value.equalsIgnoreCase(input)) {
return frequencyCode;
}
}
throw new IllegalArgumentException("Invalid frequencycode value: " + input);
}
public String getValue() {
return value;
}
} | Vitalink/evs | core/src/main/java/org/imec/ivlab/core/kmehr/model/FrequencyCode.java | 2,026 | // niet toegelaten in medicatieschema | line_comment | nl | package org.imec.ivlab.core.kmehr.model;
import java.io.Serializable;
import java.util.Objects;
public enum FrequencyCode implements Serializable {
UH("UH", Frequency.HOUR, 0.5, "Om het half uur", true),
U("U", Frequency.HOUR, 1, "Om het uur", true),
UT("UT", Frequency.HOUR, 2, "Om de twee uren", true),
UD("UD", Frequency.HOUR, 3, "Om de 3 uren", true),
UV("UV", Frequency.HOUR, 4, "om de 4 uren", true),
UQ("UQ", Frequency.HOUR, 5, "om de 5 uren", true), // niet toegelaten<SUF>
UZ("UZ", Frequency.HOUR, 6, "om de 6 uren", true),
US("US", Frequency.HOUR, 7, "om de 7 uren", true), // niet toegelaten in medicatieschema
UA("UA", Frequency.HOUR, 8, "om de 8 uren", true),
UN("UN", Frequency.HOUR, 9, "om de 9 uren", true), // niet toegelaten in medicatieschema
UX("UX", Frequency.HOUR, 10, "om de 10 uren", true),// niet toegelaten in medicatieschema
UE("UE", Frequency.HOUR, 11, "om de 11 uren", true),// niet toegelaten in medicatieschema
UW("UW", Frequency.HOUR, 12, "om de 12 uren", true),
D("D", Frequency.DAY, 1, "Dagelijks", true),
O1("O1", Frequency.DAY, 2, "Om de 2 dagen", true), // TODO: uit te klaren. Volgens kmehr: om de dag, volgens medicatie schema cookbook om de 2 dagen
DT("DT", Frequency.DAY, 2, "om de 2 dagen", true),
DD("DD", Frequency.DAY, 3, "Om de 3 dagen", true),
DV("DV", Frequency.DAY, 4, "Om de 4 dagen", true),
DQ("DQ", Frequency.DAY, 5, "Om de 5 dagen", true),
DZ("DZ", Frequency.DAY, 6, "Om de 6 dagen", true),
DA("DA", Frequency.DAY, 8, "Om de 8 dagen", true),
DN("DN", Frequency.DAY, 9, "Om de 9 dagen", true),
DX("DX", Frequency.DAY, 10, "Om de 10 dagen", true),
DE("DE", Frequency.DAY, 11, "Om de 11 dagen", true),
DW("DW", Frequency.DAY, 12, "Om de 12 dagen", true),
W("W", Frequency.WEEK, 1, "Wekelijks", true),
WT("WT", Frequency.WEEK, 2, "Om de 2 weken", true),
WD("WD", Frequency.WEEK, 3, "Om de 3 weken", true),
WV("WV", Frequency.WEEK, 4, "Om de 4 weken", true),
WQ("WQ", Frequency.WEEK, 5, "Om de 5 weken", true),
WZ("WZ", Frequency.WEEK, 6, "Om de 6 weken", true),
WS("WS", Frequency.WEEK, 7, "Om de 7 weken", true),
WA("WA", Frequency.WEEK, 8, "Om de 8 weken", true),
WN("WN", Frequency.WEEK, 9, "Om de 9 weken", true),
WX("WX", Frequency.WEEK, 10, "Om de 10 weken", true),
WE("WE", Frequency.WEEK, 11, "Om de 11 weken", true),
WW("WW", Frequency.WEEK, 12, "Om de 12 weken", true),
WP("WP", Frequency.WEEK, 24, "Om de 24 weken", true),
M("M", Frequency.MONTH, 1, "Maandelijks", true),
MT("MT", Frequency.MONTH, 2, "Om de 2 maanden", true),
MD("MD", Frequency.MONTH, 3, "Om de 3 maanden", true),
MV("MV", Frequency.MONTH, 4, "Om de 4 maanden", true),
MQ("MQ", Frequency.MONTH, 5, "Om de 5 maanden", true),
MZ2("MZ2", Frequency.MONTH, 6, "Om de 6 maanden", true),
MS("MS", Frequency.MONTH, 7, "Om de 7 maanden", true),
MA("MA", Frequency.MONTH, 8, "Om de 8 maanden", true),
MN("MN", Frequency.MONTH, 9, "Om de 9 maanden", true),
MX("MX", Frequency.MONTH, 10, "Om de 10 maanden", true),
ME("ME", Frequency.MONTH, 11, "Om de 11 maanden", true),
MC("MC", Frequency.MONTH, 18, "Om de 18 maanden", true),
JH2("JH2", Frequency.MONTH, 6, "Halfjaarlijks", true), // YEAR, 0.5 in specs
J("J", Frequency.YEAR, 1, "Jaarlijks", true),
JT("JT", Frequency.YEAR, 2, "Om de 2 jaar", true),
JD("JD", Frequency.YEAR, 3, "Om de 3 jaar", true),
JV("JV", Frequency.YEAR, 4, "Om de 4 jaar", true),
JQ("JQ", Frequency.YEAR, 5, "Om de 5 jaar", true),
JZ("JZ", Frequency.YEAR, 6, "Om de 6 jaar", true),
ONDEMAND("ondemand", null, 0, "Op aanvraag", false);
private Frequency frequency;
private Double multiplier;
private String translation;
private boolean supportedByVitalink;
private String value;
FrequencyCode(String value, Frequency frequency, int multiplier, String translation, boolean supportedByVitalink) {
this(value, frequency, Double.valueOf(multiplier), translation, supportedByVitalink);
}
FrequencyCode(String value, Frequency frequency, Double multiplier, String translation, boolean supportedByVitalink) {
this.value = value;
this.frequency = frequency;
this.multiplier = multiplier;
this.translation = translation;
this.supportedByVitalink = supportedByVitalink;
}
public Double getMultiplier() {
return multiplier;
}
public Frequency getFrequency() {
return frequency;
}
public String getTranslation() {
return translation;
}
public boolean hasFrequency(Frequency frequency) {
return Objects.equals(this.frequency, frequency);
}
public boolean isSupportedByVitalink() {
return supportedByVitalink;
}
public static FrequencyCode fromValue(String input) {
for (FrequencyCode frequencyCode : values()) {
if (frequencyCode.value.equalsIgnoreCase(input)) {
return frequencyCode;
}
}
throw new IllegalArgumentException("Invalid frequencycode value: " + input);
}
public String getValue() {
return value;
}
} | True | 1,678 | 11 | 1,779 | 11 | 1,754 | 9 | 1,779 | 11 | 2,075 | 11 | false | false | false | false | false | true |
19 | 132832_0 | package Shipflex;
import Boat.Boat;
import Boat.Option;
import Customer.CustomCustomer;
import Customer.BusinessCustomer;
import Customer.FoundationCustomer;
import Customer.GovermentCustomer;
import DataInOut.Info;
import DataInOut.Printer;
import java.util.ArrayList;
import java.util.List;
public class Quote {
private Company companyShipbuild;
private CustomCustomer customCustomer;
private BusinessCustomer businessCustomer;
private GovermentCustomer govermentCustomer;
private FoundationCustomer foundationCustomer;
private String date;
private String quoteDate;
private String about;
private double workHoursCost;
private Boat boat;
public Quote(Company companyShipbuild, Boat boat) {
this.companyShipbuild = companyShipbuild;
this.businessCustomer = null;
this.customCustomer = null;
this.govermentCustomer = null;
this.foundationCustomer = null;
this.boat = boat;
}
public void setCustomCustomer(CustomCustomer customCustomer) {
this.customCustomer = customCustomer;
}
public void setBusinessCustomer(BusinessCustomer businessCustomer) {
this.businessCustomer = businessCustomer;
}
public void setGovermentCustomer(GovermentCustomer govermentCustomer) {
this.govermentCustomer = govermentCustomer;
}
public void setFoundationCustomer(FoundationCustomer foundationCustomer) {
this.foundationCustomer = foundationCustomer;
}
public void setAbout(String about) {
this.about = about;
}
public void setDate(String date) {
this.date = date;
}
public void setQuoteDate(String quoteDate) {
this.quoteDate = quoteDate;
}
public void setBoat(Boat boat) {
this.boat = boat;
}
public Boat getBoat() {
return boat;
}
public CustomCustomer getCustomCustomer() {
return customCustomer;
}
public BusinessCustomer getBusinessCustomer() {
return businessCustomer;
}
public GovermentCustomer getGovermentCustomer() {
return govermentCustomer;
}
public FoundationCustomer getFoundationCustomer() {
return foundationCustomer;
}
public void setWorkHoursCost(double workHoursCost) {
this.workHoursCost = workHoursCost;
}
public void printCustomer() {
switch (checkCustomerType()) {
case "goverment":
govermentCustomer.printCustomer();
break;
case "business":
businessCustomer.printCustomer();
break;
case "foundation":
foundationCustomer.printCustomer();
break;
case "customer":
customCustomer.printCustomer();
break;
default:
Printer.getInstance().printLine("Nog geen klant toegevoegd");
break;
}
}
private String checkCustomerType() {
if (govermentCustomer != null) {
return "goverment";
} else if (businessCustomer != null) {
return "business";
} else if (customCustomer != null) {
return "customer";
} else if (foundationCustomer != null) {
return "foundation";
} else {
return "";
}
}
public void printOptions(boolean showIndex) {
for (Option option : this.boat.getOptions()) {
if (showIndex)
Info.printOptionInfo(option, Info.getOptions().indexOf(option));
else
Info.printOptionInfo(option, -1);
Printer.getInstance().emptyLine();
}
}
public void printDate() {
if (this.date != null && !this.date.equals("")) {
Printer.getInstance().printLine("Datum: " + this.date);
} else {
Printer.getInstance().printLine("Datum nog niet ingevuld");
}
if (this.quoteDate != null && !this.quoteDate.equals("")) {
Printer.getInstance().printLine("Geldigsheid datum: " + this.quoteDate);
} else {
Printer.getInstance().printLine("Geldigsheid datum nog niet ingevuld");
}
}
public void printBasicInformation() {
companyShipbuild.printCompany();
Printer.getInstance().emptyLine();
printCustomer();
Printer.getInstance().emptyLine();
printDate();
Printer.getInstance().emptyLine();
if(this.about != null && !this.about.equals("")) {
Printer.getInstance().printLine("Betreft: " + this.about);
}else {
Printer.getInstance().printLine("Betreft is nog niet ingevuld");
}
Printer.getInstance().emptyLine();
}
public void printQuote() {
Printer.getInstance().printCharacters(129, '━');
Printer.getInstance().emptyLine();
this.printBasicInformation();
Printer.getInstance().printCharacters(78, '﹏');
Printer.getInstance().emptyLine();
boat.printBoat();
Printer.getInstance().printCharacters(78, '﹏');
Printer.getInstance().emptyLine();
this.printOptions();
Printer.getInstance().emptyLine();
this.printTotal();
Printer.getInstance().emptyLine();
Printer.getInstance().printCharacters(129, '━');
}
public void printOptions() {
List<Option> essentialOptions = new ArrayList<>();
List<Option> extraOptions = new ArrayList<>();
for (Option option : boat.getOptions()) {
if (option.getEssentialForBoatType().contains(boat.getType().toLowerCase()))
essentialOptions.add(option);
else
extraOptions.add(option);
}
printOptionsListFormatted(essentialOptions);
printOptionsListFormatted(extraOptions);
}
private void printOptionsListFormatted(List<Option> options) {
for (Option option : options) {
option.printOptionInfoForBoat(boat.getType());
}
}
public int getDiscount() {
int discount = 0;
switch (checkCustomerType()) {
case "goverment":
discount = govermentCustomer.getDiscount();
break;
case "business":
discount = businessCustomer.getDiscount();
break;
case "foundation":
discount = foundationCustomer.getDiscount();
break;
case "customer":
discount = customCustomer.getDiscount();
break;
}
return 100 - discount;
}
public double calculatePercentage(int percentage, double price) {
return (price / 100) * percentage;
}
public double calculateBoatPrice() {
double price = 0;
price += boat.getBasePrice();
for (Option option : boat.getOptions()) {
price += option.getPrice();
}
return price;
}
public void printTotal() {
Printer.getInstance().emptyLine();
//Totaal prijs boot
double totalPriceBoat = calculateBoatPrice();
Printer.getInstance().printFormatInfo(String.format("Totaal prijs boot:"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
Printer.getInstance().emptyLine();
//Totaal prijs boot met korting
if (getDiscount() < 100 && getDiscount() > 0) {
totalPriceBoat = calculatePercentage(getDiscount(), totalPriceBoat);
Printer.getInstance().printFormatInfo(String.format("Totaal prijs boot met korting:"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
Printer.getInstance().emptyLine();
}
//prijs arbeids uren
Printer.getInstance().emptyLine();
double workCost = workHoursCost;
Printer.getInstance().printFormatInfo("Prijs arbeids uren:");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", workCost));
Printer.getInstance().emptyLine();
Printer.getInstance().emptyLine();
//prijs arbeids uren incl
workCost = calculatePercentage(109, workCost);
Printer.getInstance().printFormatInfo(String.format("Prijs arbeids uren incl. Btw(9%%):"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", workCost));
Printer.getInstance().emptyLine();
//Totaal prijs boot incl btw
totalPriceBoat = calculatePercentage(121, totalPriceBoat);
Printer.getInstance().printFormatInfo(String.format("Totaal prijs boot incl. Btw(21%%):"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
Printer.getInstance().emptyLine();
//Totaalprijs offerte
totalPriceBoat += workHoursCost;
Printer.getInstance().printSpaces(128);
Printer.getInstance().printCharacters(1,'+');
Printer.getInstance().emptyLine();
Printer.getInstance().printFormatInfo(String.format("Totaal prijs offerte:"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
}
} | 22082476/PROJ1-Milkshake | src/Shipflex/Quote.java | 2,681 | //Totaal prijs boot | line_comment | nl | package Shipflex;
import Boat.Boat;
import Boat.Option;
import Customer.CustomCustomer;
import Customer.BusinessCustomer;
import Customer.FoundationCustomer;
import Customer.GovermentCustomer;
import DataInOut.Info;
import DataInOut.Printer;
import java.util.ArrayList;
import java.util.List;
public class Quote {
private Company companyShipbuild;
private CustomCustomer customCustomer;
private BusinessCustomer businessCustomer;
private GovermentCustomer govermentCustomer;
private FoundationCustomer foundationCustomer;
private String date;
private String quoteDate;
private String about;
private double workHoursCost;
private Boat boat;
public Quote(Company companyShipbuild, Boat boat) {
this.companyShipbuild = companyShipbuild;
this.businessCustomer = null;
this.customCustomer = null;
this.govermentCustomer = null;
this.foundationCustomer = null;
this.boat = boat;
}
public void setCustomCustomer(CustomCustomer customCustomer) {
this.customCustomer = customCustomer;
}
public void setBusinessCustomer(BusinessCustomer businessCustomer) {
this.businessCustomer = businessCustomer;
}
public void setGovermentCustomer(GovermentCustomer govermentCustomer) {
this.govermentCustomer = govermentCustomer;
}
public void setFoundationCustomer(FoundationCustomer foundationCustomer) {
this.foundationCustomer = foundationCustomer;
}
public void setAbout(String about) {
this.about = about;
}
public void setDate(String date) {
this.date = date;
}
public void setQuoteDate(String quoteDate) {
this.quoteDate = quoteDate;
}
public void setBoat(Boat boat) {
this.boat = boat;
}
public Boat getBoat() {
return boat;
}
public CustomCustomer getCustomCustomer() {
return customCustomer;
}
public BusinessCustomer getBusinessCustomer() {
return businessCustomer;
}
public GovermentCustomer getGovermentCustomer() {
return govermentCustomer;
}
public FoundationCustomer getFoundationCustomer() {
return foundationCustomer;
}
public void setWorkHoursCost(double workHoursCost) {
this.workHoursCost = workHoursCost;
}
public void printCustomer() {
switch (checkCustomerType()) {
case "goverment":
govermentCustomer.printCustomer();
break;
case "business":
businessCustomer.printCustomer();
break;
case "foundation":
foundationCustomer.printCustomer();
break;
case "customer":
customCustomer.printCustomer();
break;
default:
Printer.getInstance().printLine("Nog geen klant toegevoegd");
break;
}
}
private String checkCustomerType() {
if (govermentCustomer != null) {
return "goverment";
} else if (businessCustomer != null) {
return "business";
} else if (customCustomer != null) {
return "customer";
} else if (foundationCustomer != null) {
return "foundation";
} else {
return "";
}
}
public void printOptions(boolean showIndex) {
for (Option option : this.boat.getOptions()) {
if (showIndex)
Info.printOptionInfo(option, Info.getOptions().indexOf(option));
else
Info.printOptionInfo(option, -1);
Printer.getInstance().emptyLine();
}
}
public void printDate() {
if (this.date != null && !this.date.equals("")) {
Printer.getInstance().printLine("Datum: " + this.date);
} else {
Printer.getInstance().printLine("Datum nog niet ingevuld");
}
if (this.quoteDate != null && !this.quoteDate.equals("")) {
Printer.getInstance().printLine("Geldigsheid datum: " + this.quoteDate);
} else {
Printer.getInstance().printLine("Geldigsheid datum nog niet ingevuld");
}
}
public void printBasicInformation() {
companyShipbuild.printCompany();
Printer.getInstance().emptyLine();
printCustomer();
Printer.getInstance().emptyLine();
printDate();
Printer.getInstance().emptyLine();
if(this.about != null && !this.about.equals("")) {
Printer.getInstance().printLine("Betreft: " + this.about);
}else {
Printer.getInstance().printLine("Betreft is nog niet ingevuld");
}
Printer.getInstance().emptyLine();
}
public void printQuote() {
Printer.getInstance().printCharacters(129, '━');
Printer.getInstance().emptyLine();
this.printBasicInformation();
Printer.getInstance().printCharacters(78, '﹏');
Printer.getInstance().emptyLine();
boat.printBoat();
Printer.getInstance().printCharacters(78, '﹏');
Printer.getInstance().emptyLine();
this.printOptions();
Printer.getInstance().emptyLine();
this.printTotal();
Printer.getInstance().emptyLine();
Printer.getInstance().printCharacters(129, '━');
}
public void printOptions() {
List<Option> essentialOptions = new ArrayList<>();
List<Option> extraOptions = new ArrayList<>();
for (Option option : boat.getOptions()) {
if (option.getEssentialForBoatType().contains(boat.getType().toLowerCase()))
essentialOptions.add(option);
else
extraOptions.add(option);
}
printOptionsListFormatted(essentialOptions);
printOptionsListFormatted(extraOptions);
}
private void printOptionsListFormatted(List<Option> options) {
for (Option option : options) {
option.printOptionInfoForBoat(boat.getType());
}
}
public int getDiscount() {
int discount = 0;
switch (checkCustomerType()) {
case "goverment":
discount = govermentCustomer.getDiscount();
break;
case "business":
discount = businessCustomer.getDiscount();
break;
case "foundation":
discount = foundationCustomer.getDiscount();
break;
case "customer":
discount = customCustomer.getDiscount();
break;
}
return 100 - discount;
}
public double calculatePercentage(int percentage, double price) {
return (price / 100) * percentage;
}
public double calculateBoatPrice() {
double price = 0;
price += boat.getBasePrice();
for (Option option : boat.getOptions()) {
price += option.getPrice();
}
return price;
}
public void printTotal() {
Printer.getInstance().emptyLine();
//Totaal prijs<SUF>
double totalPriceBoat = calculateBoatPrice();
Printer.getInstance().printFormatInfo(String.format("Totaal prijs boot:"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
Printer.getInstance().emptyLine();
//Totaal prijs boot met korting
if (getDiscount() < 100 && getDiscount() > 0) {
totalPriceBoat = calculatePercentage(getDiscount(), totalPriceBoat);
Printer.getInstance().printFormatInfo(String.format("Totaal prijs boot met korting:"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
Printer.getInstance().emptyLine();
}
//prijs arbeids uren
Printer.getInstance().emptyLine();
double workCost = workHoursCost;
Printer.getInstance().printFormatInfo("Prijs arbeids uren:");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", workCost));
Printer.getInstance().emptyLine();
Printer.getInstance().emptyLine();
//prijs arbeids uren incl
workCost = calculatePercentage(109, workCost);
Printer.getInstance().printFormatInfo(String.format("Prijs arbeids uren incl. Btw(9%%):"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", workCost));
Printer.getInstance().emptyLine();
//Totaal prijs boot incl btw
totalPriceBoat = calculatePercentage(121, totalPriceBoat);
Printer.getInstance().printFormatInfo(String.format("Totaal prijs boot incl. Btw(21%%):"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
Printer.getInstance().emptyLine();
//Totaalprijs offerte
totalPriceBoat += workHoursCost;
Printer.getInstance().printSpaces(128);
Printer.getInstance().printCharacters(1,'+');
Printer.getInstance().emptyLine();
Printer.getInstance().printFormatInfo(String.format("Totaal prijs offerte:"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
}
} | True | 1,944 | 7 | 2,150 | 7 | 2,269 | 5 | 2,150 | 7 | 2,579 | 7 | false | false | false | false | false | true |
2,383 | 200198_0 | /***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
package de.cismet.cids.custom.wrrl_db_mv.util.gup;
import org.jdesktop.swingx.JXPanel;
import org.jdesktop.swingx.painter.MattePainter;
import org.jdesktop.swingx.painter.Painter;
import java.awt.Color;
import java.util.ArrayList;
import javax.swing.JComponent;
import de.cismet.tools.gui.jbands.SimpleSection;
/**
* DOCUMENT ME!
*
* @author thorsten
* @version $Revision$, $Date$
*/
public class NaturschutzBandMember extends SimpleSection {
//~ Instance fields --------------------------------------------------------
String typ;
JXPanel component = new JXPanel();
//~ Constructors -----------------------------------------------------------
/**
* Creates a new NaturschutzBandMember object.
*
* @param queryResult DOCUMENT ME!
*/
public NaturschutzBandMember(final ArrayList queryResult) {
super((Double)queryResult.get(1), (Double)queryResult.get(2));
typ = queryResult.get(0).toString();
component.setBackgroundPainter(getBackgroundPainterforTyp(typ));
component.setToolTipText(typ);
}
//~ Methods ----------------------------------------------------------------
@Override
public JComponent getBandMemberComponent() {
return component;
}
/**
* DOCUMENT ME!
*
* @param typ DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws IllegalArgumentException DOCUMENT ME!
*/
private Painter getBackgroundPainterforTyp(final String typ) {
assert (typ != null);
if (typ.equalsIgnoreCase("NSG")) {
return new MattePainter(new Color(0x58AD00));
} else if (typ.equalsIgnoreCase("Naturpark")) {
return new MattePainter(new Color(0x9CDB48));
} else if (typ.equalsIgnoreCase("FFH")) {
return new MattePainter(new Color(0xC2F364));
} else if (typ.equalsIgnoreCase("LSG")) {
return new MattePainter(new Color(0xE0FF9C));
} else if (typ.equalsIgnoreCase("P20")) {
return new MattePainter(new Color(0xEFF3DD));
} else if (typ.equalsIgnoreCase("Eu Vogelschutzgebiet")) {
return new MattePainter(new Color(0xC1995B));
}
throw new IllegalArgumentException(
"Typ ist nicht in: NSG,Nationalpark,Naturpark,FFH,LSG,P20,Eu Vogelschutzgebiet");
}
}
| cismet/cids-custom-wrrl-db-mv | src/main/java/de/cismet/cids/custom/wrrl_db_mv/util/gup/NaturschutzBandMember.java | 794 | /***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/ | block_comment | nl | /***************************************************
*
* cismet GmbH, Saarbruecken,<SUF>*/
package de.cismet.cids.custom.wrrl_db_mv.util.gup;
import org.jdesktop.swingx.JXPanel;
import org.jdesktop.swingx.painter.MattePainter;
import org.jdesktop.swingx.painter.Painter;
import java.awt.Color;
import java.util.ArrayList;
import javax.swing.JComponent;
import de.cismet.tools.gui.jbands.SimpleSection;
/**
* DOCUMENT ME!
*
* @author thorsten
* @version $Revision$, $Date$
*/
public class NaturschutzBandMember extends SimpleSection {
//~ Instance fields --------------------------------------------------------
String typ;
JXPanel component = new JXPanel();
//~ Constructors -----------------------------------------------------------
/**
* Creates a new NaturschutzBandMember object.
*
* @param queryResult DOCUMENT ME!
*/
public NaturschutzBandMember(final ArrayList queryResult) {
super((Double)queryResult.get(1), (Double)queryResult.get(2));
typ = queryResult.get(0).toString();
component.setBackgroundPainter(getBackgroundPainterforTyp(typ));
component.setToolTipText(typ);
}
//~ Methods ----------------------------------------------------------------
@Override
public JComponent getBandMemberComponent() {
return component;
}
/**
* DOCUMENT ME!
*
* @param typ DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws IllegalArgumentException DOCUMENT ME!
*/
private Painter getBackgroundPainterforTyp(final String typ) {
assert (typ != null);
if (typ.equalsIgnoreCase("NSG")) {
return new MattePainter(new Color(0x58AD00));
} else if (typ.equalsIgnoreCase("Naturpark")) {
return new MattePainter(new Color(0x9CDB48));
} else if (typ.equalsIgnoreCase("FFH")) {
return new MattePainter(new Color(0xC2F364));
} else if (typ.equalsIgnoreCase("LSG")) {
return new MattePainter(new Color(0xE0FF9C));
} else if (typ.equalsIgnoreCase("P20")) {
return new MattePainter(new Color(0xEFF3DD));
} else if (typ.equalsIgnoreCase("Eu Vogelschutzgebiet")) {
return new MattePainter(new Color(0xC1995B));
}
throw new IllegalArgumentException(
"Typ ist nicht in: NSG,Nationalpark,Naturpark,FFH,LSG,P20,Eu Vogelschutzgebiet");
}
}
| False | 558 | 29 | 655 | 36 | 673 | 36 | 655 | 36 | 794 | 40 | false | false | false | false | false | true |
1,435 | 123508_22 | //
// http://www.windows2universe.org/our_solar_system/planets_table.html
// http://www.fourmilab.ch/cgi-bin/Solar
// http://planets.findthedata.com/
//
package me3;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
// En planet indeholde selv sit eget kreds�b
public class Planet {
double radiusTilKredsloebCenter = 0;
// planetIndex = plads/nummer fra centrum eks = Jorden = 3;
private int planetIndex = 0;
// planet level er en marings for hvilket niveau planet er p�
// level 0 = solen
// level 1 planeter = Jorden, mars Jupiter osv....
// level 2 er m�ner til level 1
// level 3 er m�ner til level 2....
int planetLevel = 0;
private double radius = 1;
// orbit real x,y
int orbitRealX, orbitRealY = 0;
// faktisk X,Y er det rigtigt x,y p� sk�rmen
long faktiskX = 0;
long faktiskY = 0;
// center X,Y er relativt
long centerX = 0;
long centerY = 0;
// enheds Cirkel x,y
double eX, eY = 0;
float vinkelFraCenterTilPlanet = 0;
// VinklerTilAndrePlaneter bruges til at analyser om planter ligger p� samme
// linje
long[] vinklerTilAndrePlanet = new long[10];
String name;
private double omkreds;
public ArrayList<Planet> moons = new ArrayList<Planet>();
public double planetensTilbagelagteAfstand = 0;
public long planetensTilbagelagteAfstandFraStart = 0;
public double planetensHastighed = 0;
public Color color;
public boolean drawRayToPlanet = true;
public boolean drawName = true;
public boolean drawOrbit = true;
public boolean drawMoons = false;
BufferedImage planetImage = null;
public double planetYears;
public double scale = 1;
public void setImage() {
String planetFileName = "img\\" + this.name + ".png";
if (this.planetLevel == 1) {
try {
planetImage = ImageIO.read(new File(planetFileName));
} catch (IOException e) {
System.out.println(this.name);
e.printStackTrace();
}
}
}
public boolean isDrawMoons() {
return drawMoons;
}
public void setDrawMoons(boolean drawMoons) {
this.drawMoons = drawMoons;
}
// GETTER AND SETTERS *************************************
public double getRadius() {
return radius;
}
public void setRadius(double planetsize) {
this.radius = planetsize;
}
public int getPlanetIndex() {
return planetIndex;
}
public void setPlanetIndex(int planetIndex) {
this.planetIndex = planetIndex;
}
public boolean isDrawOrbit() {
return drawOrbit;
}
public void setDrawOrbit(boolean drawOrbit) {
this.drawOrbit = drawOrbit;
}
public boolean isDrawName() {
return drawName;
}
public void setDrawName(boolean drawName) {
this.drawName = drawName;
}
public boolean isDrawRayToPlanet() {
return drawRayToPlanet;
}
public void setDrawRayToPlanet(boolean drawRayToPlanet) {
this.drawRayToPlanet = drawRayToPlanet;
}
public Planet() {
// Constructor
}
public void addMoon(Planet moon) {
this.moons.add(moon);
}
public double getOmkredsPaaKredsloebet() {
return this.omkreds;
}
public void setOmkredsPaaKredsloebet(int o) {
this.omkreds = o;
this.radiusTilKredsloebCenter = o / (int) Math.PI / 2;
}
public double getRadiusPaaKredsloeb() {
return radiusTilKredsloebCenter;
}
public void setRadiusPaaKredsloeb(double d) {
this.radiusTilKredsloebCenter = d;
this.omkreds = (int) Math.PI * this.radiusTilKredsloebCenter * 2;
}
public void getPlanetX(double d) {
double radianer = (d * Math.PI) / 180;
eX = Math.cos(radianer);
// faktiskX = Math.round(eX * getRadiusPaaKredsloeb() / 2);
faktiskX = (long) (eX * getRadiusPaaKredsloeb() / 2);
faktiskX += centerX;
}
public void getPlanetY(double d) {
double radianer = (d * Math.PI) / 180;
eY = Math.sin(radianer);
// faktiskY = (int) (eY * getRadiusPaaKredsloeb()) / 2;
faktiskY = (long) (eY * getRadiusPaaKredsloeb() / 2);
faktiskY += centerY;
}
static private final double calcCircleCenter(long javaCoord, double radius2) {
return (javaCoord - (radius2 / 2));
}
public int getCircleCenterX() {
return (int) (calcCircleCenter(faktiskX, radius));
}
public int getCircleCenterY() {
return (int) (calcCircleCenter(faktiskY, radius));
}
public void LogPlanetXY() {
System.out.println(this.name + "(X,Y) : " + this.faktiskX + "," + this.faktiskY + " Vinkel : "
+ this.vinkelFraCenterTilPlanet);
}
public double beregnAfstandTilbagelagtIalt(double click) {
// afstand tilbagelagt i kredsl�bet i alt
double retVal = click * this.planetensHastighed;
this.planetensTilbagelagteAfstand = retVal;
this.planetYears = planetensTilbagelagteAfstand / omkreds;
return retVal;
}
public void beregnPlanetensGradIKredsloebet(double d) {
// Denne funktin skal retunere den grad planetet er i kredsl�bet
// ud fra den vinkel en linje skulle tegnes fra centrum og ud
float retVal = 0;
double afstand = this.planetensTilbagelagteAfstandFraStart
+ this.beregnAfstandTilbagelagtIalt(d) % this.omkreds;
retVal = (float) ((afstand / this.omkreds) * 360);
this.vinkelFraCenterTilPlanet = retVal;
}
public void calcOrbit() {
// calculate Orbit real Center X,Y
orbitRealX = Util.calcRealCoord(this.centerX, radiusTilKredsloebCenter);
orbitRealY = Util.calcRealCoord(this.centerY, radiusTilKredsloebCenter);
}
public static double calcRotationAngleInDegrees(Point centerPt, Point targetPt) {
double theta = Math.atan2(targetPt.y - centerPt.y, targetPt.x - centerPt.x);
double angle = Math.toDegrees(theta);
if (angle < 0)
angle += 360;
angle *= -1;
return angle;
}
public void calcPlanet(EclipseTime ec) {
getPlanetX((vinkelFraCenterTilPlanet));
getPlanetY((vinkelFraCenterTilPlanet));
beregnPlanetensGradIKredsloebet(ec.getSSClick());
// calcOrbit();
}
// DRAW Funktion - Kan tegne alle elementer
// ---------------------------------------------------------------------------------------
public void draw(Graphics2D g, EclipseTime ec, int analyse, ArrayList<Planet> allPlanets) {
// Kontrol af hvad der skal tegnes
drawPlanet(g);
if (isDrawName())
drawPlanetName(g);
if (isDrawOrbit())
drawOrbit(g);
if (this.isDrawMoons())
drawMoons(g, ec, analyse, allPlanets);
if (isDrawRayToPlanet())
drawRayToPlanet(g);
if (planetIndex > -1) {
calcVinkelTilAndrePlaneter(allPlanets);
drawAnalyseRays(g, analyse, allPlanets);
}
}
public void drawPlanetName(Graphics2D g) {
g.drawString(this.name, (int) (faktiskX) - 20, (int) (faktiskY - (radius / 2) - 10));
}
public void drawPlanet(Graphics2D g) {
g.drawImage(planetImage, getCircleCenterX(), getCircleCenterY(), (int) radius, (int) radius, null);
}
public void drawRayToPlanet(Graphics2D g) {
g.drawLine((int) this.centerX, (int) this.centerY, (int) faktiskX, (int) faktiskY);
}
public void drawOrbit(Graphics2D g) {
g.drawArc(orbitRealX, orbitRealY, (int) radiusTilKredsloebCenter, (int) radiusTilKredsloebCenter, 0, 360);
}
public void drawMoons(Graphics2D g, EclipseTime ec, int analyse, ArrayList<Planet> allPlanets) {
for (Planet moons : moons) {
moons.centerX = this.faktiskX;
moons.centerY = this.faktiskY;
moons.calcOrbit();
moons.calcPlanet(ec);
moons.draw(g, ec, analyse, allPlanets);
}
}
public void calcVinkelTilAndrePlaneter(ArrayList<Planet> allPlanets) {
for (int i = 0; i < allPlanets.size(); i++) {
Planet planet = new Planet();
planet = allPlanets.get(i);
Point pointCenter = new Point();
Point pointTo = new Point();
pointCenter.x = (int) this.faktiskX;
pointCenter.y = (int) this.faktiskY;
pointTo.x = (int) planet.faktiskX;
pointTo.y = (int) planet.faktiskY;
vinklerTilAndrePlanet[i] = (long) calcRotationAngleInDegrees(pointCenter, pointTo);
}
}
public void drawAnalyseRays(Graphics2D g, int analyse, ArrayList<Planet> allPlanets) {
int x, y = 0;
if (analyse > 0) {
// draw analyse "moons in top of the screen
for (int i = 0; i < vinklerTilAndrePlanet.length - 1; i++) {
g.setColor(color);
x = (planetIndex * 130) + 240;
if (planetLevel == 1) {
y = 0;
g.drawString(name, x + 20, y + 20);
g.drawImage(planetImage, x + 20, y + 40, 40, 40, null);
g.setColor(allPlanets.get(i).color);
y = 10;
}
g.fillArc(x - 10, y, (int) (100), (int) (100), (int) vinklerTilAndrePlanet[i], 2);
}
}
// Draw rays between planets
if (analyse > 1) {
if (planetIndex < UniverseData.MAX_PLANETS - 1) {
g.setColor(color);
g.drawLine((int) faktiskX, (int) faktiskY, (int) allPlanets.get(planetIndex + 1).faktiskX,
(int) allPlanets.get(planetIndex + 1).faktiskY);
}
}
}
public void moonGenerator(int GenMoon) {
for (int i = 0; i < GenMoon; i++) {
Planet moon = new Planet();
moon.name = this.name + "'s moon" + i;
moon.centerX = this.centerX;
moon.centerY = this.centerY;
moon.planetIndex = this.planetIndex + i;
moon.planetLevel = this.planetLevel + 1;
moon.planetensHastighed = Util.randInt(0, (int) this.planetensHastighed * 5);
moon.planetensTilbagelagteAfstandFraStart = Util.randInt(0, (int) this.getOmkredsPaaKredsloebet());
moon.setRadiusPaaKredsloeb(
this.getRadius() + this.getRadius() / 10 + Util.randInt(1, (int) (this.getRadius() / 3)));
moon.setRadius(this.radius / Util.randInt(30, 50));
moon.color = (new Color(Util.randInt(200, 255), Util.randInt(30, 100), Util.randInt(30, 90)));
moon.setDrawRayToPlanet(true);
moon.setDrawName(false);
moon.setDrawOrbit(false);
moon.setImage();
this.addMoon(moon);
}
}
}
| RasmusOtharKirketerp/MultiEclipse_Ver4.0 | MultiEclipse_Ver4.01/src/me3/Planet.java | 3,772 | // Draw rays between planets | line_comment | nl | //
// http://www.windows2universe.org/our_solar_system/planets_table.html
// http://www.fourmilab.ch/cgi-bin/Solar
// http://planets.findthedata.com/
//
package me3;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
// En planet indeholde selv sit eget kreds�b
public class Planet {
double radiusTilKredsloebCenter = 0;
// planetIndex = plads/nummer fra centrum eks = Jorden = 3;
private int planetIndex = 0;
// planet level er en marings for hvilket niveau planet er p�
// level 0 = solen
// level 1 planeter = Jorden, mars Jupiter osv....
// level 2 er m�ner til level 1
// level 3 er m�ner til level 2....
int planetLevel = 0;
private double radius = 1;
// orbit real x,y
int orbitRealX, orbitRealY = 0;
// faktisk X,Y er det rigtigt x,y p� sk�rmen
long faktiskX = 0;
long faktiskY = 0;
// center X,Y er relativt
long centerX = 0;
long centerY = 0;
// enheds Cirkel x,y
double eX, eY = 0;
float vinkelFraCenterTilPlanet = 0;
// VinklerTilAndrePlaneter bruges til at analyser om planter ligger p� samme
// linje
long[] vinklerTilAndrePlanet = new long[10];
String name;
private double omkreds;
public ArrayList<Planet> moons = new ArrayList<Planet>();
public double planetensTilbagelagteAfstand = 0;
public long planetensTilbagelagteAfstandFraStart = 0;
public double planetensHastighed = 0;
public Color color;
public boolean drawRayToPlanet = true;
public boolean drawName = true;
public boolean drawOrbit = true;
public boolean drawMoons = false;
BufferedImage planetImage = null;
public double planetYears;
public double scale = 1;
public void setImage() {
String planetFileName = "img\\" + this.name + ".png";
if (this.planetLevel == 1) {
try {
planetImage = ImageIO.read(new File(planetFileName));
} catch (IOException e) {
System.out.println(this.name);
e.printStackTrace();
}
}
}
public boolean isDrawMoons() {
return drawMoons;
}
public void setDrawMoons(boolean drawMoons) {
this.drawMoons = drawMoons;
}
// GETTER AND SETTERS *************************************
public double getRadius() {
return radius;
}
public void setRadius(double planetsize) {
this.radius = planetsize;
}
public int getPlanetIndex() {
return planetIndex;
}
public void setPlanetIndex(int planetIndex) {
this.planetIndex = planetIndex;
}
public boolean isDrawOrbit() {
return drawOrbit;
}
public void setDrawOrbit(boolean drawOrbit) {
this.drawOrbit = drawOrbit;
}
public boolean isDrawName() {
return drawName;
}
public void setDrawName(boolean drawName) {
this.drawName = drawName;
}
public boolean isDrawRayToPlanet() {
return drawRayToPlanet;
}
public void setDrawRayToPlanet(boolean drawRayToPlanet) {
this.drawRayToPlanet = drawRayToPlanet;
}
public Planet() {
// Constructor
}
public void addMoon(Planet moon) {
this.moons.add(moon);
}
public double getOmkredsPaaKredsloebet() {
return this.omkreds;
}
public void setOmkredsPaaKredsloebet(int o) {
this.omkreds = o;
this.radiusTilKredsloebCenter = o / (int) Math.PI / 2;
}
public double getRadiusPaaKredsloeb() {
return radiusTilKredsloebCenter;
}
public void setRadiusPaaKredsloeb(double d) {
this.radiusTilKredsloebCenter = d;
this.omkreds = (int) Math.PI * this.radiusTilKredsloebCenter * 2;
}
public void getPlanetX(double d) {
double radianer = (d * Math.PI) / 180;
eX = Math.cos(radianer);
// faktiskX = Math.round(eX * getRadiusPaaKredsloeb() / 2);
faktiskX = (long) (eX * getRadiusPaaKredsloeb() / 2);
faktiskX += centerX;
}
public void getPlanetY(double d) {
double radianer = (d * Math.PI) / 180;
eY = Math.sin(radianer);
// faktiskY = (int) (eY * getRadiusPaaKredsloeb()) / 2;
faktiskY = (long) (eY * getRadiusPaaKredsloeb() / 2);
faktiskY += centerY;
}
static private final double calcCircleCenter(long javaCoord, double radius2) {
return (javaCoord - (radius2 / 2));
}
public int getCircleCenterX() {
return (int) (calcCircleCenter(faktiskX, radius));
}
public int getCircleCenterY() {
return (int) (calcCircleCenter(faktiskY, radius));
}
public void LogPlanetXY() {
System.out.println(this.name + "(X,Y) : " + this.faktiskX + "," + this.faktiskY + " Vinkel : "
+ this.vinkelFraCenterTilPlanet);
}
public double beregnAfstandTilbagelagtIalt(double click) {
// afstand tilbagelagt i kredsl�bet i alt
double retVal = click * this.planetensHastighed;
this.planetensTilbagelagteAfstand = retVal;
this.planetYears = planetensTilbagelagteAfstand / omkreds;
return retVal;
}
public void beregnPlanetensGradIKredsloebet(double d) {
// Denne funktin skal retunere den grad planetet er i kredsl�bet
// ud fra den vinkel en linje skulle tegnes fra centrum og ud
float retVal = 0;
double afstand = this.planetensTilbagelagteAfstandFraStart
+ this.beregnAfstandTilbagelagtIalt(d) % this.omkreds;
retVal = (float) ((afstand / this.omkreds) * 360);
this.vinkelFraCenterTilPlanet = retVal;
}
public void calcOrbit() {
// calculate Orbit real Center X,Y
orbitRealX = Util.calcRealCoord(this.centerX, radiusTilKredsloebCenter);
orbitRealY = Util.calcRealCoord(this.centerY, radiusTilKredsloebCenter);
}
public static double calcRotationAngleInDegrees(Point centerPt, Point targetPt) {
double theta = Math.atan2(targetPt.y - centerPt.y, targetPt.x - centerPt.x);
double angle = Math.toDegrees(theta);
if (angle < 0)
angle += 360;
angle *= -1;
return angle;
}
public void calcPlanet(EclipseTime ec) {
getPlanetX((vinkelFraCenterTilPlanet));
getPlanetY((vinkelFraCenterTilPlanet));
beregnPlanetensGradIKredsloebet(ec.getSSClick());
// calcOrbit();
}
// DRAW Funktion - Kan tegne alle elementer
// ---------------------------------------------------------------------------------------
public void draw(Graphics2D g, EclipseTime ec, int analyse, ArrayList<Planet> allPlanets) {
// Kontrol af hvad der skal tegnes
drawPlanet(g);
if (isDrawName())
drawPlanetName(g);
if (isDrawOrbit())
drawOrbit(g);
if (this.isDrawMoons())
drawMoons(g, ec, analyse, allPlanets);
if (isDrawRayToPlanet())
drawRayToPlanet(g);
if (planetIndex > -1) {
calcVinkelTilAndrePlaneter(allPlanets);
drawAnalyseRays(g, analyse, allPlanets);
}
}
public void drawPlanetName(Graphics2D g) {
g.drawString(this.name, (int) (faktiskX) - 20, (int) (faktiskY - (radius / 2) - 10));
}
public void drawPlanet(Graphics2D g) {
g.drawImage(planetImage, getCircleCenterX(), getCircleCenterY(), (int) radius, (int) radius, null);
}
public void drawRayToPlanet(Graphics2D g) {
g.drawLine((int) this.centerX, (int) this.centerY, (int) faktiskX, (int) faktiskY);
}
public void drawOrbit(Graphics2D g) {
g.drawArc(orbitRealX, orbitRealY, (int) radiusTilKredsloebCenter, (int) radiusTilKredsloebCenter, 0, 360);
}
public void drawMoons(Graphics2D g, EclipseTime ec, int analyse, ArrayList<Planet> allPlanets) {
for (Planet moons : moons) {
moons.centerX = this.faktiskX;
moons.centerY = this.faktiskY;
moons.calcOrbit();
moons.calcPlanet(ec);
moons.draw(g, ec, analyse, allPlanets);
}
}
public void calcVinkelTilAndrePlaneter(ArrayList<Planet> allPlanets) {
for (int i = 0; i < allPlanets.size(); i++) {
Planet planet = new Planet();
planet = allPlanets.get(i);
Point pointCenter = new Point();
Point pointTo = new Point();
pointCenter.x = (int) this.faktiskX;
pointCenter.y = (int) this.faktiskY;
pointTo.x = (int) planet.faktiskX;
pointTo.y = (int) planet.faktiskY;
vinklerTilAndrePlanet[i] = (long) calcRotationAngleInDegrees(pointCenter, pointTo);
}
}
public void drawAnalyseRays(Graphics2D g, int analyse, ArrayList<Planet> allPlanets) {
int x, y = 0;
if (analyse > 0) {
// draw analyse "moons in top of the screen
for (int i = 0; i < vinklerTilAndrePlanet.length - 1; i++) {
g.setColor(color);
x = (planetIndex * 130) + 240;
if (planetLevel == 1) {
y = 0;
g.drawString(name, x + 20, y + 20);
g.drawImage(planetImage, x + 20, y + 40, 40, 40, null);
g.setColor(allPlanets.get(i).color);
y = 10;
}
g.fillArc(x - 10, y, (int) (100), (int) (100), (int) vinklerTilAndrePlanet[i], 2);
}
}
// Draw rays<SUF>
if (analyse > 1) {
if (planetIndex < UniverseData.MAX_PLANETS - 1) {
g.setColor(color);
g.drawLine((int) faktiskX, (int) faktiskY, (int) allPlanets.get(planetIndex + 1).faktiskX,
(int) allPlanets.get(planetIndex + 1).faktiskY);
}
}
}
public void moonGenerator(int GenMoon) {
for (int i = 0; i < GenMoon; i++) {
Planet moon = new Planet();
moon.name = this.name + "'s moon" + i;
moon.centerX = this.centerX;
moon.centerY = this.centerY;
moon.planetIndex = this.planetIndex + i;
moon.planetLevel = this.planetLevel + 1;
moon.planetensHastighed = Util.randInt(0, (int) this.planetensHastighed * 5);
moon.planetensTilbagelagteAfstandFraStart = Util.randInt(0, (int) this.getOmkredsPaaKredsloebet());
moon.setRadiusPaaKredsloeb(
this.getRadius() + this.getRadius() / 10 + Util.randInt(1, (int) (this.getRadius() / 3)));
moon.setRadius(this.radius / Util.randInt(30, 50));
moon.color = (new Color(Util.randInt(200, 255), Util.randInt(30, 100), Util.randInt(30, 90)));
moon.setDrawRayToPlanet(true);
moon.setDrawName(false);
moon.setDrawOrbit(false);
moon.setImage();
this.addMoon(moon);
}
}
}
| False | 3,056 | 5 | 3,607 | 7 | 3,401 | 5 | 3,607 | 7 | 4,120 | 7 | false | false | false | false | false | true |
4,579 | 169859_1 | /**
*
* Copyright 2012-2017 TNO Geologische Dienst Nederland
*
* Licensed under the EUPL, Version 1.2 or - as soon they will be approved by
* the European Commission - subsequent versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the Licence.
* You may obtain a copy of the Licence at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*
* This work was sponsored by the Dutch Rijksoverheid, Basisregistratie
* Ondergrond (BRO) Programme (https://bro.pleio.nl/)
*/
package nl.bro.cpt.gef.main;
import static org.fest.assertions.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.LogRecord;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import nl.bro.cpt.gef.main.util.TestHandler;
public class ConverGefTest {
@Before
public void init() {
TestHandler.LOG_RECORDS.clear();
}
@After
public void cleanup() {
TestHandler.LOG_RECORDS.clear();
}
private List<String> getMessages() {
List<String> messages = new ArrayList<>();
for ( LogRecord record : TestHandler.LOG_RECORDS ) {
messages.add( record.getMessage() );
}
return messages;
}
@Test
public void testNoArguments() {
// -- action
ConvertGef.main( new String[0] );
// -- verify
List<String> messages = getMessages();
assertThat( messages ).contains( "Missing t option", "Missing r option", "Missing q option" );
}
@Test
public void testNonExistingFile() {
ConvertGef.main( new String[] { "-r", "test", "-t", "R", "-q", "IMBRO", "TEST.GEF" } );
List<String> messages = getMessages();
assertThat( messages.toString() ).contains( "kan niet gevonden worden" );
}
/**
* Ignore tot dat filenaam probleem is opgelost
*/
@Test
@Ignore
public void testNormal() {
ConvertGef.main(
new String[] { "-r", "test", "-t", "R", "-q", "IMBRO", "-d", "target", "src/test/resources/CPT-F3b-i3-23913-completion-CPT.GEF",
"src/test/resources/CPT-F3b-i3-23913-completion-DISS.GEF" } );
}
}
| tvcstseng/CPT_GEF_CONVERTER | gef_standalone/src/test/java/nl/bro/cpt/gef/main/ConverGefTest.java | 795 | /**
* Ignore tot dat filenaam probleem is opgelost
*/ | block_comment | nl | /**
*
* Copyright 2012-2017 TNO Geologische Dienst Nederland
*
* Licensed under the EUPL, Version 1.2 or - as soon they will be approved by
* the European Commission - subsequent versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the Licence.
* You may obtain a copy of the Licence at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*
* This work was sponsored by the Dutch Rijksoverheid, Basisregistratie
* Ondergrond (BRO) Programme (https://bro.pleio.nl/)
*/
package nl.bro.cpt.gef.main;
import static org.fest.assertions.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.LogRecord;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import nl.bro.cpt.gef.main.util.TestHandler;
public class ConverGefTest {
@Before
public void init() {
TestHandler.LOG_RECORDS.clear();
}
@After
public void cleanup() {
TestHandler.LOG_RECORDS.clear();
}
private List<String> getMessages() {
List<String> messages = new ArrayList<>();
for ( LogRecord record : TestHandler.LOG_RECORDS ) {
messages.add( record.getMessage() );
}
return messages;
}
@Test
public void testNoArguments() {
// -- action
ConvertGef.main( new String[0] );
// -- verify
List<String> messages = getMessages();
assertThat( messages ).contains( "Missing t option", "Missing r option", "Missing q option" );
}
@Test
public void testNonExistingFile() {
ConvertGef.main( new String[] { "-r", "test", "-t", "R", "-q", "IMBRO", "TEST.GEF" } );
List<String> messages = getMessages();
assertThat( messages.toString() ).contains( "kan niet gevonden worden" );
}
/**
* Ignore tot dat<SUF>*/
@Test
@Ignore
public void testNormal() {
ConvertGef.main(
new String[] { "-r", "test", "-t", "R", "-q", "IMBRO", "-d", "target", "src/test/resources/CPT-F3b-i3-23913-completion-CPT.GEF",
"src/test/resources/CPT-F3b-i3-23913-completion-DISS.GEF" } );
}
}
| True | 642 | 18 | 739 | 17 | 734 | 17 | 739 | 17 | 823 | 20 | false | false | false | false | false | true |
4,417 | 151743_47 | package BomberButtiClient;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Iterator;
/**
*The class Bomber Player includes all data from the player
* Which player has its own object of this class
*/
public class BomberPlayer {
BomberMap map;
BomberGame game;
int id; //Each player has a unique ID
int x;
int y;
boolean isDead; //True if player is dead
int speed; //Indication of speed at which the character can move on the playing field
int totalBombs; //Total number of trees that the player can simultaneously
int bombStrike; //Scope of the bows of the bombs that explains this player
int usedBombs; //Number of bombs that the player has used
int direction; //Direction in which the player moves on the field (to be performed at this.act ()
boolean dropBomb; //True if player wants to lay a bomb (performed at this.act ())
ArrayList<Bomb> bombs = new ArrayList<>(); //tracking the bombs laid by this player
String name; //The username of this player
int[] keys;
private static final int DIR_UP = 1;
private static final int DIR_DOWN = 2;
private static final int DIR_LEFT = 3;
private static final int DIR_RIGHT = 4;
private static final int UP = 0;
private static final int DOWN = 1;
private static final int LEFT = 2;
private static final int RIGHT = 3;
private static final int BOMB = 4;
/**
* Default constructor
*/
public BomberPlayer() {
keys = new int[5];
id = 0;
x = 0;
y = 0;
isDead = false;
speed = 1;
totalBombs = 1;
bombStrike = 0;
usedBombs = 0;
direction = 0;
dropBomb = false;
name = "Unknown player";
}
/**
* Constructor
* @param game
* @param map
* @param id
* @param x
* @param y
*/
public BomberPlayer(BomberGame game, BomberMap map, int id, int x, int y, String name) {
this();
this.game = game;
this.map = map;
this.id = id;
this.x = x;
this.y = y;
this.name = name;
}
/**
* Control Keys pick for this player from the keyconfig class
*/
public void loadKeys() {
KeyConfig kC = new KeyConfig();
keys[UP] = kC.keys[id-1][UP];
keys[DOWN] = kC.keys[id-1][DOWN];
keys[LEFT] = kC.keys[id-1][LEFT];
keys[RIGHT] = kC.keys[id-1][RIGHT];
keys[BOMB] = kC.keys[id-1][BOMB];
}
/**
* @return
*/
public BomberMap getMap() {
return this.map;
}
/**
* @return
*/
public BomberGame getGame() {
return this.game;
}
/**
* @return
*/
public int getId() {
return this.id;
}
/**
* @return
*/
public int getX() {
return this.x;
}
/**
* @return
*/
public int getY() {
return this.y;
}
/**
* @return
*/
public Coord getCoords() {
return new Coord(this.x,this.y);
}
/**
* @return
*/
public boolean getIsDead() {
return this.isDead;
}
/**
* @return
*/
public int getSpeed() {
return this.speed;
}
/**
* @return
*/
public int getTotalBombs() {
return this.totalBombs;
}
/**
* @return
*/
public int getBombStrike() {
return this.bombStrike;
}
/**
* @return
*/
public int getUsedBombs() {
return this.usedBombs;
}
/**
* Get function for the ArrayList of the bombs laid by this player
* @return
*/
public ArrayList<Bomb> getBombs() {
return this.bombs;
}
/**
* @return
*/
public String getName() {
return this.name;
}
/**
* Set functions; So that external classes can set the variables of these classes
*/
public void setMap(BomberMap map) {
this.map = map;
}
public void setGame(BomberGame game) {
this.game = game;
}
public void setId(int id) {
this.id = id;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setIsDead(boolean isDead) {
this.isDead = isDead;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public void setTotalBombs(int totalBombs) {
this.totalBombs = totalBombs;
}
public void setBombStrike(int bombStrike) {
this.bombStrike = bombStrike;
}
public void setUsedBombs(int usedBombs) {
this.usedBombs = usedBombs;
}
public void setDirection(int direction) {
this.direction = direction;
}
public void setDropBomb(boolean dropBomb) {
this.dropBomb = dropBomb;
}
public void setBombs(ArrayList<Bomb> bombs) {
this.bombs = bombs;
}
/**
* Semi-set functions
*/
public void incSpeed(int a) {
speed = speed+a;
}
public void decSpeed(int a) {
speed = speed-a;
}
public void incTotalBombs(int a) {
totalBombs = totalBombs+a;
}
public void decTotalBombs(int a) {
totalBombs = totalBombs-a;
}
public void incBombStrike(int a) {
bombStrike = bombStrike+a;
}
public void decBombStrike(int a) {
bombStrike = bombStrike-a;
}
/**
* Is performed by pressing a button
* @param evt: Contains information key pressed
*/
public void keyPressed(KeyEvent evt) {
if (evt.getKeyCode() == keys[UP]) {
this.direction = DIR_UP;
}
else if (evt.getKeyCode() == keys[DOWN]) {
this.direction = DIR_DOWN;
}
else if (evt.getKeyCode() == keys[LEFT]) {
this.direction = DIR_LEFT;
}
else if (evt.getKeyCode() == keys[RIGHT]) {
this.direction = DIR_RIGHT;
}
else if (evt.getKeyCode() == keys[BOMB]) {
dropBomb = true;
}
}
/**
* Is performed at the release of a key
* @param evt: Contains information about the release button
*/
public void keyReleased(KeyEvent evt) {
if ((evt.getKeyCode() == keys[UP]) && (direction == DIR_UP)) {
direction = 0;
}
if ((evt.getKeyCode() == keys[DOWN]) && (direction == DIR_DOWN)) {
direction = 0;
}
if ((evt.getKeyCode() == keys[LEFT]) && (direction == DIR_LEFT)) {
direction = 0;
}
if ((evt.getKeyCode() == keys[RIGHT]) && (direction == DIR_RIGHT)) {
direction = 0;
}
}
/**
* Players will be 'killed'
*/
public void kill() {
this.isDead = true;
}
/**
* Is performed at each "pulse timer", from here everything is performed every
*/
public void act() {
//Loop all the bombs laid by the player to remove the unexploded bombs from the list
for (Iterator i = bombs.listIterator(); i.hasNext();) {
Bomb b = (Bomb) i.next(); //Current 'bomb' in the course
if (b.isExploded()) {
i.remove();
}
}
Coord c = new Coord(x,y);
if (map.isStrike(c)) {
this.kill();
game.endGame();
}
else {
map.checkBonus(this);
if (dropBomb) {
if (bombs.size() < totalBombs) {
Bomb b = new Bomb(this,x,y);
bombs.add(b);
map.createBomb(b);
usedBombs++;
}
}
dropBomb = false;
//Control or player wants to move
switch(direction) {
case DIR_UP: //Players will move upwards
c.decY(); //Current coordinate one box up
if (!map.isObstacle(c)) {
this.y--;
} //n-> Move Up
break;
case DIR_DOWN: //Player wants to move downwardly
c.incY(); //Current coordinate 1 box down
if (!map.isObstacle(c)) {
this.y++;
} //n-> Move Down
break;
case DIR_LEFT: //Players will move to the left
c.decX(); //Current coordinate one box to the left
if (!map.isObstacle(c)) {
this.x--;
} //n-> move left
break;
case DIR_RIGHT: //Players will move to the right
c.incX(); //Current coordinate one box to the right
if (!map.isObstacle(c)) {
this.x++;
} //n->naar rechts verlaatsen
break;
default: //Player does not want to move -> nothing
}
}
}
}
| surdarmaputra/bomberman | BomberPlayer.java | 2,953 | //n->naar rechts verlaatsen | line_comment | nl | package BomberButtiClient;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Iterator;
/**
*The class Bomber Player includes all data from the player
* Which player has its own object of this class
*/
public class BomberPlayer {
BomberMap map;
BomberGame game;
int id; //Each player has a unique ID
int x;
int y;
boolean isDead; //True if player is dead
int speed; //Indication of speed at which the character can move on the playing field
int totalBombs; //Total number of trees that the player can simultaneously
int bombStrike; //Scope of the bows of the bombs that explains this player
int usedBombs; //Number of bombs that the player has used
int direction; //Direction in which the player moves on the field (to be performed at this.act ()
boolean dropBomb; //True if player wants to lay a bomb (performed at this.act ())
ArrayList<Bomb> bombs = new ArrayList<>(); //tracking the bombs laid by this player
String name; //The username of this player
int[] keys;
private static final int DIR_UP = 1;
private static final int DIR_DOWN = 2;
private static final int DIR_LEFT = 3;
private static final int DIR_RIGHT = 4;
private static final int UP = 0;
private static final int DOWN = 1;
private static final int LEFT = 2;
private static final int RIGHT = 3;
private static final int BOMB = 4;
/**
* Default constructor
*/
public BomberPlayer() {
keys = new int[5];
id = 0;
x = 0;
y = 0;
isDead = false;
speed = 1;
totalBombs = 1;
bombStrike = 0;
usedBombs = 0;
direction = 0;
dropBomb = false;
name = "Unknown player";
}
/**
* Constructor
* @param game
* @param map
* @param id
* @param x
* @param y
*/
public BomberPlayer(BomberGame game, BomberMap map, int id, int x, int y, String name) {
this();
this.game = game;
this.map = map;
this.id = id;
this.x = x;
this.y = y;
this.name = name;
}
/**
* Control Keys pick for this player from the keyconfig class
*/
public void loadKeys() {
KeyConfig kC = new KeyConfig();
keys[UP] = kC.keys[id-1][UP];
keys[DOWN] = kC.keys[id-1][DOWN];
keys[LEFT] = kC.keys[id-1][LEFT];
keys[RIGHT] = kC.keys[id-1][RIGHT];
keys[BOMB] = kC.keys[id-1][BOMB];
}
/**
* @return
*/
public BomberMap getMap() {
return this.map;
}
/**
* @return
*/
public BomberGame getGame() {
return this.game;
}
/**
* @return
*/
public int getId() {
return this.id;
}
/**
* @return
*/
public int getX() {
return this.x;
}
/**
* @return
*/
public int getY() {
return this.y;
}
/**
* @return
*/
public Coord getCoords() {
return new Coord(this.x,this.y);
}
/**
* @return
*/
public boolean getIsDead() {
return this.isDead;
}
/**
* @return
*/
public int getSpeed() {
return this.speed;
}
/**
* @return
*/
public int getTotalBombs() {
return this.totalBombs;
}
/**
* @return
*/
public int getBombStrike() {
return this.bombStrike;
}
/**
* @return
*/
public int getUsedBombs() {
return this.usedBombs;
}
/**
* Get function for the ArrayList of the bombs laid by this player
* @return
*/
public ArrayList<Bomb> getBombs() {
return this.bombs;
}
/**
* @return
*/
public String getName() {
return this.name;
}
/**
* Set functions; So that external classes can set the variables of these classes
*/
public void setMap(BomberMap map) {
this.map = map;
}
public void setGame(BomberGame game) {
this.game = game;
}
public void setId(int id) {
this.id = id;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setIsDead(boolean isDead) {
this.isDead = isDead;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public void setTotalBombs(int totalBombs) {
this.totalBombs = totalBombs;
}
public void setBombStrike(int bombStrike) {
this.bombStrike = bombStrike;
}
public void setUsedBombs(int usedBombs) {
this.usedBombs = usedBombs;
}
public void setDirection(int direction) {
this.direction = direction;
}
public void setDropBomb(boolean dropBomb) {
this.dropBomb = dropBomb;
}
public void setBombs(ArrayList<Bomb> bombs) {
this.bombs = bombs;
}
/**
* Semi-set functions
*/
public void incSpeed(int a) {
speed = speed+a;
}
public void decSpeed(int a) {
speed = speed-a;
}
public void incTotalBombs(int a) {
totalBombs = totalBombs+a;
}
public void decTotalBombs(int a) {
totalBombs = totalBombs-a;
}
public void incBombStrike(int a) {
bombStrike = bombStrike+a;
}
public void decBombStrike(int a) {
bombStrike = bombStrike-a;
}
/**
* Is performed by pressing a button
* @param evt: Contains information key pressed
*/
public void keyPressed(KeyEvent evt) {
if (evt.getKeyCode() == keys[UP]) {
this.direction = DIR_UP;
}
else if (evt.getKeyCode() == keys[DOWN]) {
this.direction = DIR_DOWN;
}
else if (evt.getKeyCode() == keys[LEFT]) {
this.direction = DIR_LEFT;
}
else if (evt.getKeyCode() == keys[RIGHT]) {
this.direction = DIR_RIGHT;
}
else if (evt.getKeyCode() == keys[BOMB]) {
dropBomb = true;
}
}
/**
* Is performed at the release of a key
* @param evt: Contains information about the release button
*/
public void keyReleased(KeyEvent evt) {
if ((evt.getKeyCode() == keys[UP]) && (direction == DIR_UP)) {
direction = 0;
}
if ((evt.getKeyCode() == keys[DOWN]) && (direction == DIR_DOWN)) {
direction = 0;
}
if ((evt.getKeyCode() == keys[LEFT]) && (direction == DIR_LEFT)) {
direction = 0;
}
if ((evt.getKeyCode() == keys[RIGHT]) && (direction == DIR_RIGHT)) {
direction = 0;
}
}
/**
* Players will be 'killed'
*/
public void kill() {
this.isDead = true;
}
/**
* Is performed at each "pulse timer", from here everything is performed every
*/
public void act() {
//Loop all the bombs laid by the player to remove the unexploded bombs from the list
for (Iterator i = bombs.listIterator(); i.hasNext();) {
Bomb b = (Bomb) i.next(); //Current 'bomb' in the course
if (b.isExploded()) {
i.remove();
}
}
Coord c = new Coord(x,y);
if (map.isStrike(c)) {
this.kill();
game.endGame();
}
else {
map.checkBonus(this);
if (dropBomb) {
if (bombs.size() < totalBombs) {
Bomb b = new Bomb(this,x,y);
bombs.add(b);
map.createBomb(b);
usedBombs++;
}
}
dropBomb = false;
//Control or player wants to move
switch(direction) {
case DIR_UP: //Players will move upwards
c.decY(); //Current coordinate one box up
if (!map.isObstacle(c)) {
this.y--;
} //n-> Move Up
break;
case DIR_DOWN: //Player wants to move downwardly
c.incY(); //Current coordinate 1 box down
if (!map.isObstacle(c)) {
this.y++;
} //n-> Move Down
break;
case DIR_LEFT: //Players will move to the left
c.decX(); //Current coordinate one box to the left
if (!map.isObstacle(c)) {
this.x--;
} //n-> move left
break;
case DIR_RIGHT: //Players will move to the right
c.incX(); //Current coordinate one box to the right
if (!map.isObstacle(c)) {
this.x++;
} //n->naar rechts<SUF>
break;
default: //Player does not want to move -> nothing
}
}
}
}
| True | 2,219 | 11 | 2,409 | 12 | 2,653 | 7 | 2,409 | 12 | 2,914 | 11 | false | false | false | false | false | true |
4,371 | 41780_0 | import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Day8 {
static final class LR {
private final String left;
private final String right;
public LR(String left, String right) {
this.left = left;
this.right = right;
}
public String get(Character lOrR){
if(lOrR.equals('L'))
return left;
if(lOrR.equals('R'))
return right;
throw new RuntimeException();
}
}
public static void main(String[] args) {
calculate1("src/day8/example1.txt");
calculate1("src/day8/input.txt");
calculate2("src/day8/example2.txt");
calculate2("src/day8/input.txt");
}
private static void calculate1(String filename) {
Util.applyToFile(filename, lines -> {
var split = lines.split("\n\n");
var instructions = split[0].strip().chars().mapToObj(c -> (char)c).toList();
var size = instructions.size();
var nodes = getNodeMap(split[1]);
var i = 0;
String node = "AAA";
while(true){
var c = instructions.get(i % size);
node = nodes.get(node).get(c);
if(node.equals("ZZZ")){
System.out.println(i+1);
return;
}
i++;
}
});
}
private static void calculate2(String filename) {
Util.applyToFile(filename, lines -> {
var split = lines.split("\n\n");
var instructions = split[0].strip().chars().mapToObj(c -> (char)c).toList();
var size = instructions.size();
var nodes = getNodeMap(split[1]);
var node = nodes.keySet().stream().filter(s -> s.endsWith("A")).collect(Collectors.toList());
List<Integer> tails = new ArrayList<>();
List<Integer> cycleLengths = new ArrayList<>();
List<Integer> zPos = new ArrayList<>();
for(var n : node){
var i = 0;
var cycle = new ArrayList<String>();
var next = n;
inner: while(true){
var c = instructions.get(i % size);
next = nodes.get(next).get(c);
if(cycle.contains(next) && cycle.indexOf(next) - i % size == 0){
tails.add(cycle.indexOf(next));
cycleLengths.add(i - cycle.indexOf(next));
break inner;
}
cycle.add(next);
if(next.endsWith("Z"))
zPos.add(cycle.indexOf(next));
i++;
}
}
System.out.println(cycleLengths); //Gebruik wolfram alpha om lcm te berekenen, Java is moeilijk.
});
}
private static Map<String,LR> getNodeMap(String string) {
return Util.split(string,"\n").map(s -> s.split("="))
.collect(Collectors.toMap(s -> s[0].strip(), s -> {
var s2 = s[1].strip();
return new LR(s2.substring(1,4), s2.substring(6,9));
}));
}
}
| spr3nk3ls/aoc_2023 | src/Day8.java | 923 | //Gebruik wolfram alpha om lcm te berekenen, Java is moeilijk. | line_comment | nl | import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Day8 {
static final class LR {
private final String left;
private final String right;
public LR(String left, String right) {
this.left = left;
this.right = right;
}
public String get(Character lOrR){
if(lOrR.equals('L'))
return left;
if(lOrR.equals('R'))
return right;
throw new RuntimeException();
}
}
public static void main(String[] args) {
calculate1("src/day8/example1.txt");
calculate1("src/day8/input.txt");
calculate2("src/day8/example2.txt");
calculate2("src/day8/input.txt");
}
private static void calculate1(String filename) {
Util.applyToFile(filename, lines -> {
var split = lines.split("\n\n");
var instructions = split[0].strip().chars().mapToObj(c -> (char)c).toList();
var size = instructions.size();
var nodes = getNodeMap(split[1]);
var i = 0;
String node = "AAA";
while(true){
var c = instructions.get(i % size);
node = nodes.get(node).get(c);
if(node.equals("ZZZ")){
System.out.println(i+1);
return;
}
i++;
}
});
}
private static void calculate2(String filename) {
Util.applyToFile(filename, lines -> {
var split = lines.split("\n\n");
var instructions = split[0].strip().chars().mapToObj(c -> (char)c).toList();
var size = instructions.size();
var nodes = getNodeMap(split[1]);
var node = nodes.keySet().stream().filter(s -> s.endsWith("A")).collect(Collectors.toList());
List<Integer> tails = new ArrayList<>();
List<Integer> cycleLengths = new ArrayList<>();
List<Integer> zPos = new ArrayList<>();
for(var n : node){
var i = 0;
var cycle = new ArrayList<String>();
var next = n;
inner: while(true){
var c = instructions.get(i % size);
next = nodes.get(next).get(c);
if(cycle.contains(next) && cycle.indexOf(next) - i % size == 0){
tails.add(cycle.indexOf(next));
cycleLengths.add(i - cycle.indexOf(next));
break inner;
}
cycle.add(next);
if(next.endsWith("Z"))
zPos.add(cycle.indexOf(next));
i++;
}
}
System.out.println(cycleLengths); //Gebruik wolfram<SUF>
});
}
private static Map<String,LR> getNodeMap(String string) {
return Util.split(string,"\n").map(s -> s.split("="))
.collect(Collectors.toMap(s -> s[0].strip(), s -> {
var s2 = s[1].strip();
return new LR(s2.substring(1,4), s2.substring(6,9));
}));
}
}
| True | 665 | 20 | 780 | 22 | 845 | 15 | 780 | 22 | 908 | 21 | false | false | false | false | false | true |
1,008 | 101677_3 | package de.hs.mannheim.tpe.smits.group3.impl;
/**
* Klasse Vektor. Für einen 3 dimensionalen Vektor R3
* @author alexanderschaaf
*/
public class Vector{
/**
* Koordinaten des 3D Vektors
*/
private double x;
private double y;
private double z;
/**
* Erzeugt einen Null-Vector, d.h. den Vektor bei dem alle Komponenten den Wert 0 haben.
* */
public Vector (){
this.x = 0.0d;
this.y = 0.0d;
this.z = 0.0d;
}
/**
* Erzeugt einen neuen Vektor mit den angebgebenen Elementen
* @param x Koordinate1
* @param y Koordinate2
* @param z Koordinate3
*/
public Vector( double x, double y, double z){
this.x = x;
this.y = y;
this.z = z;
}
/**
*Addiert den gegebenen Vektor zu diesem.
*@param vektor Der Vektor der hinzu addiert wird
*/
public Vector addiere(Vector vektor) throws java.lang.IllegalArgumentException{
if ( vektor instanceof Vector){
/*neu berechnete Vektor Koordinaten*/
double koordinateX = this.getX() + vektor.getX();
double koordinateY = this.getY() + vektor.getY();
double koordinateZ = this.getZ() + vektor.getZ();
return new Vector(koordinateX,koordinateY,koordinateZ);
}
else {throw new java.lang.IllegalArgumentException();}
}
/**
* Bestimmt den Betrag (die Länge) dieses Vektors.
* @return Die Länge des Vektors
*/
public double betrag (){
double exp = 2.0;
double radikant1 = Math.pow(this.getX(),exp);
double radikant2 = Math.pow(this.getY(),exp);
double radikant3 = Math.pow(this.getZ(),exp);
return Math.sqrt(radikant1 + radikant2 + radikant3);
}
/**
* Liefert einen Vektor zurück, der diesem Vektor bezüglich der Richtung entspricht,
* aber auf die Länge 1 normiert ist.
*/
public Vector einheitsvektor() throws java.lang.IllegalStateException{
Vector einheitsVektor;
if (this.betrag() == 0.00){
throw new java.lang.IllegalStateException("Vektor hat die länge 0.00");
}else{
einheitsVektor = multipliziere(1 / this.betrag());
}
return einheitsVektor;
}
/**
* Liefert die 1. Komponente des Vektors
* */
public double getX(){
return x;
}
/**
* Liefert die 2. Komponente des Vektors
* */
public double getY(){
return y;
}
/**
* Liefert die 3. Komponente des Vektors
*/
public double getZ(){
return z;
}
/**
* Bestimmt das Kreuzprodukt dises mit dem gegebenen Vektor.
* @param v Vektor
* @return kreuzprodukt Das Kreuzprodukt der zwei Vektoren
*
*/
public Vector kreuzprodukt(Vector v){
double neueKoordinateX;
double neueKoordinateY;
double neueKoordinateZ;
double winkel = winkel(v);
if (winkel <= 180.00){
neueKoordinateX= (this.getY()* v.getZ())-(this.getZ()*v.getY());
neueKoordinateY= (this.getZ()* v.getX())-(this.getX()*v.getZ());
neueKoordinateZ= (this.getX()* v.getY())-(this.getY()*v.getX());
return new Vector(neueKoordinateX,neueKoordinateY,neueKoordinateZ);
}
else{
return new Vector();
}
}
/**
* Skalarmultiplikation: Multiplikation des Vektors mit einem Skalar.
* @param skalar Skalar, mit dem der Vektor multipliziert werden soll
* */
public Vector multipliziere(double skalar){
/*neu berechnete Vektor Koordinaten*/
double koordinateX = this.getX() * skalar;
double koordinateY = this.getY() * skalar;
double koordinateZ = this.getZ() * skalar;
return new Vector(koordinateX,koordinateY,koordinateZ);
}
/**
* Skalarmultiplikation: Multiplikation des Vektors mit einem Vektor.
* @param vektor Vektor mit dem multipliziert wird.
*/
public double multipliziere(Vector vektor)throws java.lang.IllegalArgumentException{
if ( vektor instanceof Vector){
/*neu berechnete Vektor Koordinaten*/
double koordinateX = this.getX() * vektor.getX();
double koordinateY = this.getY() * vektor.getY();
double koordinateZ = this.getZ() * vektor.getZ();
double ergebniss = koordinateX + koordinateY + koordinateZ;
return ergebniss;
}else{ throw new java.lang.IllegalArgumentException();}
}
/**
* Wandelt Degree in Radian.
* @param rad Double
*/
public double radToDeg(double rad){
return rad*(180/Math.PI);
}
/**
* Bestimmt den eingeschlossenen Winkel von diesem und dem gegebenen Vektor.
* @param v Vector der andere.
*/
public double winkel(Vector v){
double skalarProdukt = multipliziere(v);
double laengenProdukt = this.betrag() * v.betrag();
double cosPhi = skalarProdukt / laengenProdukt;
double winkelRad = Math.acos(cosPhi);
double winkel=radToDeg(winkelRad);
return winkel;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Vector vector = (Vector) o;
if (Double.compare(vector.x, x) != 0) return false;
if (Double.compare(vector.y, y) != 0) return false;
if (Double.compare(vector.z, z) != 0) return false;
return true;
}
@Override
public int hashCode() {
int result;
long temp;
temp = Double.doubleToLongBits(x);
result = (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(y);
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(z);
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
/**
* Gibt den Vektor aus
*/
@Override
public String toString(){
String ausgabeX = String.format("%.2f",getX());
String ausgabeY = String.format("%.2f",getY());
String ausgabeZ = String.format("%.2f",getZ());
String ausgabe = new String("[ "+ ausgabeX+" "+ ausgabeY+" "+ausgabeZ+" ]");
return ausgabe;
}
}
| MEP2014-TeamBlue/TestFuerTPE | exercise1/src/Vector.java | 2,086 | /**
* Erzeugt einen neuen Vektor mit den angebgebenen Elementen
* @param x Koordinate1
* @param y Koordinate2
* @param z Koordinate3
*/ | block_comment | nl | package de.hs.mannheim.tpe.smits.group3.impl;
/**
* Klasse Vektor. Für einen 3 dimensionalen Vektor R3
* @author alexanderschaaf
*/
public class Vector{
/**
* Koordinaten des 3D Vektors
*/
private double x;
private double y;
private double z;
/**
* Erzeugt einen Null-Vector, d.h. den Vektor bei dem alle Komponenten den Wert 0 haben.
* */
public Vector (){
this.x = 0.0d;
this.y = 0.0d;
this.z = 0.0d;
}
/**
* Erzeugt einen neuen<SUF>*/
public Vector( double x, double y, double z){
this.x = x;
this.y = y;
this.z = z;
}
/**
*Addiert den gegebenen Vektor zu diesem.
*@param vektor Der Vektor der hinzu addiert wird
*/
public Vector addiere(Vector vektor) throws java.lang.IllegalArgumentException{
if ( vektor instanceof Vector){
/*neu berechnete Vektor Koordinaten*/
double koordinateX = this.getX() + vektor.getX();
double koordinateY = this.getY() + vektor.getY();
double koordinateZ = this.getZ() + vektor.getZ();
return new Vector(koordinateX,koordinateY,koordinateZ);
}
else {throw new java.lang.IllegalArgumentException();}
}
/**
* Bestimmt den Betrag (die Länge) dieses Vektors.
* @return Die Länge des Vektors
*/
public double betrag (){
double exp = 2.0;
double radikant1 = Math.pow(this.getX(),exp);
double radikant2 = Math.pow(this.getY(),exp);
double radikant3 = Math.pow(this.getZ(),exp);
return Math.sqrt(radikant1 + radikant2 + radikant3);
}
/**
* Liefert einen Vektor zurück, der diesem Vektor bezüglich der Richtung entspricht,
* aber auf die Länge 1 normiert ist.
*/
public Vector einheitsvektor() throws java.lang.IllegalStateException{
Vector einheitsVektor;
if (this.betrag() == 0.00){
throw new java.lang.IllegalStateException("Vektor hat die länge 0.00");
}else{
einheitsVektor = multipliziere(1 / this.betrag());
}
return einheitsVektor;
}
/**
* Liefert die 1. Komponente des Vektors
* */
public double getX(){
return x;
}
/**
* Liefert die 2. Komponente des Vektors
* */
public double getY(){
return y;
}
/**
* Liefert die 3. Komponente des Vektors
*/
public double getZ(){
return z;
}
/**
* Bestimmt das Kreuzprodukt dises mit dem gegebenen Vektor.
* @param v Vektor
* @return kreuzprodukt Das Kreuzprodukt der zwei Vektoren
*
*/
public Vector kreuzprodukt(Vector v){
double neueKoordinateX;
double neueKoordinateY;
double neueKoordinateZ;
double winkel = winkel(v);
if (winkel <= 180.00){
neueKoordinateX= (this.getY()* v.getZ())-(this.getZ()*v.getY());
neueKoordinateY= (this.getZ()* v.getX())-(this.getX()*v.getZ());
neueKoordinateZ= (this.getX()* v.getY())-(this.getY()*v.getX());
return new Vector(neueKoordinateX,neueKoordinateY,neueKoordinateZ);
}
else{
return new Vector();
}
}
/**
* Skalarmultiplikation: Multiplikation des Vektors mit einem Skalar.
* @param skalar Skalar, mit dem der Vektor multipliziert werden soll
* */
public Vector multipliziere(double skalar){
/*neu berechnete Vektor Koordinaten*/
double koordinateX = this.getX() * skalar;
double koordinateY = this.getY() * skalar;
double koordinateZ = this.getZ() * skalar;
return new Vector(koordinateX,koordinateY,koordinateZ);
}
/**
* Skalarmultiplikation: Multiplikation des Vektors mit einem Vektor.
* @param vektor Vektor mit dem multipliziert wird.
*/
public double multipliziere(Vector vektor)throws java.lang.IllegalArgumentException{
if ( vektor instanceof Vector){
/*neu berechnete Vektor Koordinaten*/
double koordinateX = this.getX() * vektor.getX();
double koordinateY = this.getY() * vektor.getY();
double koordinateZ = this.getZ() * vektor.getZ();
double ergebniss = koordinateX + koordinateY + koordinateZ;
return ergebniss;
}else{ throw new java.lang.IllegalArgumentException();}
}
/**
* Wandelt Degree in Radian.
* @param rad Double
*/
public double radToDeg(double rad){
return rad*(180/Math.PI);
}
/**
* Bestimmt den eingeschlossenen Winkel von diesem und dem gegebenen Vektor.
* @param v Vector der andere.
*/
public double winkel(Vector v){
double skalarProdukt = multipliziere(v);
double laengenProdukt = this.betrag() * v.betrag();
double cosPhi = skalarProdukt / laengenProdukt;
double winkelRad = Math.acos(cosPhi);
double winkel=radToDeg(winkelRad);
return winkel;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Vector vector = (Vector) o;
if (Double.compare(vector.x, x) != 0) return false;
if (Double.compare(vector.y, y) != 0) return false;
if (Double.compare(vector.z, z) != 0) return false;
return true;
}
@Override
public int hashCode() {
int result;
long temp;
temp = Double.doubleToLongBits(x);
result = (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(y);
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(z);
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
/**
* Gibt den Vektor aus
*/
@Override
public String toString(){
String ausgabeX = String.format("%.2f",getX());
String ausgabeY = String.format("%.2f",getY());
String ausgabeZ = String.format("%.2f",getZ());
String ausgabe = new String("[ "+ ausgabeX+" "+ ausgabeY+" "+ausgabeZ+" ]");
return ausgabe;
}
}
| False | 1,748 | 49 | 1,920 | 49 | 1,862 | 47 | 1,920 | 49 | 2,107 | 49 | false | false | false | false | false | true |
314 | 174333_3 | package nl.cerios.cerioscoop.service;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.sql.DataSource;
import nl.cerios.cerioscoop.ValueObjects.ShowPresentationVO;
import nl.cerios.cerioscoop.ValueObjects.ShowsPresentationVO;
import nl.cerios.cerioscoop.domain.Customer;
import nl.cerios.cerioscoop.domain.Movie;
import nl.cerios.cerioscoop.domain.MovieBuilder;
import nl.cerios.cerioscoop.domain.Show;
import nl.cerios.cerioscoop.domain.User;
import nl.cerios.cerioscoop.util.DateUtils;
@Stateless //Stateless is de status van de gevulde opjecten. Best Practice is stateless.
public class GeneralService {
@Resource(name = "jdbc/cerioscoop") //Content Dependency Injection techniek
private DataSource dataSource;
private DateUtils dateUtils = new DateUtils();
public List<Movie> getMovies(){
final List<Movie> movies = new ArrayList<>();
try (final Connection connection = dataSource.getConnection()) { //AutoCloseable
final Statement statement = connection.createStatement();
final ResultSet resultSet = statement.executeQuery("SELECT movie_id, title, movie_description FROM movie");
while (resultSet.next()) {
final Movie movie = new MovieBuilder()
.withMovieId(resultSet.getBigDecimal("movie_id").toBigInteger())
.withMovieTitle(resultSet.getString("title"))
.withMovieDescription(resultSet.getString("movie_description"))
.build();
movies.add(movie);
}
return movies;
}catch (final SQLException e) {
throw new ServiceException("Something went terribly wrong while retrieving the movie.", e);
}
}
public List<Show> getShows(){
final List<Show> shows = new ArrayList<>();
try (final Connection connection = dataSource.getConnection()){
final Statement statement = connection.createStatement();
final ResultSet resultSet = statement.executeQuery("SELECT show_id, movie_id, room_id, show_date, show_time, available_places, show_price FROM show_table"); {
while (resultSet.next()) {
final int showId = resultSet.getInt("show_id");
final int movieId = resultSet.getInt("movie_id");
final int roomId = resultSet.getInt("room_id");
final Date showDate = resultSet.getDate("show_date");
final Time showTime = resultSet.getTime("show_time");
final int availablePlaces = resultSet.getInt("available_places");
final float showPrice = resultSet.getInt("show_price");
shows.add(new Show(showId, movieId, roomId, showDate, showTime, availablePlaces, showPrice));
}
return shows;
}
}catch (final SQLException e) {
throw new ServiceException("Something went terribly wrong while retrieving the first date.", e);
}
}
public List<Customer> getCustomers(){
final List<Customer> customers = new ArrayList<>();
try (final Connection connection = dataSource.getConnection()){
final Statement statement = connection.createStatement();
final ResultSet resultSet = statement.executeQuery("SELECT customer_id, first_name, last_name, username, password, email FROM customer"); {
while (resultSet.next()) {
final int customerId = resultSet.getInt("customer_id");
final String firstName = resultSet.getString("first_name");
final String lastName = resultSet.getString("last_name");
final String username = resultSet.getString("username");
final String password = resultSet.getString("password");
final String email = resultSet.getString("email");
customers.add(new Customer(customerId, firstName, lastName, username, password, email));
}
return customers;
}
}catch (final SQLException e) {
throw new ServiceException("Something went terribly wrong while retrieving the customers.", e);
}
}
/**
* Returns a first showing record.
*
* @return firstShowing
*/
public Show getFirstShowforToday(final List<Show> listOfShows){
Show firstShow = null;
for (final Show show : listOfShows) {
if(dateUtils.toDateTime(show.getShowDate(), show.getShowTime()).after(dateUtils.getCurrentSqlTime())){
if(firstShow == null){ //hier wordt voor 1x eerstVolgendeFilm gevuld
firstShow = show;
}
else if(show.getShowTime().before(firstShow.getShowTime())){
firstShow = show;
}
}
}
return firstShow;
}
public Movie getMovieByMovieId(final int movieId, final List<Movie> listOfMovies) throws MovieNotFoundException {
final List<Movie> movies = listOfMovies;
Movie movieByMovieId = null;
for (final Movie movieItem : movies){
if (movieItem.getMovieId().intValue() == movieId) {
movieByMovieId = movieItem;
}
}
return movieByMovieId;
}
public void registerCustomer(final Customer customer){
try (final Connection connection = dataSource.getConnection();
final PreparedStatement preparedStatement = connection.prepareStatement(
"INSERT INTO customer (first_name, last_name, username, password, email) VALUES (?,?,?,?,?)")) {
preparedStatement.setString(1, customer.getFirstName());
preparedStatement.setString(2, customer.getLastName());
preparedStatement.setString(3, customer.getUsername());
preparedStatement.setString(4, customer.getPassword());
preparedStatement.setString(5, customer.getEmail());
preparedStatement.executeUpdate();
System.out.println("Data inserted.");
}catch (final SQLException e) {
throw new ServiceException("Something went wrong while inserting the customer items.", e);
}
}
public User authenticateCustomer(User customer, List<Customer> listOfCustomers){
final List<Customer> dbCustomers = listOfCustomers;
final String usernameCustomer = customer.getUsername();
final String passwordCustomer = customer.getPassword();
User authenticatedCustomer = null;
for (final Customer customerItem : dbCustomers){
if(customerItem.getUsername().equals(usernameCustomer) && customerItem.getPassword().equals(passwordCustomer)){
authenticatedCustomer = customerItem;
}
}
return authenticatedCustomer;
}
public Boolean authenticateUser(User authenticatedUser){
if(authenticatedUser == null){
return false;
}
return true;
}
public List<ShowsPresentationVO> generateShowTable(final List<Show> shows, final List<Movie> movies) throws MovieNotFoundException {
List<ShowsPresentationVO> todaysShowsTable = new ArrayList<ShowsPresentationVO>();
// voeg alle shows toe aan de tabel
for (Show todaysShow : shows) {
ShowsPresentationVO existingShowsPresentationVORow = null; // checkt of de movie van de huidige tabel al is opgenomen
for (ShowsPresentationVO showsRowIter : todaysShowsTable) {
if (todaysShow.getMovieId() == showsRowIter.getMovie().getMovieId().intValue()) {// hier bestaat de movie al in de index
ShowPresentationVO newShowPresentationVO = new ShowPresentationVO();
newShowPresentationVO.setShow(todaysShow);
newShowPresentationVO.setSoldOut(checkIfThereAreNoAvailablePlaces(todaysShow.getAvailablePlaces()));
showsRowIter.shows.add(newShowPresentationVO);
existingShowsPresentationVORow = showsRowIter;
}
}
if (existingShowsPresentationVORow == null) {//Nieuwe MovieRow worst gemaakt
ShowPresentationVO newShowPresentationVO = new ShowPresentationVO();
newShowPresentationVO.setShow(todaysShow);
newShowPresentationVO.setSoldOut(checkIfThereAreNoAvailablePlaces(todaysShow.getAvailablePlaces()));
ShowsPresentationVO newShowsPresentationRowVO = new ShowsPresentationVO();
List<ShowPresentationVO> showPresentationVOList = new ArrayList<ShowPresentationVO>();
showPresentationVOList.add(newShowPresentationVO);
newShowsPresentationRowVO.setMovie(getMovieByMovieId(todaysShow.getMovieId(), movies));
newShowsPresentationRowVO.setShowsPresentationVO(showPresentationVOList);
todaysShowsTable.add(newShowsPresentationRowVO);
}
}
return todaysShowsTable;
}
public String generateRandomUsername(){
char[] chars = "abcdefghijklmnopqrstuvwxyz1234567890".toCharArray();
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 20; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
return sb.toString();
}
public Boolean checkIfThereAreNoAvailablePlaces(int availablePlaces){
if(availablePlaces == 0){
return true;
}else{
return false;
}
}
}
| Cerios/cerioscoop-web | src/main/java/nl/cerios/cerioscoop/service/GeneralService.java | 2,747 | //hier wordt voor 1x eerstVolgendeFilm gevuld | line_comment | nl | package nl.cerios.cerioscoop.service;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.sql.DataSource;
import nl.cerios.cerioscoop.ValueObjects.ShowPresentationVO;
import nl.cerios.cerioscoop.ValueObjects.ShowsPresentationVO;
import nl.cerios.cerioscoop.domain.Customer;
import nl.cerios.cerioscoop.domain.Movie;
import nl.cerios.cerioscoop.domain.MovieBuilder;
import nl.cerios.cerioscoop.domain.Show;
import nl.cerios.cerioscoop.domain.User;
import nl.cerios.cerioscoop.util.DateUtils;
@Stateless //Stateless is de status van de gevulde opjecten. Best Practice is stateless.
public class GeneralService {
@Resource(name = "jdbc/cerioscoop") //Content Dependency Injection techniek
private DataSource dataSource;
private DateUtils dateUtils = new DateUtils();
public List<Movie> getMovies(){
final List<Movie> movies = new ArrayList<>();
try (final Connection connection = dataSource.getConnection()) { //AutoCloseable
final Statement statement = connection.createStatement();
final ResultSet resultSet = statement.executeQuery("SELECT movie_id, title, movie_description FROM movie");
while (resultSet.next()) {
final Movie movie = new MovieBuilder()
.withMovieId(resultSet.getBigDecimal("movie_id").toBigInteger())
.withMovieTitle(resultSet.getString("title"))
.withMovieDescription(resultSet.getString("movie_description"))
.build();
movies.add(movie);
}
return movies;
}catch (final SQLException e) {
throw new ServiceException("Something went terribly wrong while retrieving the movie.", e);
}
}
public List<Show> getShows(){
final List<Show> shows = new ArrayList<>();
try (final Connection connection = dataSource.getConnection()){
final Statement statement = connection.createStatement();
final ResultSet resultSet = statement.executeQuery("SELECT show_id, movie_id, room_id, show_date, show_time, available_places, show_price FROM show_table"); {
while (resultSet.next()) {
final int showId = resultSet.getInt("show_id");
final int movieId = resultSet.getInt("movie_id");
final int roomId = resultSet.getInt("room_id");
final Date showDate = resultSet.getDate("show_date");
final Time showTime = resultSet.getTime("show_time");
final int availablePlaces = resultSet.getInt("available_places");
final float showPrice = resultSet.getInt("show_price");
shows.add(new Show(showId, movieId, roomId, showDate, showTime, availablePlaces, showPrice));
}
return shows;
}
}catch (final SQLException e) {
throw new ServiceException("Something went terribly wrong while retrieving the first date.", e);
}
}
public List<Customer> getCustomers(){
final List<Customer> customers = new ArrayList<>();
try (final Connection connection = dataSource.getConnection()){
final Statement statement = connection.createStatement();
final ResultSet resultSet = statement.executeQuery("SELECT customer_id, first_name, last_name, username, password, email FROM customer"); {
while (resultSet.next()) {
final int customerId = resultSet.getInt("customer_id");
final String firstName = resultSet.getString("first_name");
final String lastName = resultSet.getString("last_name");
final String username = resultSet.getString("username");
final String password = resultSet.getString("password");
final String email = resultSet.getString("email");
customers.add(new Customer(customerId, firstName, lastName, username, password, email));
}
return customers;
}
}catch (final SQLException e) {
throw new ServiceException("Something went terribly wrong while retrieving the customers.", e);
}
}
/**
* Returns a first showing record.
*
* @return firstShowing
*/
public Show getFirstShowforToday(final List<Show> listOfShows){
Show firstShow = null;
for (final Show show : listOfShows) {
if(dateUtils.toDateTime(show.getShowDate(), show.getShowTime()).after(dateUtils.getCurrentSqlTime())){
if(firstShow == null){ //hier wordt<SUF>
firstShow = show;
}
else if(show.getShowTime().before(firstShow.getShowTime())){
firstShow = show;
}
}
}
return firstShow;
}
public Movie getMovieByMovieId(final int movieId, final List<Movie> listOfMovies) throws MovieNotFoundException {
final List<Movie> movies = listOfMovies;
Movie movieByMovieId = null;
for (final Movie movieItem : movies){
if (movieItem.getMovieId().intValue() == movieId) {
movieByMovieId = movieItem;
}
}
return movieByMovieId;
}
public void registerCustomer(final Customer customer){
try (final Connection connection = dataSource.getConnection();
final PreparedStatement preparedStatement = connection.prepareStatement(
"INSERT INTO customer (first_name, last_name, username, password, email) VALUES (?,?,?,?,?)")) {
preparedStatement.setString(1, customer.getFirstName());
preparedStatement.setString(2, customer.getLastName());
preparedStatement.setString(3, customer.getUsername());
preparedStatement.setString(4, customer.getPassword());
preparedStatement.setString(5, customer.getEmail());
preparedStatement.executeUpdate();
System.out.println("Data inserted.");
}catch (final SQLException e) {
throw new ServiceException("Something went wrong while inserting the customer items.", e);
}
}
public User authenticateCustomer(User customer, List<Customer> listOfCustomers){
final List<Customer> dbCustomers = listOfCustomers;
final String usernameCustomer = customer.getUsername();
final String passwordCustomer = customer.getPassword();
User authenticatedCustomer = null;
for (final Customer customerItem : dbCustomers){
if(customerItem.getUsername().equals(usernameCustomer) && customerItem.getPassword().equals(passwordCustomer)){
authenticatedCustomer = customerItem;
}
}
return authenticatedCustomer;
}
public Boolean authenticateUser(User authenticatedUser){
if(authenticatedUser == null){
return false;
}
return true;
}
public List<ShowsPresentationVO> generateShowTable(final List<Show> shows, final List<Movie> movies) throws MovieNotFoundException {
List<ShowsPresentationVO> todaysShowsTable = new ArrayList<ShowsPresentationVO>();
// voeg alle shows toe aan de tabel
for (Show todaysShow : shows) {
ShowsPresentationVO existingShowsPresentationVORow = null; // checkt of de movie van de huidige tabel al is opgenomen
for (ShowsPresentationVO showsRowIter : todaysShowsTable) {
if (todaysShow.getMovieId() == showsRowIter.getMovie().getMovieId().intValue()) {// hier bestaat de movie al in de index
ShowPresentationVO newShowPresentationVO = new ShowPresentationVO();
newShowPresentationVO.setShow(todaysShow);
newShowPresentationVO.setSoldOut(checkIfThereAreNoAvailablePlaces(todaysShow.getAvailablePlaces()));
showsRowIter.shows.add(newShowPresentationVO);
existingShowsPresentationVORow = showsRowIter;
}
}
if (existingShowsPresentationVORow == null) {//Nieuwe MovieRow worst gemaakt
ShowPresentationVO newShowPresentationVO = new ShowPresentationVO();
newShowPresentationVO.setShow(todaysShow);
newShowPresentationVO.setSoldOut(checkIfThereAreNoAvailablePlaces(todaysShow.getAvailablePlaces()));
ShowsPresentationVO newShowsPresentationRowVO = new ShowsPresentationVO();
List<ShowPresentationVO> showPresentationVOList = new ArrayList<ShowPresentationVO>();
showPresentationVOList.add(newShowPresentationVO);
newShowsPresentationRowVO.setMovie(getMovieByMovieId(todaysShow.getMovieId(), movies));
newShowsPresentationRowVO.setShowsPresentationVO(showPresentationVOList);
todaysShowsTable.add(newShowsPresentationRowVO);
}
}
return todaysShowsTable;
}
public String generateRandomUsername(){
char[] chars = "abcdefghijklmnopqrstuvwxyz1234567890".toCharArray();
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 20; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
return sb.toString();
}
public Boolean checkIfThereAreNoAvailablePlaces(int availablePlaces){
if(availablePlaces == 0){
return true;
}else{
return false;
}
}
}
| True | 1,908 | 16 | 2,265 | 18 | 2,298 | 14 | 2,265 | 18 | 2,893 | 20 | false | false | false | false | false | true |
4,549 | 131463_4 | /*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package org.jbox2d.collision;
import org.jbox2d.common.MathUtils;
import org.jbox2d.common.Rot;
import org.jbox2d.common.Settings;
import org.jbox2d.common.Transform;
import org.jbox2d.common.Vec2;
/** This is used to compute the current state of a contact manifold.
*
* @author daniel */
public class WorldManifold {
/** World vector pointing from A to B */
public final Vec2 normal;
/** World contact point (point of intersection) */
public final Vec2[] points;
/** A negative value indicates overlap, in meters. */
public final float[] separations;
public WorldManifold () {
normal = new Vec2();
points = new Vec2[Settings.maxManifoldPoints];
separations = new float[Settings.maxManifoldPoints];
for (int i = 0; i < Settings.maxManifoldPoints; i++) {
points[i] = new Vec2();
}
}
private final Vec2 pool3 = new Vec2();
private final Vec2 pool4 = new Vec2();
public final void initialize (final Manifold manifold, final Transform xfA, float radiusA, final Transform xfB,
float radiusB) {
if (manifold.pointCount == 0) {
return;
}
switch (manifold.type) {
case CIRCLES: {
final Vec2 pointA = pool3;
final Vec2 pointB = pool4;
normal.x = 1;
normal.y = 0;
Vec2 v = manifold.localPoint;
// Transform.mulToOutUnsafe(xfA, manifold.localPoint, pointA);
// Transform.mulToOutUnsafe(xfB, manifold.points[0].localPoint, pointB);
pointA.x = (xfA.q.c * v.x - xfA.q.s * v.y) + xfA.p.x;
pointA.y = (xfA.q.s * v.x + xfA.q.c * v.y) + xfA.p.y;
Vec2 mp0p = manifold.points[0].localPoint;
pointB.x = (xfB.q.c * mp0p.x - xfB.q.s * mp0p.y) + xfB.p.x;
pointB.y = (xfB.q.s * mp0p.x + xfB.q.c * mp0p.y) + xfB.p.y;
if (MathUtils.distanceSquared(pointA, pointB) > Settings.EPSILON * Settings.EPSILON) {
normal.x = pointB.x - pointA.x;
normal.y = pointB.y - pointA.y;
normal.normalize();
}
final float cAx = normal.x * radiusA + pointA.x;
final float cAy = normal.y * radiusA + pointA.y;
final float cBx = -normal.x * radiusB + pointB.x;
final float cBy = -normal.y * radiusB + pointB.y;
points[0].x = (cAx + cBx) * .5f;
points[0].y = (cAy + cBy) * .5f;
separations[0] = (cBx - cAx) * normal.x + (cBy - cAy) * normal.y;
}
break;
case FACE_A: {
final Vec2 planePoint = pool3;
Rot.mulToOutUnsafe(xfA.q, manifold.localNormal, normal);
Transform.mulToOut(xfA, manifold.localPoint, planePoint);
final Vec2 clipPoint = pool4;
for (int i = 0; i < manifold.pointCount; i++) {
// b2Vec2 clipPoint = b2Mul(xfB, manifold->points[i].localPoint);
// b2Vec2 cA = clipPoint + (radiusA - b2Dot(clipPoint - planePoint,
// normal)) * normal;
// b2Vec2 cB = clipPoint - radiusB * normal;
// points[i] = 0.5f * (cA + cB);
Transform.mulToOut(xfB, manifold.points[i].localPoint, clipPoint);
// use cA as temporary for now
// cA.set(clipPoint).subLocal(planePoint);
// float scalar = radiusA - Vec2.dot(cA, normal);
// cA.set(normal).mulLocal(scalar).addLocal(clipPoint);
// cB.set(normal).mulLocal(radiusB).subLocal(clipPoint).negateLocal();
// points[i].set(cA).addLocal(cB).mulLocal(0.5f);
final float scalar = radiusA - ((clipPoint.x - planePoint.x) * normal.x + (clipPoint.y - planePoint.y) * normal.y);
final float cAx = normal.x * scalar + clipPoint.x;
final float cAy = normal.y * scalar + clipPoint.y;
final float cBx = -normal.x * radiusB + clipPoint.x;
final float cBy = -normal.y * radiusB + clipPoint.y;
points[i].x = (cAx + cBx) * .5f;
points[i].y = (cAy + cBy) * .5f;
separations[i] = (cBx - cAx) * normal.x + (cBy - cAy) * normal.y;
}
}
break;
case FACE_B:
final Vec2 planePoint = pool3;
Rot.mulToOutUnsafe(xfB.q, manifold.localNormal, normal);
Transform.mulToOut(xfB, manifold.localPoint, planePoint);
// final Mat22 R = xfB.q;
// normal.x = R.ex.x * manifold.localNormal.x + R.ey.x * manifold.localNormal.y;
// normal.y = R.ex.y * manifold.localNormal.x + R.ey.y * manifold.localNormal.y;
// final Vec2 v = manifold.localPoint;
// planePoint.x = xfB.p.x + xfB.q.ex.x * v.x + xfB.q.ey.x * v.y;
// planePoint.y = xfB.p.y + xfB.q.ex.y * v.x + xfB.q.ey.y * v.y;
final Vec2 clipPoint = pool4;
for (int i = 0; i < manifold.pointCount; i++) {
// b2Vec2 clipPoint = b2Mul(xfA, manifold->points[i].localPoint);
// b2Vec2 cB = clipPoint + (radiusB - b2Dot(clipPoint - planePoint,
// normal)) * normal;
// b2Vec2 cA = clipPoint - radiusA * normal;
// points[i] = 0.5f * (cA + cB);
Transform.mulToOut(xfA, manifold.points[i].localPoint, clipPoint);
// cB.set(clipPoint).subLocal(planePoint);
// float scalar = radiusB - Vec2.dot(cB, normal);
// cB.set(normal).mulLocal(scalar).addLocal(clipPoint);
// cA.set(normal).mulLocal(radiusA).subLocal(clipPoint).negateLocal();
// points[i].set(cA).addLocal(cB).mulLocal(0.5f);
// points[i] = 0.5f * (cA + cB);
//
// clipPoint.x = xfA.p.x + xfA.q.ex.x * manifold.points[i].localPoint.x + xfA.q.ey.x *
// manifold.points[i].localPoint.y;
// clipPoint.y = xfA.p.y + xfA.q.ex.y * manifold.points[i].localPoint.x + xfA.q.ey.y *
// manifold.points[i].localPoint.y;
final float scalar = radiusB - ((clipPoint.x - planePoint.x) * normal.x + (clipPoint.y - planePoint.y) * normal.y);
final float cBx = normal.x * scalar + clipPoint.x;
final float cBy = normal.y * scalar + clipPoint.y;
final float cAx = -normal.x * radiusA + clipPoint.x;
final float cAy = -normal.y * radiusA + clipPoint.y;
points[i].x = (cAx + cBx) * .5f;
points[i].y = (cAy + cBy) * .5f;
separations[i] = (cAx - cBx) * normal.x + (cAy - cBy) * normal.y;
}
// Ensure normal points from A to B.
normal.x = -normal.x;
normal.y = -normal.y;
break;
}
}
}
| tommyettinger/libgdx | extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/org/jbox2d/collision/WorldManifold.java | 2,823 | /** A negative value indicates overlap, in meters. */ | block_comment | nl | /*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package org.jbox2d.collision;
import org.jbox2d.common.MathUtils;
import org.jbox2d.common.Rot;
import org.jbox2d.common.Settings;
import org.jbox2d.common.Transform;
import org.jbox2d.common.Vec2;
/** This is used to compute the current state of a contact manifold.
*
* @author daniel */
public class WorldManifold {
/** World vector pointing from A to B */
public final Vec2 normal;
/** World contact point (point of intersection) */
public final Vec2[] points;
/** A negative value<SUF>*/
public final float[] separations;
public WorldManifold () {
normal = new Vec2();
points = new Vec2[Settings.maxManifoldPoints];
separations = new float[Settings.maxManifoldPoints];
for (int i = 0; i < Settings.maxManifoldPoints; i++) {
points[i] = new Vec2();
}
}
private final Vec2 pool3 = new Vec2();
private final Vec2 pool4 = new Vec2();
public final void initialize (final Manifold manifold, final Transform xfA, float radiusA, final Transform xfB,
float radiusB) {
if (manifold.pointCount == 0) {
return;
}
switch (manifold.type) {
case CIRCLES: {
final Vec2 pointA = pool3;
final Vec2 pointB = pool4;
normal.x = 1;
normal.y = 0;
Vec2 v = manifold.localPoint;
// Transform.mulToOutUnsafe(xfA, manifold.localPoint, pointA);
// Transform.mulToOutUnsafe(xfB, manifold.points[0].localPoint, pointB);
pointA.x = (xfA.q.c * v.x - xfA.q.s * v.y) + xfA.p.x;
pointA.y = (xfA.q.s * v.x + xfA.q.c * v.y) + xfA.p.y;
Vec2 mp0p = manifold.points[0].localPoint;
pointB.x = (xfB.q.c * mp0p.x - xfB.q.s * mp0p.y) + xfB.p.x;
pointB.y = (xfB.q.s * mp0p.x + xfB.q.c * mp0p.y) + xfB.p.y;
if (MathUtils.distanceSquared(pointA, pointB) > Settings.EPSILON * Settings.EPSILON) {
normal.x = pointB.x - pointA.x;
normal.y = pointB.y - pointA.y;
normal.normalize();
}
final float cAx = normal.x * radiusA + pointA.x;
final float cAy = normal.y * radiusA + pointA.y;
final float cBx = -normal.x * radiusB + pointB.x;
final float cBy = -normal.y * radiusB + pointB.y;
points[0].x = (cAx + cBx) * .5f;
points[0].y = (cAy + cBy) * .5f;
separations[0] = (cBx - cAx) * normal.x + (cBy - cAy) * normal.y;
}
break;
case FACE_A: {
final Vec2 planePoint = pool3;
Rot.mulToOutUnsafe(xfA.q, manifold.localNormal, normal);
Transform.mulToOut(xfA, manifold.localPoint, planePoint);
final Vec2 clipPoint = pool4;
for (int i = 0; i < manifold.pointCount; i++) {
// b2Vec2 clipPoint = b2Mul(xfB, manifold->points[i].localPoint);
// b2Vec2 cA = clipPoint + (radiusA - b2Dot(clipPoint - planePoint,
// normal)) * normal;
// b2Vec2 cB = clipPoint - radiusB * normal;
// points[i] = 0.5f * (cA + cB);
Transform.mulToOut(xfB, manifold.points[i].localPoint, clipPoint);
// use cA as temporary for now
// cA.set(clipPoint).subLocal(planePoint);
// float scalar = radiusA - Vec2.dot(cA, normal);
// cA.set(normal).mulLocal(scalar).addLocal(clipPoint);
// cB.set(normal).mulLocal(radiusB).subLocal(clipPoint).negateLocal();
// points[i].set(cA).addLocal(cB).mulLocal(0.5f);
final float scalar = radiusA - ((clipPoint.x - planePoint.x) * normal.x + (clipPoint.y - planePoint.y) * normal.y);
final float cAx = normal.x * scalar + clipPoint.x;
final float cAy = normal.y * scalar + clipPoint.y;
final float cBx = -normal.x * radiusB + clipPoint.x;
final float cBy = -normal.y * radiusB + clipPoint.y;
points[i].x = (cAx + cBx) * .5f;
points[i].y = (cAy + cBy) * .5f;
separations[i] = (cBx - cAx) * normal.x + (cBy - cAy) * normal.y;
}
}
break;
case FACE_B:
final Vec2 planePoint = pool3;
Rot.mulToOutUnsafe(xfB.q, manifold.localNormal, normal);
Transform.mulToOut(xfB, manifold.localPoint, planePoint);
// final Mat22 R = xfB.q;
// normal.x = R.ex.x * manifold.localNormal.x + R.ey.x * manifold.localNormal.y;
// normal.y = R.ex.y * manifold.localNormal.x + R.ey.y * manifold.localNormal.y;
// final Vec2 v = manifold.localPoint;
// planePoint.x = xfB.p.x + xfB.q.ex.x * v.x + xfB.q.ey.x * v.y;
// planePoint.y = xfB.p.y + xfB.q.ex.y * v.x + xfB.q.ey.y * v.y;
final Vec2 clipPoint = pool4;
for (int i = 0; i < manifold.pointCount; i++) {
// b2Vec2 clipPoint = b2Mul(xfA, manifold->points[i].localPoint);
// b2Vec2 cB = clipPoint + (radiusB - b2Dot(clipPoint - planePoint,
// normal)) * normal;
// b2Vec2 cA = clipPoint - radiusA * normal;
// points[i] = 0.5f * (cA + cB);
Transform.mulToOut(xfA, manifold.points[i].localPoint, clipPoint);
// cB.set(clipPoint).subLocal(planePoint);
// float scalar = radiusB - Vec2.dot(cB, normal);
// cB.set(normal).mulLocal(scalar).addLocal(clipPoint);
// cA.set(normal).mulLocal(radiusA).subLocal(clipPoint).negateLocal();
// points[i].set(cA).addLocal(cB).mulLocal(0.5f);
// points[i] = 0.5f * (cA + cB);
//
// clipPoint.x = xfA.p.x + xfA.q.ex.x * manifold.points[i].localPoint.x + xfA.q.ey.x *
// manifold.points[i].localPoint.y;
// clipPoint.y = xfA.p.y + xfA.q.ex.y * manifold.points[i].localPoint.x + xfA.q.ey.y *
// manifold.points[i].localPoint.y;
final float scalar = radiusB - ((clipPoint.x - planePoint.x) * normal.x + (clipPoint.y - planePoint.y) * normal.y);
final float cBx = normal.x * scalar + clipPoint.x;
final float cBy = normal.y * scalar + clipPoint.y;
final float cAx = -normal.x * radiusA + clipPoint.x;
final float cAy = -normal.y * radiusA + clipPoint.y;
points[i].x = (cAx + cBx) * .5f;
points[i].y = (cAy + cBy) * .5f;
separations[i] = (cAx - cBx) * normal.x + (cAy - cBy) * normal.y;
}
// Ensure normal points from A to B.
normal.x = -normal.x;
normal.y = -normal.y;
break;
}
}
}
| False | 2,221 | 11 | 2,580 | 11 | 2,575 | 11 | 2,580 | 11 | 3,138 | 11 | false | false | false | false | false | true |
2,164 | 50849_6 | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
package software.amazon.awssdk.crt.http;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/**
* A wrapper class for http header key-value pairs
*/
public class HttpHeader {
private final static int BUFFER_INT_SIZE = 4;
private final static Charset UTF8 = StandardCharsets.UTF_8;
private byte[] name; /* Not final, Native will manually set name after calling empty Constructor. */
private byte[] value; /* Not final, Native will manually set value after calling empty Constructor. */
/** Called by Native to create a new HttpHeader. This is so that Native doesn't have to worry about UTF8
* encoding/decoding issues. The user thread will deal with them when they call getName() or getValue() **/
private HttpHeader() {}
/**
*
* @param name header name
* @param value header value
*/
public HttpHeader(String name, String value){
this.name = name.getBytes(UTF8);
this.value = value.getBytes(UTF8);
}
/**
*
* @param name header name
* @param value header value
*/
public HttpHeader(byte[] name, byte[] value){
this.name = name;
this.value = value;
}
/**
*
* @return the name of the header, converted to a UTF-8 string
*/
public String getName() {
if (name == null) {
return "";
}
return new String(name, UTF8);
}
/**
*
* @return the name of the header, in raw bytes
*/
public byte[] getNameBytes() {
return name;
}
/**
*
* @return the value of the header, converted to a UTF-8 string
*/
public String getValue() {
if (value == null) {
return "";
}
return new String(value, UTF8);
}
/**
*
* @return the value of the header, in raw bytes
*/
public byte[] getValueBytes() {
return value;
}
@Override
public String toString() {
return getName() + ":" + getValue();
}
/** Each header is marshalled as
* [4-bytes BE name length] [variable length name value] [4-bytes BE value length] [variable length value value]
* @param headersBlob Blob of encoded headers
* @return array of decoded headers
*/
public static List<HttpHeader> loadHeadersListFromMarshalledHeadersBlob(ByteBuffer headersBlob) {
List<HttpHeader> headers = new ArrayList<>(16);
while(headersBlob.hasRemaining()) {
int nameLen = headersBlob.getInt();
// we want to protect against 0 length header names, 0 length values are fine.
// the marshalling layer will make sure that even if a length is 0, the 0 will
// still be stored in the byte array.
if (nameLen > 0) {
byte[] nameBuf = new byte[nameLen];
headersBlob.get(nameBuf);
int valLen = headersBlob.getInt();
byte[] valueBuf = new byte[valLen];
headersBlob.get(valueBuf);
headers.add(new HttpHeader(nameBuf, valueBuf));
}
}
return headers;
}
/**
* Lists of headers are marshalled as follows:
*
* each string field is: [4-bytes BE] [variable length bytes specified by the
* previous field]
*
* @param headers List of header name-value pairs
*
* @return encoded blob of headers
*/
public static byte[] marshalHeadersForJni(List<HttpHeader> headers) {
int size = 0;
for (HttpHeader header : headers) {
if (header.getNameBytes().length > 0) {
size += header.getNameBytes().length + header.getValueBytes().length + (BUFFER_INT_SIZE * 2);
}
}
ByteBuffer buffer = ByteBuffer.allocate(size);
for (HttpHeader header : headers) {
if (header.getNameBytes().length > 0) {
buffer.putInt(header.getNameBytes().length);
buffer.put(header.getNameBytes());
buffer.putInt(header.getValueBytes().length);
buffer.put(header.getValueBytes());
}
}
return buffer.array();
}
/**
* @param headersBlob encoded headers blob
* @return array of headers
* @see #loadHeadersListFromMarshalledHeadersBlob
*/
public static HttpHeader[] loadHeadersFromMarshalledHeadersBlob(ByteBuffer headersBlob) {
List<HttpHeader> headers = loadHeadersListFromMarshalledHeadersBlob(headersBlob);
HttpHeader[] headersArray = new HttpHeader[headers.size()];
return headers.toArray(headersArray);
}
}
| awslabs/aws-crt-java | src/main/java/software/amazon/awssdk/crt/http/HttpHeader.java | 1,342 | /**
*
* @param name header name
* @param value header value
*/ | block_comment | nl | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
package software.amazon.awssdk.crt.http;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/**
* A wrapper class for http header key-value pairs
*/
public class HttpHeader {
private final static int BUFFER_INT_SIZE = 4;
private final static Charset UTF8 = StandardCharsets.UTF_8;
private byte[] name; /* Not final, Native will manually set name after calling empty Constructor. */
private byte[] value; /* Not final, Native will manually set value after calling empty Constructor. */
/** Called by Native to create a new HttpHeader. This is so that Native doesn't have to worry about UTF8
* encoding/decoding issues. The user thread will deal with them when they call getName() or getValue() **/
private HttpHeader() {}
/**
*
* @param name header name
* @param value header value
*/
public HttpHeader(String name, String value){
this.name = name.getBytes(UTF8);
this.value = value.getBytes(UTF8);
}
/**
*
* @param name header<SUF>*/
public HttpHeader(byte[] name, byte[] value){
this.name = name;
this.value = value;
}
/**
*
* @return the name of the header, converted to a UTF-8 string
*/
public String getName() {
if (name == null) {
return "";
}
return new String(name, UTF8);
}
/**
*
* @return the name of the header, in raw bytes
*/
public byte[] getNameBytes() {
return name;
}
/**
*
* @return the value of the header, converted to a UTF-8 string
*/
public String getValue() {
if (value == null) {
return "";
}
return new String(value, UTF8);
}
/**
*
* @return the value of the header, in raw bytes
*/
public byte[] getValueBytes() {
return value;
}
@Override
public String toString() {
return getName() + ":" + getValue();
}
/** Each header is marshalled as
* [4-bytes BE name length] [variable length name value] [4-bytes BE value length] [variable length value value]
* @param headersBlob Blob of encoded headers
* @return array of decoded headers
*/
public static List<HttpHeader> loadHeadersListFromMarshalledHeadersBlob(ByteBuffer headersBlob) {
List<HttpHeader> headers = new ArrayList<>(16);
while(headersBlob.hasRemaining()) {
int nameLen = headersBlob.getInt();
// we want to protect against 0 length header names, 0 length values are fine.
// the marshalling layer will make sure that even if a length is 0, the 0 will
// still be stored in the byte array.
if (nameLen > 0) {
byte[] nameBuf = new byte[nameLen];
headersBlob.get(nameBuf);
int valLen = headersBlob.getInt();
byte[] valueBuf = new byte[valLen];
headersBlob.get(valueBuf);
headers.add(new HttpHeader(nameBuf, valueBuf));
}
}
return headers;
}
/**
* Lists of headers are marshalled as follows:
*
* each string field is: [4-bytes BE] [variable length bytes specified by the
* previous field]
*
* @param headers List of header name-value pairs
*
* @return encoded blob of headers
*/
public static byte[] marshalHeadersForJni(List<HttpHeader> headers) {
int size = 0;
for (HttpHeader header : headers) {
if (header.getNameBytes().length > 0) {
size += header.getNameBytes().length + header.getValueBytes().length + (BUFFER_INT_SIZE * 2);
}
}
ByteBuffer buffer = ByteBuffer.allocate(size);
for (HttpHeader header : headers) {
if (header.getNameBytes().length > 0) {
buffer.putInt(header.getNameBytes().length);
buffer.put(header.getNameBytes());
buffer.putInt(header.getValueBytes().length);
buffer.put(header.getValueBytes());
}
}
return buffer.array();
}
/**
* @param headersBlob encoded headers blob
* @return array of headers
* @see #loadHeadersListFromMarshalledHeadersBlob
*/
public static HttpHeader[] loadHeadersFromMarshalledHeadersBlob(ByteBuffer headersBlob) {
List<HttpHeader> headers = loadHeadersListFromMarshalledHeadersBlob(headersBlob);
HttpHeader[] headersArray = new HttpHeader[headers.size()];
return headers.toArray(headersArray);
}
}
| False | 1,068 | 21 | 1,136 | 19 | 1,258 | 23 | 1,136 | 19 | 1,357 | 23 | false | false | false | false | false | true |
566 | 21120_0 | package be.intecbrussel.the_notebook.app;
import be.intecbrussel.the_notebook.entities.animal_entities.Animal;
import be.intecbrussel.the_notebook.entities.animal_entities.Carnivore;
import be.intecbrussel.the_notebook.entities.animal_entities.Herbivore;
import be.intecbrussel.the_notebook.entities.animal_entities.Omnivore;
import be.intecbrussel.the_notebook.entities.plant_entities.*;
import be.intecbrussel.the_notebook.service.ForestNotebook;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
public class NatureApp {
public static void main(String[] args) {
lineGenerator();
System.out.println("FOREST NOTEBOOK TEST");
lineGenerator();
ForestNotebook forestNotebook = new ForestNotebook();
Plant plant = new Plant("Orchid", 0.55);
Tree tree = new Tree("Pine tree", 40.5);
tree.setLeafType(LeafType.NEEDLE);
Flower flower = new Flower("Rose", 0.15);
flower.setSmell(Scent.SWEET);
Weed weed = new Weed("Dandelion", 0.05);
// Geen idee over wat was de echte bedoeling van deze methode hieronder. Ik heb een willekeurig cijfer daarin geplaatst.
weed.setArea(10.5);
Bush bush = new Bush("Blueberry bush", 3.5);
bush.setLeafType(LeafType.SPEAR);
bush.setFruit("Blueberry");
forestNotebook.addPlant(plant);
forestNotebook.addPlant(tree);
forestNotebook.addPlant(flower);
forestNotebook.addPlant(weed);
forestNotebook.addPlant(bush);
forestNotebook.addPlant(plant);
List<Carnivore> carnivoreList = new ArrayList<>();
List<Herbivore> herbivoreList = new ArrayList<>();
List<Omnivore> omnivoreList = new ArrayList<>();
Carnivore lion = new Carnivore("Lion", 190, 1.2, 2.1);
// Geen idee over wat was de echte bedoeling van deze methode hieronder. Ik heb een willekeurige maat daarin geplaatst.
lion.setMaxFoodSize(1.5);
carnivoreList.add(lion);
forestNotebook.setCarnivores(carnivoreList);
Herbivore elephant = new Herbivore("Elephant", 6000, 3.2, 6.5);
Set<Plant> elephantDiet = new LinkedHashSet<>();
Plant plant1 = new Plant("Grasses");
Plant plant2 = new Plant("Leaves");
Plant plant3 = new Plant("Fruits");
Plant plant4 = new Plant("Roots");
elephantDiet.add(plant1);
elephantDiet.add(plant2);
elephantDiet.add(plant3);
elephant.setPlantDiet(elephantDiet);
elephant.addPlantToDiet(plant4);
herbivoreList.add(elephant);
forestNotebook.setHerbivores(herbivoreList);
Omnivore bear = new Omnivore("Bear", 500, 1.5, 2.8);
bear.setMaxFoodSize(1.5);
Set<Plant> bearDiet = new LinkedHashSet<>();
bearDiet.add(new Plant("Berries"));
bearDiet.add(plant1);
bear.setPlantDiet(bearDiet);
bear.addPlantToDiet(plant4);
omnivoreList.add(bear);
forestNotebook.setOmnivores(omnivoreList);
Animal animal1 = new Animal("Gorilla", 270, 1.8, 1.7);
Animal animal2 = new Animal("Anaconda", 250, 0.3, 8.5);
Animal animal3 = new Animal("Red fox", 14, 0.5, 0.85);
Animal animal4 = new Animal("Rabbit", 2, 0.22, 0.45);
Animal animal5 = new Animal("Wolf", 80, 0.85, 1.6);
Animal animal6 = new Animal("Eagle", 6, 0.61, 0.90);
forestNotebook.addAnimal(lion);
forestNotebook.addAnimal(elephant);
forestNotebook.addAnimal(bear);
forestNotebook.addAnimal(animal1);
forestNotebook.addAnimal(animal2);
forestNotebook.addAnimal(animal3);
forestNotebook.addAnimal(animal4);
forestNotebook.addAnimal(animal5);
forestNotebook.addAnimal(animal6);
forestNotebook.addAnimal(lion);
lineGenerator();
System.out.println("TOTAL PLANTS AND ANIMALS");
lineGenerator();
System.out.println("Plants -> " + forestNotebook.getPlantCount());
System.out.println("Animals -> " + forestNotebook.getAnimalCount());
lineGenerator();
System.out.println("UNSORTED LIST OF PLANTS AND ANIMALS");
lineGenerator();
forestNotebook.printNotebook();
lineGenerator();
System.out.println("LIST OF CARNIVORE, OMNIVORE AND HERBIVORE ANIMALS");
lineGenerator();
forestNotebook.getCarnivores().forEach(System.out::println);
forestNotebook.getOmnivores().forEach(System.out::println);
forestNotebook.getHerbivores().forEach(System.out::println);
lineGenerator();
System.out.println("LIST OF PLANTS AND ANIMALS SORTED BY NAME");
lineGenerator();
forestNotebook.sortAnimalsByName();
forestNotebook.sortPlantsByName();
forestNotebook.printNotebook();
// Ik heb alle metingen omgezet naar meters om correct te kunnen sorteren.
lineGenerator();
System.out.println("BONUS - LIST OF PLANTS AND ANIMALS SORTED BY HEIGHT");
lineGenerator();
forestNotebook.sortAnimalsByHeight();
forestNotebook.sortPlantsHeight();
forestNotebook.printNotebook();
}
public static void lineGenerator() {
System.out.println("-".repeat(100));
}
}
| Gabe-Alvess/ForestNoteBook | src/be/intecbrussel/the_notebook/app/NatureApp.java | 1,805 | // Geen idee over wat was de echte bedoeling van deze methode hieronder. Ik heb een willekeurig cijfer daarin geplaatst. | line_comment | nl | package be.intecbrussel.the_notebook.app;
import be.intecbrussel.the_notebook.entities.animal_entities.Animal;
import be.intecbrussel.the_notebook.entities.animal_entities.Carnivore;
import be.intecbrussel.the_notebook.entities.animal_entities.Herbivore;
import be.intecbrussel.the_notebook.entities.animal_entities.Omnivore;
import be.intecbrussel.the_notebook.entities.plant_entities.*;
import be.intecbrussel.the_notebook.service.ForestNotebook;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
public class NatureApp {
public static void main(String[] args) {
lineGenerator();
System.out.println("FOREST NOTEBOOK TEST");
lineGenerator();
ForestNotebook forestNotebook = new ForestNotebook();
Plant plant = new Plant("Orchid", 0.55);
Tree tree = new Tree("Pine tree", 40.5);
tree.setLeafType(LeafType.NEEDLE);
Flower flower = new Flower("Rose", 0.15);
flower.setSmell(Scent.SWEET);
Weed weed = new Weed("Dandelion", 0.05);
// Geen idee<SUF>
weed.setArea(10.5);
Bush bush = new Bush("Blueberry bush", 3.5);
bush.setLeafType(LeafType.SPEAR);
bush.setFruit("Blueberry");
forestNotebook.addPlant(plant);
forestNotebook.addPlant(tree);
forestNotebook.addPlant(flower);
forestNotebook.addPlant(weed);
forestNotebook.addPlant(bush);
forestNotebook.addPlant(plant);
List<Carnivore> carnivoreList = new ArrayList<>();
List<Herbivore> herbivoreList = new ArrayList<>();
List<Omnivore> omnivoreList = new ArrayList<>();
Carnivore lion = new Carnivore("Lion", 190, 1.2, 2.1);
// Geen idee over wat was de echte bedoeling van deze methode hieronder. Ik heb een willekeurige maat daarin geplaatst.
lion.setMaxFoodSize(1.5);
carnivoreList.add(lion);
forestNotebook.setCarnivores(carnivoreList);
Herbivore elephant = new Herbivore("Elephant", 6000, 3.2, 6.5);
Set<Plant> elephantDiet = new LinkedHashSet<>();
Plant plant1 = new Plant("Grasses");
Plant plant2 = new Plant("Leaves");
Plant plant3 = new Plant("Fruits");
Plant plant4 = new Plant("Roots");
elephantDiet.add(plant1);
elephantDiet.add(plant2);
elephantDiet.add(plant3);
elephant.setPlantDiet(elephantDiet);
elephant.addPlantToDiet(plant4);
herbivoreList.add(elephant);
forestNotebook.setHerbivores(herbivoreList);
Omnivore bear = new Omnivore("Bear", 500, 1.5, 2.8);
bear.setMaxFoodSize(1.5);
Set<Plant> bearDiet = new LinkedHashSet<>();
bearDiet.add(new Plant("Berries"));
bearDiet.add(plant1);
bear.setPlantDiet(bearDiet);
bear.addPlantToDiet(plant4);
omnivoreList.add(bear);
forestNotebook.setOmnivores(omnivoreList);
Animal animal1 = new Animal("Gorilla", 270, 1.8, 1.7);
Animal animal2 = new Animal("Anaconda", 250, 0.3, 8.5);
Animal animal3 = new Animal("Red fox", 14, 0.5, 0.85);
Animal animal4 = new Animal("Rabbit", 2, 0.22, 0.45);
Animal animal5 = new Animal("Wolf", 80, 0.85, 1.6);
Animal animal6 = new Animal("Eagle", 6, 0.61, 0.90);
forestNotebook.addAnimal(lion);
forestNotebook.addAnimal(elephant);
forestNotebook.addAnimal(bear);
forestNotebook.addAnimal(animal1);
forestNotebook.addAnimal(animal2);
forestNotebook.addAnimal(animal3);
forestNotebook.addAnimal(animal4);
forestNotebook.addAnimal(animal5);
forestNotebook.addAnimal(animal6);
forestNotebook.addAnimal(lion);
lineGenerator();
System.out.println("TOTAL PLANTS AND ANIMALS");
lineGenerator();
System.out.println("Plants -> " + forestNotebook.getPlantCount());
System.out.println("Animals -> " + forestNotebook.getAnimalCount());
lineGenerator();
System.out.println("UNSORTED LIST OF PLANTS AND ANIMALS");
lineGenerator();
forestNotebook.printNotebook();
lineGenerator();
System.out.println("LIST OF CARNIVORE, OMNIVORE AND HERBIVORE ANIMALS");
lineGenerator();
forestNotebook.getCarnivores().forEach(System.out::println);
forestNotebook.getOmnivores().forEach(System.out::println);
forestNotebook.getHerbivores().forEach(System.out::println);
lineGenerator();
System.out.println("LIST OF PLANTS AND ANIMALS SORTED BY NAME");
lineGenerator();
forestNotebook.sortAnimalsByName();
forestNotebook.sortPlantsByName();
forestNotebook.printNotebook();
// Ik heb alle metingen omgezet naar meters om correct te kunnen sorteren.
lineGenerator();
System.out.println("BONUS - LIST OF PLANTS AND ANIMALS SORTED BY HEIGHT");
lineGenerator();
forestNotebook.sortAnimalsByHeight();
forestNotebook.sortPlantsHeight();
forestNotebook.printNotebook();
}
public static void lineGenerator() {
System.out.println("-".repeat(100));
}
}
| True | 1,417 | 39 | 1,607 | 45 | 1,495 | 27 | 1,607 | 45 | 1,844 | 42 | false | false | false | false | false | true |
2,730 | 153258_7 | /* Generated by Together */
package bank.bankieren;
import java.io.*;
import java.text.*;
public class Money implements Serializable, Comparable<Money> {
private static final long serialVersionUID = 1L;
public static final String EURO = "\u20AC";
/* private Money() {
currency="undefined";
}
*/
/**
* er is een geldbedrag van munteenheid currency en waarde cents gecreeerd
*
* @param amount
* @param currency
* @throws RuntimeException
* als currency een lege string is
*/
public Money(long cents, String currency) {
if (currency.equals(""))
throw new RuntimeException("currency may not be the empty string");
this.cents=cents;
this.currency = currency;
}
/**
*
* @return de munteenheid gevolgd door een spatie en de waarde in twee
* decimalen nauwkeurig
*/
public String toString() {
return currency + " " + getValue();
}
/**
*
* @return <b>true</b> als het Money-object groter dan 0 is, anders
* <b>false</b>
*/
public boolean isPositive() {
return cents > 0;
}
public String getCurrency() {
return currency;
}
/**
*
* @return de waarde in twee decimalen nauwkeurig
*/
public String getValue() {
DecimalFormat df = new DecimalFormat("0.00");
return df.format(((double) cents) / 100);
}
public long getCents() {
return cents;
}
/**
* voorwaarde: currency van m1 en m2 moeten gelijk zijn
* @returns het verschil tussen m1 en m2
*/
public static Money difference(Money m1, Money m2) {
if (!m1.currency.equals(m2.currency))
throw new RuntimeException("munteenheden in aanroep 'difference' ongelijk, te weten: " +
m1.currency + " en " + m2.currency
);
return new Money(m1.cents-m2.cents, m1.currency);
}
/**
* voorwaarde: currency van m1 en m2 moeten gelijk zijn
* @returns de som van m1 en m2
*/
public static Money sum(Money m1, Money m2) {
if (!m1.currency.equals(m2.currency))
throw new RuntimeException("munteenheden in aanroep 'sum' ongelijk, te weten: " +
m1.currency + " en " + m2.currency
);
return new Money(m1.cents+m2.cents, m1.currency);
}
public boolean equals(Object o) {
if (!(o instanceof Money))
return false;
Money m = (Money) o;
return this.currency.equals(m.currency) && this.cents == m.cents;
}
private String currency;
private long cents;
public int compareTo(Money o) {
Money m = (Money) o;
if (!this.currency.equals(m.currency))
throw new RuntimeException("comparing amounts with different currency is not implemented");
if (this.cents==m.cents) return 0;
if (this.cents<m.cents) return -1;
else return +1;
}
}
| frankie285/Netbeans | BankierenNoObserverFX/src/bank/bankieren/Money.java | 937 | /**
* voorwaarde: currency van m1 en m2 moeten gelijk zijn
* @returns de som van m1 en m2
*/ | block_comment | nl | /* Generated by Together */
package bank.bankieren;
import java.io.*;
import java.text.*;
public class Money implements Serializable, Comparable<Money> {
private static final long serialVersionUID = 1L;
public static final String EURO = "\u20AC";
/* private Money() {
currency="undefined";
}
*/
/**
* er is een geldbedrag van munteenheid currency en waarde cents gecreeerd
*
* @param amount
* @param currency
* @throws RuntimeException
* als currency een lege string is
*/
public Money(long cents, String currency) {
if (currency.equals(""))
throw new RuntimeException("currency may not be the empty string");
this.cents=cents;
this.currency = currency;
}
/**
*
* @return de munteenheid gevolgd door een spatie en de waarde in twee
* decimalen nauwkeurig
*/
public String toString() {
return currency + " " + getValue();
}
/**
*
* @return <b>true</b> als het Money-object groter dan 0 is, anders
* <b>false</b>
*/
public boolean isPositive() {
return cents > 0;
}
public String getCurrency() {
return currency;
}
/**
*
* @return de waarde in twee decimalen nauwkeurig
*/
public String getValue() {
DecimalFormat df = new DecimalFormat("0.00");
return df.format(((double) cents) / 100);
}
public long getCents() {
return cents;
}
/**
* voorwaarde: currency van m1 en m2 moeten gelijk zijn
* @returns het verschil tussen m1 en m2
*/
public static Money difference(Money m1, Money m2) {
if (!m1.currency.equals(m2.currency))
throw new RuntimeException("munteenheden in aanroep 'difference' ongelijk, te weten: " +
m1.currency + " en " + m2.currency
);
return new Money(m1.cents-m2.cents, m1.currency);
}
/**
* voorwaarde: currency van<SUF>*/
public static Money sum(Money m1, Money m2) {
if (!m1.currency.equals(m2.currency))
throw new RuntimeException("munteenheden in aanroep 'sum' ongelijk, te weten: " +
m1.currency + " en " + m2.currency
);
return new Money(m1.cents+m2.cents, m1.currency);
}
public boolean equals(Object o) {
if (!(o instanceof Money))
return false;
Money m = (Money) o;
return this.currency.equals(m.currency) && this.cents == m.cents;
}
private String currency;
private long cents;
public int compareTo(Money o) {
Money m = (Money) o;
if (!this.currency.equals(m.currency))
throw new RuntimeException("comparing amounts with different currency is not implemented");
if (this.cents==m.cents) return 0;
if (this.cents<m.cents) return -1;
else return +1;
}
}
| True | 742 | 34 | 881 | 34 | 843 | 33 | 881 | 34 | 1,006 | 36 | false | false | false | false | false | true |
2,349 | 56075_1 | package exapus.model.forest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import com.google.common.base.Charsets;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.IBuffer;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.io.Files;
import exapus.model.visitors.IForestVisitor;
public class Member extends MemberContainer {
public Member(UqName id, Element e) {
super(id);
element = e;
references = new ArrayList<Ref>();
}
private String filePath;
private List<Ref> references;
private Element element;
public Element getElement() {
return element;
}
public Iterable<Ref> getReferences() {
return references;
}
public Iterable<Ref> getAllReferences() {
Iterable<Ref> references = getReferences();
for(Member m : getMembers()) {
references = Iterables.concat(references, m.getAllReferences());
}
return references;
}
public void addAPIReference(Ref reference) {
references.add(reference);
reference.setParent(this);
getParentFactForest().fireUpdate(reference);
}
public String toString() {
return "M[" + element.toString() + ": " + getName() + "(" + references.size() + ")" + "]";
}
public Member getTopLevelMember() {
Member parent = this;
Member oldParent = this;
while (parent instanceof Member) {
oldParent = parent;
parent = parent.getParentMember();
}
return oldParent;
}
public String getSourceString() {
try {
String path = getFilePath();
if(path == null) {
Member topLevelMember = getTopLevelMember();
path = topLevelMember.getFilePath();
}
if(path != null) {
return Files.toString(new File(path), Charsets.UTF_8);
}
return null;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean isTopLevel() {
ForestElement parent = getParent();
return !(parent instanceof Member);
}
public ICompilationUnit getCorrespondingICompilationUnit() {
IMember member = getCorrespondingIMember();
if (member != null)
return member.getCompilationUnit();
return null;
}
public IMember getCorrespondingIMember() {
//TODO: only if element = class/etc, or change to getCorrespondingMember
//en daarna getMethod, getField ..
IJavaProject project = getCorrespondingJavaProject();
if(project == null)
return null;
try {
if (element.declaresType())
return project.findType(getQName().toString(), (IProgressMonitor) null);
Member declaringMember = getParentTypeDeclaringMember();
if(declaringMember == null)
return null;
IMember declaringIMember = declaringMember.getCorrespondingIMember();
if(declaringIMember instanceof IType) {
IType declaringIType = (IType) declaringIMember;
if(element.isField())
return declaringIType.getField(this.getName().toString());
if(element.isMethod()) {
UqName uqName = getName();
String shortName = uqName.getMethodName();
String[] parameterSignatures = uqName.getMethodParameterTypeSignatures();
IMethod method = declaringIType.getMethod(shortName, parameterSignatures);
return method;
}
return null;
}
return null;
} catch (JavaModelException e) {
e.printStackTrace();
return null;
}
}
public int getSourceCharacterIndexOffset() {
IMember element = getCorrespondingIMember();
if (element == null)
return 0;
try {
return element.getSourceRange().getOffset();
} catch (JavaModelException e) {
e.printStackTrace();
return 0;
}
}
public int getSourceLineNumberOffset() {
IMember element = getCorrespondingIMember();
if (element == null)
return 0;
try {
int characterIndexOffset = element.getSourceRange().getOffset();
ICompilationUnit icu = element.getCompilationUnit();
IJavaProject ip = icu.getJavaProject();
ICompilationUnit[] icus = {icu};
//TODO: silly to reparse for this, but the usual IDocument means are unavailable (as RAP is incompatible with org.eclipse.jface.text)
return Parser.parse(ip, icus, null)[0].getLineNumber(characterIndexOffset);
} catch (JavaModelException e) {
e.printStackTrace();
return 0;
}
}
public void acceptVisitor(IForestVisitor v) {
if(v.visitMember(this)) {
for(Member m : getMembers())
m.acceptVisitor(v);
for(Ref r : getReferences())
r.acceptVisitor(v);
}
}
public ForestElement getCorrespondingForestElement(ForestElement element) {
if(element instanceof Ref) {
for(Ref ref : getReferences())
if(ref.equals(element))
return ref;
return null;
}
if(element instanceof Member) {
Member member = (Member) element;
return getMember(member);
}
return null;
}
@Override
public ForestElement getCorrespondingForestElement(boolean copyWhenMissing, ForestElement element) {
if(element instanceof Ref) {
if(copyWhenMissing) {
Ref copy = Ref.from((Ref) element);
addAPIReference(copy);
return copy;
}
else {
for(Ref ref : getReferences())
if(ref.equals(element))
return ref;
}
return null;
}
return super.getCorrespondingForestElement(copyWhenMissing, element);
}
public static Member from(Member original) {
Member member = new Member(original.getName(), original.getElement());
member.setFilePath(original.getFilePath());
member.copyTagsFrom(original);
return member;
}
@Override
public boolean hasChildren() {
return !members.isEmpty() || !references.isEmpty();
}
public boolean removeReference(Ref ref) {
return references.remove(ref);
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
| cderoove/exapus | ExapusRAP/src/exapus/model/forest/Member.java | 2,056 | //en daarna getMethod, getField .. | line_comment | nl | package exapus.model.forest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import com.google.common.base.Charsets;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.IBuffer;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.io.Files;
import exapus.model.visitors.IForestVisitor;
public class Member extends MemberContainer {
public Member(UqName id, Element e) {
super(id);
element = e;
references = new ArrayList<Ref>();
}
private String filePath;
private List<Ref> references;
private Element element;
public Element getElement() {
return element;
}
public Iterable<Ref> getReferences() {
return references;
}
public Iterable<Ref> getAllReferences() {
Iterable<Ref> references = getReferences();
for(Member m : getMembers()) {
references = Iterables.concat(references, m.getAllReferences());
}
return references;
}
public void addAPIReference(Ref reference) {
references.add(reference);
reference.setParent(this);
getParentFactForest().fireUpdate(reference);
}
public String toString() {
return "M[" + element.toString() + ": " + getName() + "(" + references.size() + ")" + "]";
}
public Member getTopLevelMember() {
Member parent = this;
Member oldParent = this;
while (parent instanceof Member) {
oldParent = parent;
parent = parent.getParentMember();
}
return oldParent;
}
public String getSourceString() {
try {
String path = getFilePath();
if(path == null) {
Member topLevelMember = getTopLevelMember();
path = topLevelMember.getFilePath();
}
if(path != null) {
return Files.toString(new File(path), Charsets.UTF_8);
}
return null;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean isTopLevel() {
ForestElement parent = getParent();
return !(parent instanceof Member);
}
public ICompilationUnit getCorrespondingICompilationUnit() {
IMember member = getCorrespondingIMember();
if (member != null)
return member.getCompilationUnit();
return null;
}
public IMember getCorrespondingIMember() {
//TODO: only if element = class/etc, or change to getCorrespondingMember
//en daarna<SUF>
IJavaProject project = getCorrespondingJavaProject();
if(project == null)
return null;
try {
if (element.declaresType())
return project.findType(getQName().toString(), (IProgressMonitor) null);
Member declaringMember = getParentTypeDeclaringMember();
if(declaringMember == null)
return null;
IMember declaringIMember = declaringMember.getCorrespondingIMember();
if(declaringIMember instanceof IType) {
IType declaringIType = (IType) declaringIMember;
if(element.isField())
return declaringIType.getField(this.getName().toString());
if(element.isMethod()) {
UqName uqName = getName();
String shortName = uqName.getMethodName();
String[] parameterSignatures = uqName.getMethodParameterTypeSignatures();
IMethod method = declaringIType.getMethod(shortName, parameterSignatures);
return method;
}
return null;
}
return null;
} catch (JavaModelException e) {
e.printStackTrace();
return null;
}
}
public int getSourceCharacterIndexOffset() {
IMember element = getCorrespondingIMember();
if (element == null)
return 0;
try {
return element.getSourceRange().getOffset();
} catch (JavaModelException e) {
e.printStackTrace();
return 0;
}
}
public int getSourceLineNumberOffset() {
IMember element = getCorrespondingIMember();
if (element == null)
return 0;
try {
int characterIndexOffset = element.getSourceRange().getOffset();
ICompilationUnit icu = element.getCompilationUnit();
IJavaProject ip = icu.getJavaProject();
ICompilationUnit[] icus = {icu};
//TODO: silly to reparse for this, but the usual IDocument means are unavailable (as RAP is incompatible with org.eclipse.jface.text)
return Parser.parse(ip, icus, null)[0].getLineNumber(characterIndexOffset);
} catch (JavaModelException e) {
e.printStackTrace();
return 0;
}
}
public void acceptVisitor(IForestVisitor v) {
if(v.visitMember(this)) {
for(Member m : getMembers())
m.acceptVisitor(v);
for(Ref r : getReferences())
r.acceptVisitor(v);
}
}
public ForestElement getCorrespondingForestElement(ForestElement element) {
if(element instanceof Ref) {
for(Ref ref : getReferences())
if(ref.equals(element))
return ref;
return null;
}
if(element instanceof Member) {
Member member = (Member) element;
return getMember(member);
}
return null;
}
@Override
public ForestElement getCorrespondingForestElement(boolean copyWhenMissing, ForestElement element) {
if(element instanceof Ref) {
if(copyWhenMissing) {
Ref copy = Ref.from((Ref) element);
addAPIReference(copy);
return copy;
}
else {
for(Ref ref : getReferences())
if(ref.equals(element))
return ref;
}
return null;
}
return super.getCorrespondingForestElement(copyWhenMissing, element);
}
public static Member from(Member original) {
Member member = new Member(original.getName(), original.getElement());
member.setFilePath(original.getFilePath());
member.copyTagsFrom(original);
return member;
}
@Override
public boolean hasChildren() {
return !members.isEmpty() || !references.isEmpty();
}
public boolean removeReference(Ref ref) {
return references.remove(ref);
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
| True | 1,515 | 9 | 1,852 | 9 | 1,864 | 8 | 1,853 | 10 | 2,280 | 10 | false | false | false | false | false | true |
2,451 | 190006_1 | package main.java.be.ipeters.ottoz.cpbelcar.services;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import main.java.be.ipeters.ottoz.cpbelcar.domain.Order;
import main.java.be.ipeters.ottoz.cpbelcar.domain.Orderline;
import main.java.be.ipeters.ottoz.cpbelcar.mappers.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class OrderService implements CrudService<Order, Integer>{
@Autowired
private OrderMapper orderMapper;
@Autowired
private OrderlineService orderlineService;
private Orderline orderline;
public int prefabOrderId;
@Override
public void save(Order entity) {
/*
* maak een voorlopig order hou de id bij
*
*/
orderMapper.insert(entity);
//postman, zet input van order met orderlien klaar
}
public void save2(Order entity) {
/*
* maak een voorlopig order hou de id bij
* maak orderlijnen en vul hier bovenstaande id in als orderId
* Op het einde een update doen van het order
*
*/
// create prefab order
prefabOrderId=prefabOrderCreation().getId();
// oproep create orderline
orderlineService.save(orderline);
// oproep validate
orderMapper.insert(entity);
//postman, zet input van order met orderlien klaar
}
@Override
public Order findById(Integer key) {
return orderMapper.findById(key);
}
@Override
public List<Order> findAll() {
return orderMapper.findAll();
}
@Override
public void deleteById(Integer key) {
orderMapper.deleteById(key);
}
@Override
public void update(Order entity) {
orderMapper.update(entity);
}
private void orderValidation(Order order) {
// check minstens 1 orderline
}
private Order prefabOrderCreation() {
Order prefab = new Order(); //(1, "prefab", 1, LocalDate.now(), LocalDate.now(),
//1, 2, 3, "dummy", 5.0);
prefab.setTypeOrder("prefab");
prefab.setOrderDate(LocalDateTime.now());
prefab.setDeliveryDate(LocalDate.now());
prefab.setCustomerId(1);
prefab.setSupplierId(2);
prefab.setEmployeeId(3);
prefab.setStatus("dummy");
prefab.setPercentage(0);
return prefab;
}
}
| cpjjpeters/BelcarFX | src/main/java/be/ipeters/ottoz/cpbelcar/services/OrderService.java | 748 | //postman, zet input van order met orderlien klaar | line_comment | nl | package main.java.be.ipeters.ottoz.cpbelcar.services;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import main.java.be.ipeters.ottoz.cpbelcar.domain.Order;
import main.java.be.ipeters.ottoz.cpbelcar.domain.Orderline;
import main.java.be.ipeters.ottoz.cpbelcar.mappers.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class OrderService implements CrudService<Order, Integer>{
@Autowired
private OrderMapper orderMapper;
@Autowired
private OrderlineService orderlineService;
private Orderline orderline;
public int prefabOrderId;
@Override
public void save(Order entity) {
/*
* maak een voorlopig order hou de id bij
*
*/
orderMapper.insert(entity);
//postman, zet<SUF>
}
public void save2(Order entity) {
/*
* maak een voorlopig order hou de id bij
* maak orderlijnen en vul hier bovenstaande id in als orderId
* Op het einde een update doen van het order
*
*/
// create prefab order
prefabOrderId=prefabOrderCreation().getId();
// oproep create orderline
orderlineService.save(orderline);
// oproep validate
orderMapper.insert(entity);
//postman, zet input van order met orderlien klaar
}
@Override
public Order findById(Integer key) {
return orderMapper.findById(key);
}
@Override
public List<Order> findAll() {
return orderMapper.findAll();
}
@Override
public void deleteById(Integer key) {
orderMapper.deleteById(key);
}
@Override
public void update(Order entity) {
orderMapper.update(entity);
}
private void orderValidation(Order order) {
// check minstens 1 orderline
}
private Order prefabOrderCreation() {
Order prefab = new Order(); //(1, "prefab", 1, LocalDate.now(), LocalDate.now(),
//1, 2, 3, "dummy", 5.0);
prefab.setTypeOrder("prefab");
prefab.setOrderDate(LocalDateTime.now());
prefab.setDeliveryDate(LocalDate.now());
prefab.setCustomerId(1);
prefab.setSupplierId(2);
prefab.setEmployeeId(3);
prefab.setStatus("dummy");
prefab.setPercentage(0);
return prefab;
}
}
| True | 562 | 14 | 692 | 15 | 670 | 12 | 692 | 15 | 804 | 16 | false | false | false | false | false | true |