file_id
stringlengths 5
10
| content
stringlengths 110
36.3k
| repo
stringlengths 7
108
| path
stringlengths 8
198
| token_length
int64 37
8.19k
| original_comment
stringlengths 11
5.72k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | prompt
stringlengths 62
36.3k
|
---|---|---|---|---|---|---|---|---|
1818_1 | //==============================================================================
// This file is part of Master Password.
// Copyright (c) 2011-2017, Maarten Billemont.
//
// Master Password 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.
//
// Master Password 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 can find a copy of the GNU General Public License in the
// LICENSE file. Alternatively, see <http://www.gnu.org/licenses/>.
//==============================================================================
package com.lyndir.masterpassword;
import android.os.Handler;
import android.os.Looper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import java.util.List;
import java.util.Set;
import java.util.concurrent.*;
import javax.annotation.Nonnull;
/**
* @author lhunath, 2015-12-22
*/
public class MainThreadExecutor extends AbstractExecutorService {
private final Handler mHandler = new Handler( Looper.getMainLooper() );
private final Set<Runnable> commands = Sets.newLinkedHashSet();
private boolean shutdown;
@Override
public void execute(final Runnable command) {
if (shutdown)
throw new RejectedExecutionException( "This executor has been shut down" );
synchronized (commands) {
commands.add( command );
mHandler.post( new Runnable() {
@Override
public void run() {
synchronized (commands) {
if (!commands.remove( command ))
// Command was removed, not executing.
return;
}
command.run();
}
} );
}
}
@Override
public void shutdown() {
shutdown = true;
}
@Nonnull
@Override
public List<Runnable> shutdownNow() {
shutdown = true;
mHandler.removeCallbacksAndMessages( null );
synchronized (commands) {
ImmutableList<Runnable> pendingTasks = ImmutableList.copyOf( commands );
commands.clear();
commands.notifyAll();
return pendingTasks;
}
}
@Override
public boolean isShutdown() {
return shutdown;
}
@Override
public boolean isTerminated() {
synchronized (commands) {
return shutdown && commands.isEmpty();
}
}
@Override
public boolean awaitTermination(final long timeout, final TimeUnit unit)
throws InterruptedException {
if (isTerminated())
return true;
commands.wait( unit.toMillis( timeout ) );
return isTerminated();
}
}
| Lyndir/MasterPassword | platform-android/src/main/java/com/lyndir/masterpassword/MainThreadExecutor.java | 810 | // Copyright (c) 2011-2017, Maarten Billemont. | line_comment | nl | //==============================================================================
// This file is part of Master Password.
// Copyright (c)<SUF>
//
// Master Password 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.
//
// Master Password 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 can find a copy of the GNU General Public License in the
// LICENSE file. Alternatively, see <http://www.gnu.org/licenses/>.
//==============================================================================
package com.lyndir.masterpassword;
import android.os.Handler;
import android.os.Looper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import java.util.List;
import java.util.Set;
import java.util.concurrent.*;
import javax.annotation.Nonnull;
/**
* @author lhunath, 2015-12-22
*/
public class MainThreadExecutor extends AbstractExecutorService {
private final Handler mHandler = new Handler( Looper.getMainLooper() );
private final Set<Runnable> commands = Sets.newLinkedHashSet();
private boolean shutdown;
@Override
public void execute(final Runnable command) {
if (shutdown)
throw new RejectedExecutionException( "This executor has been shut down" );
synchronized (commands) {
commands.add( command );
mHandler.post( new Runnable() {
@Override
public void run() {
synchronized (commands) {
if (!commands.remove( command ))
// Command was removed, not executing.
return;
}
command.run();
}
} );
}
}
@Override
public void shutdown() {
shutdown = true;
}
@Nonnull
@Override
public List<Runnable> shutdownNow() {
shutdown = true;
mHandler.removeCallbacksAndMessages( null );
synchronized (commands) {
ImmutableList<Runnable> pendingTasks = ImmutableList.copyOf( commands );
commands.clear();
commands.notifyAll();
return pendingTasks;
}
}
@Override
public boolean isShutdown() {
return shutdown;
}
@Override
public boolean isTerminated() {
synchronized (commands) {
return shutdown && commands.isEmpty();
}
}
@Override
public boolean awaitTermination(final long timeout, final TimeUnit unit)
throws InterruptedException {
if (isTerminated())
return true;
commands.wait( unit.toMillis( timeout ) );
return isTerminated();
}
}
|
37256_4 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template
*/
package javaapplicationcalculator;
import java.awt.SystemColor;
import java.util.Scanner;
import java.text.NumberFormat;
import java.util.Locale;
/**
*
* @author mig
*/
public class JavaApplicationCalculator {
//Notas :Double.parseDouble(scanner.next().trim());
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Aantal geld wat jy wil bele ? : ");
double geld = Double.parseDouble(scanner.next().trim());
System.out.print("% Maandelikse Rente? : ");
double rente = Double.parseDouble(scanner.next().trim());
rente = rente/100;
rente = rente/12;
System.out.print("Vir hoeveel jaar wil jy bele? : ");
double aantalBetalings = Double.parseDouble(scanner.next().trim());
aantalBetalings = aantalBetalings*12;
double totaalMaandelikseRente = geld *(rente * Math.pow(1 + rente , aantalBetalings))
/(Math.pow(1+ rente, aantalBetalings)-1);
//NumberFormat maandeliksePaaiementFormatted = NumberFormat.getCurrencyInstance();
System.out.println("");
System.out.println("Jou maandelikse paaiement is R"+ (totaalMaandelikseRente));
System.out.println("");
System.out.println("Die geld inbetaal is: " + geld); //{Toets of my variables reg uitwerk
System.out.println("Die rente op jou geld is: " + rente);
System.out.println("Die aantal keer wat jy moet betaal is: " + aantalBetalings);
// System.out.println();
}
}
| M1gael/Learn-Java | JavaApplicationCalculator.java | 620 | //{Toets of my variables reg uitwerk | line_comment | nl | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template
*/
package javaapplicationcalculator;
import java.awt.SystemColor;
import java.util.Scanner;
import java.text.NumberFormat;
import java.util.Locale;
/**
*
* @author mig
*/
public class JavaApplicationCalculator {
//Notas :Double.parseDouble(scanner.next().trim());
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Aantal geld wat jy wil bele ? : ");
double geld = Double.parseDouble(scanner.next().trim());
System.out.print("% Maandelikse Rente? : ");
double rente = Double.parseDouble(scanner.next().trim());
rente = rente/100;
rente = rente/12;
System.out.print("Vir hoeveel jaar wil jy bele? : ");
double aantalBetalings = Double.parseDouble(scanner.next().trim());
aantalBetalings = aantalBetalings*12;
double totaalMaandelikseRente = geld *(rente * Math.pow(1 + rente , aantalBetalings))
/(Math.pow(1+ rente, aantalBetalings)-1);
//NumberFormat maandeliksePaaiementFormatted = NumberFormat.getCurrencyInstance();
System.out.println("");
System.out.println("Jou maandelikse paaiement is R"+ (totaalMaandelikseRente));
System.out.println("");
System.out.println("Die geld inbetaal is: " + geld); //{Toets of<SUF>
System.out.println("Die rente op jou geld is: " + rente);
System.out.println("Die aantal keer wat jy moet betaal is: " + aantalBetalings);
// System.out.println();
}
}
|
202581_32 | /*
* Copyright (c) 2015, 2019 Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2018 Jason Mehrens. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package com.sun.mail.util.logging;
import static com.sun.mail.util.logging.LogManagerProperties.fromLogManager;
import java.util.logging.*;
/**
* A filter used to limit log records based on a maximum generation rate.
*
* The duration specified is used to compute the record rate and the amount of
* time the filter will reject records once the rate has been exceeded. Once the
* rate is exceeded records are not allowed until the duration has elapsed.
*
* <p>
* By default each {@code DurationFilter} is initialized using the following
* LogManager configuration properties where {@code <filter-name>} refers to the
* fully qualified class name of the handler. If properties are not defined, or
* contain invalid values, then the specified default values are used.
*
* <ul>
* <li>{@literal <filter-name>}.records the max number of records per duration.
* A numeric long integer or a multiplication expression can be used as the
* value. (defaults to {@code 1000})
*
* <li>{@literal <filter-name>}.duration the number of milliseconds to suppress
* log records from being published. This is also used as duration to determine
* the log record rate. A numeric long integer or a multiplication expression
* can be used as the value. If the {@code java.time} package is available then
* an ISO-8601 duration format of {@code PnDTnHnMn.nS} can be used as the value.
* The suffixes of "D", "H", "M" and "S" are for days, hours, minutes and
* seconds. The suffixes must occur in order. The seconds can be specified with
* a fractional component to declare milliseconds. (defaults to {@code PT15M})
* </ul>
*
* <p>
* For example, the settings to limit {@code MailHandler} with a default
* capacity to only send a maximum of two email messages every six minutes would
* be as follows:
* <pre>
* {@code
* com.sun.mail.util.logging.MailHandler.filter = com.sun.mail.util.logging.DurationFilter
* com.sun.mail.util.logging.MailHandler.capacity = 1000
* com.sun.mail.util.logging.DurationFilter.records = 2L * 1000L
* com.sun.mail.util.logging.DurationFilter.duration = PT6M
* }
* </pre>
*
*
* @author Jason Mehrens
* @since JavaMail 1.5.5
*/
public class DurationFilter implements Filter {
/**
* The number of expected records per duration.
*/
private final long records;
/**
* The duration in milliseconds used to determine the rate. The duration is
* also used as the amount of time that the filter will not allow records
* when saturated.
*/
private final long duration;
/**
* The number of records seen for the current duration. This value negative
* if saturated. Zero is considered saturated but is reserved for recording
* the first duration.
*/
private long count;
/**
* The most recent record time seen for the current duration.
*/
private long peak;
/**
* The start time for the current duration.
*/
private long start;
/**
* Creates the filter using the default properties.
*/
public DurationFilter() {
this.records = checkRecords(initLong(".records"));
this.duration = checkDuration(initLong(".duration"));
}
/**
* Creates the filter using the given properties. Default values are used if
* any of the given values are outside the allowed range.
*
* @param records the number of records per duration.
* @param duration the number of milliseconds to suppress log records from
* being published.
*/
public DurationFilter(final long records, final long duration) {
this.records = checkRecords(records);
this.duration = checkDuration(duration);
}
/**
* Determines if this filter is equal to another filter.
*
* @param obj the given object.
* @return true if equal otherwise false.
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) { //Avoid locks and deal with rapid state changes.
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final DurationFilter other = (DurationFilter) obj;
if (this.records != other.records) {
return false;
}
if (this.duration != other.duration) {
return false;
}
final long c;
final long p;
final long s;
synchronized (this) {
c = this.count;
p = this.peak;
s = this.start;
}
synchronized (other) {
if (c != other.count || p != other.peak || s != other.start) {
return false;
}
}
return true;
}
/**
* Determines if this filter is able to accept the maximum number of log
* records for this instant in time. The result is a best-effort estimate
* and should be considered out of date as soon as it is produced. This
* method is designed for use in monitoring the state of this filter.
*
* @return true if the filter is idle; false otherwise.
*/
public boolean isIdle() {
return test(0L, System.currentTimeMillis());
}
/**
* Returns a hash code value for this filter.
*
* @return hash code for this filter.
*/
@Override
public int hashCode() {
int hash = 3;
hash = 89 * hash + (int) (this.records ^ (this.records >>> 32));
hash = 89 * hash + (int) (this.duration ^ (this.duration >>> 32));
return hash;
}
/**
* Check if the given log record should be published. This method will
* modify the internal state of this filter.
*
* @param record the log record to check.
* @return true if allowed; false otherwise.
* @throws NullPointerException if given record is null.
*/
@SuppressWarnings("override") //JDK-6954234
public boolean isLoggable(final LogRecord record) {
return accept(record.getMillis());
}
/**
* Determines if this filter will accept log records for this instant in
* time. The result is a best-effort estimate and should be considered out
* of date as soon as it is produced. This method is designed for use in
* monitoring the state of this filter.
*
* @return true if the filter is not saturated; false otherwise.
*/
public boolean isLoggable() {
return test(records, System.currentTimeMillis());
}
/**
* Returns a string representation of this filter. The result is a
* best-effort estimate and should be considered out of date as soon as it
* is produced.
*
* @return a string representation of this filter.
*/
@Override
public String toString() {
boolean idle;
boolean loggable;
synchronized (this) {
final long millis = System.currentTimeMillis();
idle = test(0L, millis);
loggable = test(records, millis);
}
return getClass().getName() + "{records=" + records
+ ", duration=" + duration
+ ", idle=" + idle
+ ", loggable=" + loggable + '}';
}
/**
* Creates a copy of this filter that retains the filter settings but does
* not include the current filter state. The newly create clone acts as if
* it has never seen any records.
*
* @return a copy of this filter.
* @throws CloneNotSupportedException if this filter is not allowed to be
* cloned.
*/
@Override
protected DurationFilter clone() throws CloneNotSupportedException {
final DurationFilter clone = (DurationFilter) super.clone();
clone.count = 0L; //Reset the filter state.
clone.peak = 0L;
clone.start = 0L;
return clone;
}
/**
* Checks if this filter is not saturated or bellow a maximum rate.
*
* @param limit the number of records allowed to be under the rate.
* @param millis the current time in milliseconds.
* @return true if not saturated or bellow the rate.
*/
private boolean test(final long limit, final long millis) {
assert limit >= 0L : limit;
final long c;
final long s;
synchronized (this) {
c = count;
s = start;
}
if (c > 0L) { //If not saturated.
if ((millis - s) >= duration || c < limit) {
return true;
}
} else { //Subtraction is used to deal with numeric overflow.
if ((millis - s) >= 0L || c == 0L) {
return true;
}
}
return false;
}
/**
* Determines if the record is loggable by time.
*
* @param millis the log record milliseconds.
* @return true if accepted false otherwise.
*/
private synchronized boolean accept(final long millis) {
//Subtraction is used to deal with numeric overflow of millis.
boolean allow;
if (count > 0L) { //If not saturated.
if ((millis - peak) > 0L) {
peak = millis; //Record the new peak.
}
//Under the rate if the count has not been reached.
if (count != records) {
++count;
allow = true;
} else {
if ((peak - start) >= duration) {
count = 1L; //Start a new duration.
start = peak;
allow = true;
} else {
count = -1L; //Saturate for the duration.
start = peak + duration;
allow = false;
}
}
} else {
//If the saturation period has expired or this is the first record
//then start a new duration and allow records.
if ((millis - start) >= 0L || count == 0L) {
count = 1L;
start = millis;
peak = millis;
allow = true;
} else {
allow = false; //Remain in a saturated state.
}
}
return allow;
}
/**
* Reads a long value or multiplication expression from the LogManager. If
* the value can not be parsed or is not defined then Long.MIN_VALUE is
* returned.
*
* @param suffix a dot character followed by the key name.
* @return a long value or Long.MIN_VALUE if unable to parse or undefined.
* @throws NullPointerException if suffix is null.
*/
private long initLong(final String suffix) {
long result = 0L;
final String p = getClass().getName();
String value = fromLogManager(p.concat(suffix));
if (value != null && value.length() != 0) {
value = value.trim();
if (isTimeEntry(suffix, value)) {
try {
result = LogManagerProperties.parseDurationToMillis(value);
} catch (final RuntimeException ignore) {
} catch (final Exception ignore) {
} catch (final LinkageError ignore) {
}
}
if (result == 0L) { //Zero is invalid.
try {
result = 1L;
for (String s : tokenizeLongs(value)) {
if (s.endsWith("L") || s.endsWith("l")) {
s = s.substring(0, s.length() - 1);
}
result = multiplyExact(result, Long.parseLong(s));
}
} catch (final RuntimeException ignore) {
result = Long.MIN_VALUE;
}
}
} else {
result = Long.MIN_VALUE;
}
return result;
}
/**
* Determines if the given suffix can be a time unit and the value is
* encoded as an ISO ISO-8601 duration format.
*
* @param suffix the suffix property.
* @param value the value of the property.
* @return true if the entry is a time entry.
* @throws IndexOutOfBoundsException if value is empty.
* @throws NullPointerException if either argument is null.
*/
private boolean isTimeEntry(final String suffix, final String value) {
return (value.charAt(0) == 'P' || value.charAt(0) == 'p')
&& suffix.equals(".duration");
}
/**
* Parse any long value or multiplication expressions into tokens.
*
* @param value the expression or value.
* @return an array of long tokens, never empty.
* @throws NullPointerException if the given value is null.
* @throws NumberFormatException if the expression is invalid.
*/
private static String[] tokenizeLongs(final String value) {
String[] e;
final int i = value.indexOf('*');
if (i > -1 && (e = value.split("\\s*\\*\\s*")).length != 0) {
if (i == 0 || value.charAt(value.length() - 1) == '*') {
throw new NumberFormatException(value);
}
if (e.length == 1) {
throw new NumberFormatException(e[0]);
}
} else {
e = new String[]{value};
}
return e;
}
/**
* Multiply and check for overflow. This can be replaced with
* {@code java.lang.Math.multiplyExact} when Jakarta Mail requires JDK 8.
*
* @param x the first value.
* @param y the second value.
* @return x times y.
* @throws ArithmeticException if overflow is detected.
*/
private static long multiplyExact(final long x, final long y) {
long r = x * y;
if (((Math.abs(x) | Math.abs(y)) >>> 31L != 0L)) {
if (((y != 0L) && (r / y != x))
|| (x == Long.MIN_VALUE && y == -1L)) {
throw new ArithmeticException();
}
}
return r;
}
/**
* Converts record count to a valid record count. If the value is out of
* bounds then the default record count is used.
*
* @param records the record count.
* @return a valid number of record count.
*/
private static long checkRecords(final long records) {
return records > 0L ? records : 1000L;
}
/**
* Converts the duration to a valid duration. If the value is out of bounds
* then the default duration is used.
*
* @param duration the duration to check.
* @return a valid duration.
*/
private static long checkDuration(final long duration) {
return duration > 0L ? duration : 15L * 60L * 1000L;
}
}
| M66B/FairEmail | app/src/main/java/com/sun/mail/util/logging/DurationFilter.java | 4,390 | //Zero is invalid.
| line_comment | nl | /*
* Copyright (c) 2015, 2019 Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2018 Jason Mehrens. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package com.sun.mail.util.logging;
import static com.sun.mail.util.logging.LogManagerProperties.fromLogManager;
import java.util.logging.*;
/**
* A filter used to limit log records based on a maximum generation rate.
*
* The duration specified is used to compute the record rate and the amount of
* time the filter will reject records once the rate has been exceeded. Once the
* rate is exceeded records are not allowed until the duration has elapsed.
*
* <p>
* By default each {@code DurationFilter} is initialized using the following
* LogManager configuration properties where {@code <filter-name>} refers to the
* fully qualified class name of the handler. If properties are not defined, or
* contain invalid values, then the specified default values are used.
*
* <ul>
* <li>{@literal <filter-name>}.records the max number of records per duration.
* A numeric long integer or a multiplication expression can be used as the
* value. (defaults to {@code 1000})
*
* <li>{@literal <filter-name>}.duration the number of milliseconds to suppress
* log records from being published. This is also used as duration to determine
* the log record rate. A numeric long integer or a multiplication expression
* can be used as the value. If the {@code java.time} package is available then
* an ISO-8601 duration format of {@code PnDTnHnMn.nS} can be used as the value.
* The suffixes of "D", "H", "M" and "S" are for days, hours, minutes and
* seconds. The suffixes must occur in order. The seconds can be specified with
* a fractional component to declare milliseconds. (defaults to {@code PT15M})
* </ul>
*
* <p>
* For example, the settings to limit {@code MailHandler} with a default
* capacity to only send a maximum of two email messages every six minutes would
* be as follows:
* <pre>
* {@code
* com.sun.mail.util.logging.MailHandler.filter = com.sun.mail.util.logging.DurationFilter
* com.sun.mail.util.logging.MailHandler.capacity = 1000
* com.sun.mail.util.logging.DurationFilter.records = 2L * 1000L
* com.sun.mail.util.logging.DurationFilter.duration = PT6M
* }
* </pre>
*
*
* @author Jason Mehrens
* @since JavaMail 1.5.5
*/
public class DurationFilter implements Filter {
/**
* The number of expected records per duration.
*/
private final long records;
/**
* The duration in milliseconds used to determine the rate. The duration is
* also used as the amount of time that the filter will not allow records
* when saturated.
*/
private final long duration;
/**
* The number of records seen for the current duration. This value negative
* if saturated. Zero is considered saturated but is reserved for recording
* the first duration.
*/
private long count;
/**
* The most recent record time seen for the current duration.
*/
private long peak;
/**
* The start time for the current duration.
*/
private long start;
/**
* Creates the filter using the default properties.
*/
public DurationFilter() {
this.records = checkRecords(initLong(".records"));
this.duration = checkDuration(initLong(".duration"));
}
/**
* Creates the filter using the given properties. Default values are used if
* any of the given values are outside the allowed range.
*
* @param records the number of records per duration.
* @param duration the number of milliseconds to suppress log records from
* being published.
*/
public DurationFilter(final long records, final long duration) {
this.records = checkRecords(records);
this.duration = checkDuration(duration);
}
/**
* Determines if this filter is equal to another filter.
*
* @param obj the given object.
* @return true if equal otherwise false.
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) { //Avoid locks and deal with rapid state changes.
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final DurationFilter other = (DurationFilter) obj;
if (this.records != other.records) {
return false;
}
if (this.duration != other.duration) {
return false;
}
final long c;
final long p;
final long s;
synchronized (this) {
c = this.count;
p = this.peak;
s = this.start;
}
synchronized (other) {
if (c != other.count || p != other.peak || s != other.start) {
return false;
}
}
return true;
}
/**
* Determines if this filter is able to accept the maximum number of log
* records for this instant in time. The result is a best-effort estimate
* and should be considered out of date as soon as it is produced. This
* method is designed for use in monitoring the state of this filter.
*
* @return true if the filter is idle; false otherwise.
*/
public boolean isIdle() {
return test(0L, System.currentTimeMillis());
}
/**
* Returns a hash code value for this filter.
*
* @return hash code for this filter.
*/
@Override
public int hashCode() {
int hash = 3;
hash = 89 * hash + (int) (this.records ^ (this.records >>> 32));
hash = 89 * hash + (int) (this.duration ^ (this.duration >>> 32));
return hash;
}
/**
* Check if the given log record should be published. This method will
* modify the internal state of this filter.
*
* @param record the log record to check.
* @return true if allowed; false otherwise.
* @throws NullPointerException if given record is null.
*/
@SuppressWarnings("override") //JDK-6954234
public boolean isLoggable(final LogRecord record) {
return accept(record.getMillis());
}
/**
* Determines if this filter will accept log records for this instant in
* time. The result is a best-effort estimate and should be considered out
* of date as soon as it is produced. This method is designed for use in
* monitoring the state of this filter.
*
* @return true if the filter is not saturated; false otherwise.
*/
public boolean isLoggable() {
return test(records, System.currentTimeMillis());
}
/**
* Returns a string representation of this filter. The result is a
* best-effort estimate and should be considered out of date as soon as it
* is produced.
*
* @return a string representation of this filter.
*/
@Override
public String toString() {
boolean idle;
boolean loggable;
synchronized (this) {
final long millis = System.currentTimeMillis();
idle = test(0L, millis);
loggable = test(records, millis);
}
return getClass().getName() + "{records=" + records
+ ", duration=" + duration
+ ", idle=" + idle
+ ", loggable=" + loggable + '}';
}
/**
* Creates a copy of this filter that retains the filter settings but does
* not include the current filter state. The newly create clone acts as if
* it has never seen any records.
*
* @return a copy of this filter.
* @throws CloneNotSupportedException if this filter is not allowed to be
* cloned.
*/
@Override
protected DurationFilter clone() throws CloneNotSupportedException {
final DurationFilter clone = (DurationFilter) super.clone();
clone.count = 0L; //Reset the filter state.
clone.peak = 0L;
clone.start = 0L;
return clone;
}
/**
* Checks if this filter is not saturated or bellow a maximum rate.
*
* @param limit the number of records allowed to be under the rate.
* @param millis the current time in milliseconds.
* @return true if not saturated or bellow the rate.
*/
private boolean test(final long limit, final long millis) {
assert limit >= 0L : limit;
final long c;
final long s;
synchronized (this) {
c = count;
s = start;
}
if (c > 0L) { //If not saturated.
if ((millis - s) >= duration || c < limit) {
return true;
}
} else { //Subtraction is used to deal with numeric overflow.
if ((millis - s) >= 0L || c == 0L) {
return true;
}
}
return false;
}
/**
* Determines if the record is loggable by time.
*
* @param millis the log record milliseconds.
* @return true if accepted false otherwise.
*/
private synchronized boolean accept(final long millis) {
//Subtraction is used to deal with numeric overflow of millis.
boolean allow;
if (count > 0L) { //If not saturated.
if ((millis - peak) > 0L) {
peak = millis; //Record the new peak.
}
//Under the rate if the count has not been reached.
if (count != records) {
++count;
allow = true;
} else {
if ((peak - start) >= duration) {
count = 1L; //Start a new duration.
start = peak;
allow = true;
} else {
count = -1L; //Saturate for the duration.
start = peak + duration;
allow = false;
}
}
} else {
//If the saturation period has expired or this is the first record
//then start a new duration and allow records.
if ((millis - start) >= 0L || count == 0L) {
count = 1L;
start = millis;
peak = millis;
allow = true;
} else {
allow = false; //Remain in a saturated state.
}
}
return allow;
}
/**
* Reads a long value or multiplication expression from the LogManager. If
* the value can not be parsed or is not defined then Long.MIN_VALUE is
* returned.
*
* @param suffix a dot character followed by the key name.
* @return a long value or Long.MIN_VALUE if unable to parse or undefined.
* @throws NullPointerException if suffix is null.
*/
private long initLong(final String suffix) {
long result = 0L;
final String p = getClass().getName();
String value = fromLogManager(p.concat(suffix));
if (value != null && value.length() != 0) {
value = value.trim();
if (isTimeEntry(suffix, value)) {
try {
result = LogManagerProperties.parseDurationToMillis(value);
} catch (final RuntimeException ignore) {
} catch (final Exception ignore) {
} catch (final LinkageError ignore) {
}
}
if (result == 0L) { //Zero is<SUF>
try {
result = 1L;
for (String s : tokenizeLongs(value)) {
if (s.endsWith("L") || s.endsWith("l")) {
s = s.substring(0, s.length() - 1);
}
result = multiplyExact(result, Long.parseLong(s));
}
} catch (final RuntimeException ignore) {
result = Long.MIN_VALUE;
}
}
} else {
result = Long.MIN_VALUE;
}
return result;
}
/**
* Determines if the given suffix can be a time unit and the value is
* encoded as an ISO ISO-8601 duration format.
*
* @param suffix the suffix property.
* @param value the value of the property.
* @return true if the entry is a time entry.
* @throws IndexOutOfBoundsException if value is empty.
* @throws NullPointerException if either argument is null.
*/
private boolean isTimeEntry(final String suffix, final String value) {
return (value.charAt(0) == 'P' || value.charAt(0) == 'p')
&& suffix.equals(".duration");
}
/**
* Parse any long value or multiplication expressions into tokens.
*
* @param value the expression or value.
* @return an array of long tokens, never empty.
* @throws NullPointerException if the given value is null.
* @throws NumberFormatException if the expression is invalid.
*/
private static String[] tokenizeLongs(final String value) {
String[] e;
final int i = value.indexOf('*');
if (i > -1 && (e = value.split("\\s*\\*\\s*")).length != 0) {
if (i == 0 || value.charAt(value.length() - 1) == '*') {
throw new NumberFormatException(value);
}
if (e.length == 1) {
throw new NumberFormatException(e[0]);
}
} else {
e = new String[]{value};
}
return e;
}
/**
* Multiply and check for overflow. This can be replaced with
* {@code java.lang.Math.multiplyExact} when Jakarta Mail requires JDK 8.
*
* @param x the first value.
* @param y the second value.
* @return x times y.
* @throws ArithmeticException if overflow is detected.
*/
private static long multiplyExact(final long x, final long y) {
long r = x * y;
if (((Math.abs(x) | Math.abs(y)) >>> 31L != 0L)) {
if (((y != 0L) && (r / y != x))
|| (x == Long.MIN_VALUE && y == -1L)) {
throw new ArithmeticException();
}
}
return r;
}
/**
* Converts record count to a valid record count. If the value is out of
* bounds then the default record count is used.
*
* @param records the record count.
* @return a valid number of record count.
*/
private static long checkRecords(final long records) {
return records > 0L ? records : 1000L;
}
/**
* Converts the duration to a valid duration. If the value is out of bounds
* then the default duration is used.
*
* @param duration the duration to check.
* @return a valid duration.
*/
private static long checkDuration(final long duration) {
return duration > 0L ? duration : 15L * 60L * 1000L;
}
}
|
15396_4 | package ooad.parola.classes;
import java.util.ArrayList;
public class Speler {
private String gebruikersnaam;
private String wachtwoord;
private int saldo;
// dit is voor het spelen van quiz, wanneer een quiz is afgelopen wordt dit allemaal op null gezet
private Quiz quiz = null;
private int huidigeVraag = -1;
private Score score = null;
private int juisteAntwoorden = 0;
private char[] letters = new char[8];
public Speler(String gebruikersnaam, String wachtwoord) {
this.gebruikersnaam = gebruikersnaam;
this.wachtwoord = wachtwoord;
this.saldo = 1000;
}
public void geefAntwoord(String antwoord) {
if (huidigeVraag < quiz.getVragen().length){
Antwoord gegevenAntwoord = new Antwoord(antwoord);
// System.out.println(antwoord);
if (quiz.getVragen()[huidigeVraag - 1].controleerAntwoord(gegevenAntwoord)) {
letters[juisteAntwoorden] = quiz.getVragen()[huidigeVraag - 1].getLetter();
// System.out.println(letters[juisteAntwoorden]);
juisteAntwoorden++;
}
} else {
score = new Score(antwoord, juisteAntwoorden, 100 /* dit is een magic number, heb geen zin een timer te implementeren */);
System.out.println("je score is: " + score.berekenScore());
}
// return "";
}
public void speelQuiz() {
// System.out.println("spelen quiz"); // test code TODO: remove
// get quiz
if (huidigeVraag == -1) {
quiz = new Data().getQuiz();
score = new Score(wachtwoord, saldo, huidigeVraag);
huidigeVraag++;
} else if (huidigeVraag == quiz.getVragen().length) {
// bereken punten
System.out.println("Maak een woord met de volgende letters: ");
for (int i = 0; i < juisteAntwoorden; i++) {
System.out.print(" - " + letters[i]);
}
System.out.println();
// sluit
} else {
// System.out.println(huidigeVraag + " / " + quiz.getVragen().length);
// toon vraag
System.out.println(quiz.getVragen()[huidigeVraag]);
huidigeVraag++;
}
}
public void kopenCredits(int aantal, Speler speler) {
// wordt niet geimplementeerd omdat het niet essentieel is voor het spelen van een quiz
}
}
| MAGerritsen/Parola | parola/src/main/java/ooad/parola/classes/Speler.java | 740 | // wordt niet geimplementeerd omdat het niet essentieel is voor het spelen van een quiz | line_comment | nl | package ooad.parola.classes;
import java.util.ArrayList;
public class Speler {
private String gebruikersnaam;
private String wachtwoord;
private int saldo;
// dit is voor het spelen van quiz, wanneer een quiz is afgelopen wordt dit allemaal op null gezet
private Quiz quiz = null;
private int huidigeVraag = -1;
private Score score = null;
private int juisteAntwoorden = 0;
private char[] letters = new char[8];
public Speler(String gebruikersnaam, String wachtwoord) {
this.gebruikersnaam = gebruikersnaam;
this.wachtwoord = wachtwoord;
this.saldo = 1000;
}
public void geefAntwoord(String antwoord) {
if (huidigeVraag < quiz.getVragen().length){
Antwoord gegevenAntwoord = new Antwoord(antwoord);
// System.out.println(antwoord);
if (quiz.getVragen()[huidigeVraag - 1].controleerAntwoord(gegevenAntwoord)) {
letters[juisteAntwoorden] = quiz.getVragen()[huidigeVraag - 1].getLetter();
// System.out.println(letters[juisteAntwoorden]);
juisteAntwoorden++;
}
} else {
score = new Score(antwoord, juisteAntwoorden, 100 /* dit is een magic number, heb geen zin een timer te implementeren */);
System.out.println("je score is: " + score.berekenScore());
}
// return "";
}
public void speelQuiz() {
// System.out.println("spelen quiz"); // test code TODO: remove
// get quiz
if (huidigeVraag == -1) {
quiz = new Data().getQuiz();
score = new Score(wachtwoord, saldo, huidigeVraag);
huidigeVraag++;
} else if (huidigeVraag == quiz.getVragen().length) {
// bereken punten
System.out.println("Maak een woord met de volgende letters: ");
for (int i = 0; i < juisteAntwoorden; i++) {
System.out.print(" - " + letters[i]);
}
System.out.println();
// sluit
} else {
// System.out.println(huidigeVraag + " / " + quiz.getVragen().length);
// toon vraag
System.out.println(quiz.getVragen()[huidigeVraag]);
huidigeVraag++;
}
}
public void kopenCredits(int aantal, Speler speler) {
// wordt niet<SUF>
}
}
|
110179_0 | package nl.han.ooad.classes;
public class Data {
public Vragenlijst getVragenlijst() {
String[] antwoorden1 = { "11", "elf" };
String[] antwoorden2 = { "Ottawa" };
String juisteAntwoord1 = "Queen";
String[] fouteAntwoorden1 = { "The Beatles", "Coldplay", "ABBA" };
String juisteAntwoord2 = "50";
String[] fouteAntwoorden2 = { "40", "48", "52" };
Vraag[] vragen = {
new OpenVraag("Hoeveel tijdzones zijn er in Rusland", antwoorden1),
new OpenVraag("Hoeveel tijdzones zijn er in Rusland", antwoorden2),
new MeerkeuzeVraag("Welke band staat het vaakst in de Top 2000 van 2022", juisteAntwoord1,
fouteAntwoorden1),
new MeerkeuzeVraag("Uit hoeveel staten bestaan de Verenigde Staten", juisteAntwoord2, fouteAntwoorden2)
};
return new Vragenlijst(vragen);
}
}
/*
*
* Open vragen:
* 1)
* Vraag: Hoeveel tijdzones zijn er in Rusland?
* Antwoord: 11
*
* 2)
* Vraag: Wat is de hoofdstad van Canada?
* Antwoord: Ottawa
*
* Meerkeuze vragen:
* 3)
* Vraag: Welke band staat het vaakst in de Top 2000 van 2022?
* A: The Beatles (fout)
* B: coldplay (fout)
* C: Queen (goed)
* D: ABBA (fout)
*
* 4)
* Vraag: Uit hoeveel staten bestaan de Verenigde Staten?
* A: 40 (fout)
* B: 48 (fout)
* C: 50 (goed)
* D: 52 (fout)
*/ | MAGerritsen/finch | finch/src/main/java/nl/han/ooad/classes/Data.java | 526 | /*
*
* Open vragen:
* 1)
* Vraag: Hoeveel tijdzones zijn er in Rusland?
* Antwoord: 11
*
* 2)
* Vraag: Wat is de hoofdstad van Canada?
* Antwoord: Ottawa
*
* Meerkeuze vragen:
* 3)
* Vraag: Welke band staat het vaakst in de Top 2000 van 2022?
* A: The Beatles (fout)
* B: coldplay (fout)
* C: Queen (goed)
* D: ABBA (fout)
*
* 4)
* Vraag: Uit hoeveel staten bestaan de Verenigde Staten?
* A: 40 (fout)
* B: 48 (fout)
* C: 50 (goed)
* D: 52 (fout)
*/ | block_comment | nl | package nl.han.ooad.classes;
public class Data {
public Vragenlijst getVragenlijst() {
String[] antwoorden1 = { "11", "elf" };
String[] antwoorden2 = { "Ottawa" };
String juisteAntwoord1 = "Queen";
String[] fouteAntwoorden1 = { "The Beatles", "Coldplay", "ABBA" };
String juisteAntwoord2 = "50";
String[] fouteAntwoorden2 = { "40", "48", "52" };
Vraag[] vragen = {
new OpenVraag("Hoeveel tijdzones zijn er in Rusland", antwoorden1),
new OpenVraag("Hoeveel tijdzones zijn er in Rusland", antwoorden2),
new MeerkeuzeVraag("Welke band staat het vaakst in de Top 2000 van 2022", juisteAntwoord1,
fouteAntwoorden1),
new MeerkeuzeVraag("Uit hoeveel staten bestaan de Verenigde Staten", juisteAntwoord2, fouteAntwoorden2)
};
return new Vragenlijst(vragen);
}
}
/*
*
* Open vragen:
<SUF>*/ |
46446_12 | package game.state;
import game.Game;
import game.GameTime;
import game.UpdateGameLocations;
import game.bullet.Bullet;
import game.character.Player;
import game.client.PortalController;
import game.controller.MouseAndKeyBoardPlayerController;
import game.controller.PlayerController;
import game.enums.Facing;
import game.level.Level;
import game.physics.AABoundingRect;
import game.physics.Physics;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Random;
import java.util.Timer;
import org.newdawn.slick.Color;
import org.newdawn.slick.gui.TextField;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.TrueTypeFont;
import org.newdawn.slick.geom.Vector2f;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
public class LevelState extends BasicGameState {
private Level level;
private String startinglevel;
private Player player;
private PlayerController playerController;
private Physics physics;
TextField chatlog;
TextField textmessage;
TrueTypeFont font;
Input i;
boolean typing = false;
private PortalController control;
private Timer gameTimer;
private GameTime gametimecount;
private Timer updateTimer;
private UpdateGameLocations updategameloc;
//BULLET: stuk moet apart voor character, doe ik wel later
public LinkedList<Bullet> bullets;
protected int DELAY = 100;
protected int deelta = 0;
public LevelState(String startingLevel) {
this.startinglevel = startingLevel;
}
public void init(GameContainer container, StateBasedGame sbg) throws SlickException {
//at the start of the game we don't have a player yet
//player = new Player(128, 415, 1);
player = new Player(250, 800, 2);
//once we initialize our level, we want to load the right level
level = new Level(startinglevel, player);
control = new PortalController(level, this);
level.setControl(control);
//and we create a controller, for now we use the MouseAndKeyBoardPlayerController
playerController = new MouseAndKeyBoardPlayerController(player, level);
physics = new Physics(player);
font = new TrueTypeFont(new java.awt.Font(java.awt.Font.SERIF, java.awt.Font.BOLD, 13), false);
chatlog = new TextField(container, font, 0, container.getHeight() - 300, 300, 128);
chatlog.setText("AWSOME");
gametimecount = new GameTime(5000, level.getCharacters(), container);
updategameloc = new UpdateGameLocations(level.getCharacters(), player, level, control);
gameTimer = new Timer();
gameTimer.scheduleAtFixedRate(gametimecount, 0, 1000);
updateTimer = new Timer();
updateTimer.scheduleAtFixedRate(updategameloc, 0, 500);
textmessage = new TextField(container, font, 0, container.getHeight() - 170, 300, 25);
//BULLET: stuk moet apart voor character, doe ik wel later
bullets = new LinkedList<Bullet>();
}
public void update(GameContainer container, StateBasedGame sbg, int delta) throws SlickException {
if (!gametimecount.isEndofgame()) {
//int playerid, double health, double damage, int kills, double damagedone, Gravity gravity, float x, float y
//every update we have to handle the input from the player
playerController.handleInput(container.getInput(), delta, level.getCharacters());
//we want to pass on the gravity here, and only here in case some levels decide to do things differently (like disabling the gravity device for example)
physics.handlePhysics(level, delta, level.getCurrentGravity());
//BULLET: stuk moet apart voor character, doe ik wel later
deelta += delta;
Iterator<Bullet> i = bullets.iterator();
while (i.hasNext()) {
Bullet b = i.next();
if (b.isActive()) {
b.update(delta);
for (game.character.Character c : level.getCharacters()) {
if (b.getPlayerid() != c.getPlayerId()) {
AABoundingRect boundingShape = new AABoundingRect(b.getPosx(), b.getPosy(), 5, 5);
AABoundingRect boundingShape2 = new AABoundingRect(c.getX() - 2 - level.getXOffset() + 20, c.getY() - 2 - level.getYOffset() + 20, 26, 32);
if (boundingShape.checkCollision(boundingShape2)) {
if (player.getPlayerId() != c.getPlayerId()) {
c.takedamage(player.getDamage());
System.out.println("damage");
if (player.getPlayerId() == b.getPlayerid()) {
player.addDamagedone(player.getDamage());
if (c.getHealth() <= 0) {
player.AddPoints(200);
player.addKills();
int[] xspawns = new int[]{200, 1400, 200, 1800};
int[] yspawns = new int[]{250, 250, 1250, 1250};
Random rand = new Random();
int n = rand.nextInt(3);
if (c.getCrystal()) {
c.setCrystal(false);
control.clientsendcrystal(c.getX(), c.getY());
}
c.setX(xspawns[n]);
c.setY(yspawns[n]);
System.out.println(n);
c.setHealth(100);
}
}
control.clientsend(player.getGravity(), player.getPlayerId(), player.getHealth(), player.getDamage(), player.getKills(), player.getDamagedone(), player.getX(), player.getY(), player.getFacing(), player.getCrystal());
control.clientsend(c.getGravity(), c.getPlayerId(), c.getHealth(), c.getDamage(), c.getKills(), c.getDamagedone(), c.getX(), c.getY(), c.getFacing(), c.getCrystal());
i.remove();
}
}
}
}
} else {
i.remove();
}
}
// bullet moet nog op characters pos worden gezet en moet naar de muis toe worde geschoten , heb nu schietn op punt van muis
if (container.getInput()
.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON) && deelta > DELAY) {
Bullet bull = new Bullet(new Vector2f(player.getX() - 2 - level.getXOffset() + 50, player.getY() - 2 - level.getYOffset() + 35), new Vector2f(250, 10), new Vector2f(container.getInput().getMouseX(), container.getInput().getMouseY()), this.player.getPlayerId());
bullets.add(bull);
control.clientsendbullet(bull);
deelta = 0;
}
}
}
public String getGameTimeCount() {
return secondsToString(gametimecount.getCount());
}
private String secondsToString(int pTime) {
return String.format("%02d:%02d", pTime / 60, pTime % 60);
}
public void render(GameContainer container, StateBasedGame sbg, Graphics g) throws SlickException {
g.scale(Game.SCALE, Game.SCALE);
//render the level
level.render();
g.drawString("Score: " + player.getPoints(), 20, 20);
g.drawString("Current gravity: " + player.getGravity(), 20, 30);
g.drawString("Damage: " + player.getDamage(), 20, 45);
g.fillRect(container.getWidth() / 2 - 200, -1, 200, 60, new Image("data/img/ui/timerui.png"), 0, 0);
g.drawString(getGameTimeCount(), container.getWidth() / 2 - 125, 20);
for (game.character.Character c : level.getCharacters()) {
g.drawString("hp: " + c.getHealth(), c.getX() - 2 - level.getXOffset(), c.getY() - 2 - level.getYOffset() - 20);
}
//BULLET: stuk moet apart voor character, doe ik wel later
Iterator<Bullet> i = bullets.iterator();
while (i.hasNext()) {
i.next().render(container, g);
}
if (gametimecount.isEndofgame()) {
Color myColour = new Color(0, 0, 0, 180);
g.setColor(myColour);
g.fillRect(0, 0, container.getScreenWidth(), container.getScreenHeight());
Color scorebcolor = new Color(255, 255, 255, 255);
g.setColor(scorebcolor);
g.fillRect(200, 100, 700, 400);
Color scorecolor = new Color(0, 0, 0, 255);
g.setColor(scorecolor);
g.drawString("Player", 240, 120);
g.drawString("Points", 410, 120);
g.drawString("Damage Done", 550, 120);
g.drawString("Kills", 750, 120);
g.drawLine(200, 150, 900, 150);
int locationy = 160;
for (game.character.Character c : level.getCharacters()) {
g.drawString(Integer.toString(c.getPlayerId()), 230, locationy);
g.drawString(Integer.toString(c.getPoints()), 420, locationy);
g.drawString(Double.toString(c.getDamagedone()), 560, locationy);
g.drawString(Integer.toString(c.getKills()), 760, locationy);
locationy += 30;
}
}
}
String message = "";
//this method is overriden from basicgamestate and will trigger once you press any key on your keyboard
public void keyPressed(int key, char code) {
//if the key is escape, close our application
if (key == Input.KEY_ESCAPE) {
System.exit(0);
}
message = message + Character.toString(code);
if (key == Input.KEY_DELETE) {
message = "";
}
if (key == Input.KEY_BACK) {
message = message.substring(0, message.length() - 2);
}
textmessage.setText(message);
}
public String backSpace(String str) {
if (str.length() > 0 && str.charAt(str.length() - 1) == 'x') {
str = str.substring(0, str.length() - 1);
}
return str;
}
public int getID() {
//this is the id for changing states
return 0;
}
public void AddBullets(Bullet bull) {
for (game.character.Character e : level.getCharacters()) {
if (this.player.getPlayerId() != bull.getPlayerid()) {
if (e.getPlayerId() == bull.getPlayerid()) {
Bullet bullet = new Bullet(new Vector2f(e.getX() - 2 - level.getXOffset() + 50, e.getY() - 2 - level.getYOffset() + 35), bull.getSpeed(), bull.getMousel(), bull.getPlayerid());
this.bullets.add(bullet);
}
}
}
}
}
| MBakirci/Gravity-Falls | Prototype/Gravity_Falls/Gravity_Falls/src/game/state/LevelState.java | 3,317 | //BULLET: stuk moet apart voor character, doe ik wel later | line_comment | nl | package game.state;
import game.Game;
import game.GameTime;
import game.UpdateGameLocations;
import game.bullet.Bullet;
import game.character.Player;
import game.client.PortalController;
import game.controller.MouseAndKeyBoardPlayerController;
import game.controller.PlayerController;
import game.enums.Facing;
import game.level.Level;
import game.physics.AABoundingRect;
import game.physics.Physics;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Random;
import java.util.Timer;
import org.newdawn.slick.Color;
import org.newdawn.slick.gui.TextField;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.TrueTypeFont;
import org.newdawn.slick.geom.Vector2f;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
public class LevelState extends BasicGameState {
private Level level;
private String startinglevel;
private Player player;
private PlayerController playerController;
private Physics physics;
TextField chatlog;
TextField textmessage;
TrueTypeFont font;
Input i;
boolean typing = false;
private PortalController control;
private Timer gameTimer;
private GameTime gametimecount;
private Timer updateTimer;
private UpdateGameLocations updategameloc;
//BULLET: stuk moet apart voor character, doe ik wel later
public LinkedList<Bullet> bullets;
protected int DELAY = 100;
protected int deelta = 0;
public LevelState(String startingLevel) {
this.startinglevel = startingLevel;
}
public void init(GameContainer container, StateBasedGame sbg) throws SlickException {
//at the start of the game we don't have a player yet
//player = new Player(128, 415, 1);
player = new Player(250, 800, 2);
//once we initialize our level, we want to load the right level
level = new Level(startinglevel, player);
control = new PortalController(level, this);
level.setControl(control);
//and we create a controller, for now we use the MouseAndKeyBoardPlayerController
playerController = new MouseAndKeyBoardPlayerController(player, level);
physics = new Physics(player);
font = new TrueTypeFont(new java.awt.Font(java.awt.Font.SERIF, java.awt.Font.BOLD, 13), false);
chatlog = new TextField(container, font, 0, container.getHeight() - 300, 300, 128);
chatlog.setText("AWSOME");
gametimecount = new GameTime(5000, level.getCharacters(), container);
updategameloc = new UpdateGameLocations(level.getCharacters(), player, level, control);
gameTimer = new Timer();
gameTimer.scheduleAtFixedRate(gametimecount, 0, 1000);
updateTimer = new Timer();
updateTimer.scheduleAtFixedRate(updategameloc, 0, 500);
textmessage = new TextField(container, font, 0, container.getHeight() - 170, 300, 25);
//BULLET: stuk moet apart voor character, doe ik wel later
bullets = new LinkedList<Bullet>();
}
public void update(GameContainer container, StateBasedGame sbg, int delta) throws SlickException {
if (!gametimecount.isEndofgame()) {
//int playerid, double health, double damage, int kills, double damagedone, Gravity gravity, float x, float y
//every update we have to handle the input from the player
playerController.handleInput(container.getInput(), delta, level.getCharacters());
//we want to pass on the gravity here, and only here in case some levels decide to do things differently (like disabling the gravity device for example)
physics.handlePhysics(level, delta, level.getCurrentGravity());
//BULLET: stuk moet apart voor character, doe ik wel later
deelta += delta;
Iterator<Bullet> i = bullets.iterator();
while (i.hasNext()) {
Bullet b = i.next();
if (b.isActive()) {
b.update(delta);
for (game.character.Character c : level.getCharacters()) {
if (b.getPlayerid() != c.getPlayerId()) {
AABoundingRect boundingShape = new AABoundingRect(b.getPosx(), b.getPosy(), 5, 5);
AABoundingRect boundingShape2 = new AABoundingRect(c.getX() - 2 - level.getXOffset() + 20, c.getY() - 2 - level.getYOffset() + 20, 26, 32);
if (boundingShape.checkCollision(boundingShape2)) {
if (player.getPlayerId() != c.getPlayerId()) {
c.takedamage(player.getDamage());
System.out.println("damage");
if (player.getPlayerId() == b.getPlayerid()) {
player.addDamagedone(player.getDamage());
if (c.getHealth() <= 0) {
player.AddPoints(200);
player.addKills();
int[] xspawns = new int[]{200, 1400, 200, 1800};
int[] yspawns = new int[]{250, 250, 1250, 1250};
Random rand = new Random();
int n = rand.nextInt(3);
if (c.getCrystal()) {
c.setCrystal(false);
control.clientsendcrystal(c.getX(), c.getY());
}
c.setX(xspawns[n]);
c.setY(yspawns[n]);
System.out.println(n);
c.setHealth(100);
}
}
control.clientsend(player.getGravity(), player.getPlayerId(), player.getHealth(), player.getDamage(), player.getKills(), player.getDamagedone(), player.getX(), player.getY(), player.getFacing(), player.getCrystal());
control.clientsend(c.getGravity(), c.getPlayerId(), c.getHealth(), c.getDamage(), c.getKills(), c.getDamagedone(), c.getX(), c.getY(), c.getFacing(), c.getCrystal());
i.remove();
}
}
}
}
} else {
i.remove();
}
}
// bullet moet nog op characters pos worden gezet en moet naar de muis toe worde geschoten , heb nu schietn op punt van muis
if (container.getInput()
.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON) && deelta > DELAY) {
Bullet bull = new Bullet(new Vector2f(player.getX() - 2 - level.getXOffset() + 50, player.getY() - 2 - level.getYOffset() + 35), new Vector2f(250, 10), new Vector2f(container.getInput().getMouseX(), container.getInput().getMouseY()), this.player.getPlayerId());
bullets.add(bull);
control.clientsendbullet(bull);
deelta = 0;
}
}
}
public String getGameTimeCount() {
return secondsToString(gametimecount.getCount());
}
private String secondsToString(int pTime) {
return String.format("%02d:%02d", pTime / 60, pTime % 60);
}
public void render(GameContainer container, StateBasedGame sbg, Graphics g) throws SlickException {
g.scale(Game.SCALE, Game.SCALE);
//render the level
level.render();
g.drawString("Score: " + player.getPoints(), 20, 20);
g.drawString("Current gravity: " + player.getGravity(), 20, 30);
g.drawString("Damage: " + player.getDamage(), 20, 45);
g.fillRect(container.getWidth() / 2 - 200, -1, 200, 60, new Image("data/img/ui/timerui.png"), 0, 0);
g.drawString(getGameTimeCount(), container.getWidth() / 2 - 125, 20);
for (game.character.Character c : level.getCharacters()) {
g.drawString("hp: " + c.getHealth(), c.getX() - 2 - level.getXOffset(), c.getY() - 2 - level.getYOffset() - 20);
}
//BULLET: stuk<SUF>
Iterator<Bullet> i = bullets.iterator();
while (i.hasNext()) {
i.next().render(container, g);
}
if (gametimecount.isEndofgame()) {
Color myColour = new Color(0, 0, 0, 180);
g.setColor(myColour);
g.fillRect(0, 0, container.getScreenWidth(), container.getScreenHeight());
Color scorebcolor = new Color(255, 255, 255, 255);
g.setColor(scorebcolor);
g.fillRect(200, 100, 700, 400);
Color scorecolor = new Color(0, 0, 0, 255);
g.setColor(scorecolor);
g.drawString("Player", 240, 120);
g.drawString("Points", 410, 120);
g.drawString("Damage Done", 550, 120);
g.drawString("Kills", 750, 120);
g.drawLine(200, 150, 900, 150);
int locationy = 160;
for (game.character.Character c : level.getCharacters()) {
g.drawString(Integer.toString(c.getPlayerId()), 230, locationy);
g.drawString(Integer.toString(c.getPoints()), 420, locationy);
g.drawString(Double.toString(c.getDamagedone()), 560, locationy);
g.drawString(Integer.toString(c.getKills()), 760, locationy);
locationy += 30;
}
}
}
String message = "";
//this method is overriden from basicgamestate and will trigger once you press any key on your keyboard
public void keyPressed(int key, char code) {
//if the key is escape, close our application
if (key == Input.KEY_ESCAPE) {
System.exit(0);
}
message = message + Character.toString(code);
if (key == Input.KEY_DELETE) {
message = "";
}
if (key == Input.KEY_BACK) {
message = message.substring(0, message.length() - 2);
}
textmessage.setText(message);
}
public String backSpace(String str) {
if (str.length() > 0 && str.charAt(str.length() - 1) == 'x') {
str = str.substring(0, str.length() - 1);
}
return str;
}
public int getID() {
//this is the id for changing states
return 0;
}
public void AddBullets(Bullet bull) {
for (game.character.Character e : level.getCharacters()) {
if (this.player.getPlayerId() != bull.getPlayerid()) {
if (e.getPlayerId() == bull.getPlayerid()) {
Bullet bullet = new Bullet(new Vector2f(e.getX() - 2 - level.getXOffset() + 50, e.getY() - 2 - level.getYOffset() + 35), bull.getSpeed(), bull.getMousel(), bull.getPlayerid());
this.bullets.add(bullet);
}
}
}
}
}
|
144057_1 | package be.thomasmore.streamfindr.controllers;
import be.thomasmore.streamfindr.model.*;
import be.thomasmore.streamfindr.repositories.AccountRepository;
import be.thomasmore.streamfindr.repositories.ContentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.security.Principal;
import java.util.*;
import java.util.stream.Collectors;
@Controller
public class ContentController {
@Autowired
private ContentRepository contentRepository;
@Autowired
private AccountRepository accountRepository;
@ModelAttribute("content")
public Content findContent(@PathVariable(required = false) Integer id) {
if (id != null) {
Optional<Content> optionalContent = contentRepository.findById(id);
if (optionalContent.isPresent()) return optionalContent.get();
}
return null;
}
@GetMapping({"/", "/home"})
public String home(Model model) {
List<Content> allContent = contentRepository.findAll();
allContent.sort(Comparator.comparing(Content::getName));
List<Content> mostRecentContent = findMostRecent(allContent);
List<Content> top3Reviewed = contentRepository.findTop3ReviewedContent();
model.addAttribute("content", mostRecentContent);
model.addAttribute("top3", top3Reviewed);
return "home";
}
private List<Content> findMostRecent(List<Content> sortedContent) {
//Setting the year fixed as the data will not be updated later on
int currentYear = 2023;
List<Content> mostRecentContent = sortedContent.stream()
.filter(c -> (c instanceof Movie && ((Movie) c).getYearReleased() == currentYear + 1) ||
(c instanceof Show && ((Show) c).getLastYearAired() == currentYear + 1))
.limit(6)
.collect(Collectors.toList());
if (mostRecentContent.size() < 6) {
mostRecentContent.addAll(sortedContent.stream()
.filter(c -> (c instanceof Movie && ((Movie) c).getYearReleased() == currentYear) ||
(c instanceof Show && ((Show) c).getLastYearAired() == currentYear))
.limit(6 - mostRecentContent.size())
.collect(Collectors.toList()));
}
return mostRecentContent;
}
@GetMapping({"/contentlist", "/contentlist/"})
public String contentList(Model model) {
List<Content> allContent = contentRepository.findAll();
model.addAttribute("content", allContent);
return "contentlist";
}
@GetMapping("/contentlist/filter")
public String contentListWithFilter(Model model,
@RequestParam(required = false) String contentType,
@RequestParam(required = false) String genre,
@RequestParam(required = false) String platform,
@RequestParam(required = false) String keyword,
@RequestParam(required = false) Integer minScore) {
List<Content> filteredContent = contentRepository.findByCombinedFilter(contentType,
genre, platform, keyword, minScore);
model.addAttribute("showFilters", true);
model.addAttribute("content", filteredContent);
model.addAttribute("contentType", contentType);
model.addAttribute("selectedGenre", genre);
model.addAttribute("selectedPlatform", platform);
model.addAttribute("keyword", keyword);
model.addAttribute("minScore", minScore);
model.addAttribute("distinctGenres", contentRepository.findDistinctGenres());
model.addAttribute("distinctPlatformNames", contentRepository.findDistinctPlatformNames());
return "contentlist";
}
@GetMapping({"/contentdetails", "/contentdetails/", "/contentdetails/{id}"})
public String contentDetails(Model model,
@ModelAttribute("content") Content content,
@PathVariable(required = false) Integer id,
Principal principal) {
//Doorgeven welke user ingelogd is via Principal, en of content in favorieten zit.
if (content != null) {
Content foundContentForAccount = null;
if (principal != null) {
Optional<Account> optionalAccount = accountRepository.findByUsername(principal.getName());
if (optionalAccount.isPresent()) {
Account account = optionalAccount.get();
foundContentForAccount = findContentById(account.getContent(), id);
}
}
Optional<Content> prevContent = contentRepository.findFirstByIdLessThanOrderByIdDesc(id);
if (prevContent.isEmpty()) prevContent = contentRepository.findFirstByOrderByIdDesc();
Optional<Content> nextContent = contentRepository.findFirstByIdGreaterThanOrderByIdAsc(id);
if (nextContent.isEmpty()) nextContent = contentRepository.findFirstByOrderByIdAsc();
model.addAttribute("prevContent", prevContent.get().getId());
model.addAttribute("nextContent", nextContent.get().getId());
model.addAttribute("averageRating", contentRepository.calculateAverageRatingForContent(content));
model.addAttribute("inFavourites", foundContentForAccount != null);
}
return "contentdetails";
}
@PostMapping({"/contentfavourite", "/contentfavourite/{id}"})
public String contentFavourite(Model model,
Principal principal,
@PathVariable(required = false) Integer id) {
if (id == null) return "redirect:/contentlist";
if (principal == null) return "redirect:/contentdetails/" + id;
Optional<Content> optionalContent = contentRepository.findById(id);
Optional<Account> optionalAccount = accountRepository.findByUsername(principal.getName());
if (optionalContent.isPresent() && optionalAccount.isPresent()) {
Account account = optionalAccount.get();
//check if the content is already in account favourites
Content content = findContentById(account.getContent(), id);
if (content == null) {
account.getContent().add(optionalContent.get());
} else {
account.getContent().remove(content);
}
accountRepository.save(account);
}
return "redirect:/contentdetails/" + id;
}
private Content findContentById(Collection<Content> content, int contentId) {
for (Content contentItem : content) {
if (contentItem.getId() == contentId) return contentItem;
}
return null;
}
}
| MC-GH/streamfindr | src/main/java/be/thomasmore/streamfindr/controllers/ContentController.java | 1,716 | //Doorgeven welke user ingelogd is via Principal, en of content in favorieten zit. | line_comment | nl | package be.thomasmore.streamfindr.controllers;
import be.thomasmore.streamfindr.model.*;
import be.thomasmore.streamfindr.repositories.AccountRepository;
import be.thomasmore.streamfindr.repositories.ContentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.security.Principal;
import java.util.*;
import java.util.stream.Collectors;
@Controller
public class ContentController {
@Autowired
private ContentRepository contentRepository;
@Autowired
private AccountRepository accountRepository;
@ModelAttribute("content")
public Content findContent(@PathVariable(required = false) Integer id) {
if (id != null) {
Optional<Content> optionalContent = contentRepository.findById(id);
if (optionalContent.isPresent()) return optionalContent.get();
}
return null;
}
@GetMapping({"/", "/home"})
public String home(Model model) {
List<Content> allContent = contentRepository.findAll();
allContent.sort(Comparator.comparing(Content::getName));
List<Content> mostRecentContent = findMostRecent(allContent);
List<Content> top3Reviewed = contentRepository.findTop3ReviewedContent();
model.addAttribute("content", mostRecentContent);
model.addAttribute("top3", top3Reviewed);
return "home";
}
private List<Content> findMostRecent(List<Content> sortedContent) {
//Setting the year fixed as the data will not be updated later on
int currentYear = 2023;
List<Content> mostRecentContent = sortedContent.stream()
.filter(c -> (c instanceof Movie && ((Movie) c).getYearReleased() == currentYear + 1) ||
(c instanceof Show && ((Show) c).getLastYearAired() == currentYear + 1))
.limit(6)
.collect(Collectors.toList());
if (mostRecentContent.size() < 6) {
mostRecentContent.addAll(sortedContent.stream()
.filter(c -> (c instanceof Movie && ((Movie) c).getYearReleased() == currentYear) ||
(c instanceof Show && ((Show) c).getLastYearAired() == currentYear))
.limit(6 - mostRecentContent.size())
.collect(Collectors.toList()));
}
return mostRecentContent;
}
@GetMapping({"/contentlist", "/contentlist/"})
public String contentList(Model model) {
List<Content> allContent = contentRepository.findAll();
model.addAttribute("content", allContent);
return "contentlist";
}
@GetMapping("/contentlist/filter")
public String contentListWithFilter(Model model,
@RequestParam(required = false) String contentType,
@RequestParam(required = false) String genre,
@RequestParam(required = false) String platform,
@RequestParam(required = false) String keyword,
@RequestParam(required = false) Integer minScore) {
List<Content> filteredContent = contentRepository.findByCombinedFilter(contentType,
genre, platform, keyword, minScore);
model.addAttribute("showFilters", true);
model.addAttribute("content", filteredContent);
model.addAttribute("contentType", contentType);
model.addAttribute("selectedGenre", genre);
model.addAttribute("selectedPlatform", platform);
model.addAttribute("keyword", keyword);
model.addAttribute("minScore", minScore);
model.addAttribute("distinctGenres", contentRepository.findDistinctGenres());
model.addAttribute("distinctPlatformNames", contentRepository.findDistinctPlatformNames());
return "contentlist";
}
@GetMapping({"/contentdetails", "/contentdetails/", "/contentdetails/{id}"})
public String contentDetails(Model model,
@ModelAttribute("content") Content content,
@PathVariable(required = false) Integer id,
Principal principal) {
//Doorgeven welke<SUF>
if (content != null) {
Content foundContentForAccount = null;
if (principal != null) {
Optional<Account> optionalAccount = accountRepository.findByUsername(principal.getName());
if (optionalAccount.isPresent()) {
Account account = optionalAccount.get();
foundContentForAccount = findContentById(account.getContent(), id);
}
}
Optional<Content> prevContent = contentRepository.findFirstByIdLessThanOrderByIdDesc(id);
if (prevContent.isEmpty()) prevContent = contentRepository.findFirstByOrderByIdDesc();
Optional<Content> nextContent = contentRepository.findFirstByIdGreaterThanOrderByIdAsc(id);
if (nextContent.isEmpty()) nextContent = contentRepository.findFirstByOrderByIdAsc();
model.addAttribute("prevContent", prevContent.get().getId());
model.addAttribute("nextContent", nextContent.get().getId());
model.addAttribute("averageRating", contentRepository.calculateAverageRatingForContent(content));
model.addAttribute("inFavourites", foundContentForAccount != null);
}
return "contentdetails";
}
@PostMapping({"/contentfavourite", "/contentfavourite/{id}"})
public String contentFavourite(Model model,
Principal principal,
@PathVariable(required = false) Integer id) {
if (id == null) return "redirect:/contentlist";
if (principal == null) return "redirect:/contentdetails/" + id;
Optional<Content> optionalContent = contentRepository.findById(id);
Optional<Account> optionalAccount = accountRepository.findByUsername(principal.getName());
if (optionalContent.isPresent() && optionalAccount.isPresent()) {
Account account = optionalAccount.get();
//check if the content is already in account favourites
Content content = findContentById(account.getContent(), id);
if (content == null) {
account.getContent().add(optionalContent.get());
} else {
account.getContent().remove(content);
}
accountRepository.save(account);
}
return "redirect:/contentdetails/" + id;
}
private Content findContentById(Collection<Content> content, int contentId) {
for (Content contentItem : content) {
if (contentItem.getId() == contentId) return contentItem;
}
return null;
}
}
|
21353_11 | /**
*/
package lowcoders.impl;
import java.util.Collection;
import lowcoders.GroundTruthExtraction;
import lowcoders.LowcodersPackage;
import lowcoders.Variable;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.eclipse.emf.ecore.util.EDataTypeUniqueEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Ground Truth Extraction</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link lowcoders.impl.GroundTruthExtractionImpl#getSizeGT <em>Size GT</em>}</li>
* <li>{@link lowcoders.impl.GroundTruthExtractionImpl#getSplittingRules <em>Splitting Rules</em>}</li>
* <li>{@link lowcoders.impl.GroundTruthExtractionImpl#getTargetVariable <em>Target Variable</em>}</li>
* </ul>
*
* @generated
*/
public class GroundTruthExtractionImpl extends MinimalEObjectImpl.Container implements GroundTruthExtraction {
/**
* The default value of the '{@link #getSizeGT() <em>Size GT</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSizeGT()
* @generated
* @ordered
*/
protected static final String SIZE_GT_EDEFAULT = null;
/**
* The cached value of the '{@link #getSizeGT() <em>Size GT</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSizeGT()
* @generated
* @ordered
*/
protected String sizeGT = SIZE_GT_EDEFAULT;
/**
* The cached value of the '{@link #getSplittingRules() <em>Splitting Rules</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSplittingRules()
* @generated
* @ordered
*/
protected EList<String> splittingRules;
/**
* The cached value of the '{@link #getTargetVariable() <em>Target Variable</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTargetVariable()
* @generated
* @ordered
*/
protected Variable targetVariable;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected GroundTruthExtractionImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return LowcodersPackage.Literals.GROUND_TRUTH_EXTRACTION;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getSizeGT() {
return sizeGT;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setSizeGT(String newSizeGT) {
String oldSizeGT = sizeGT;
sizeGT = newSizeGT;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, LowcodersPackage.GROUND_TRUTH_EXTRACTION__SIZE_GT, oldSizeGT, sizeGT));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public EList<String> getSplittingRules() {
if (splittingRules == null) {
splittingRules = new EDataTypeUniqueEList<String>(String.class, this, LowcodersPackage.GROUND_TRUTH_EXTRACTION__SPLITTING_RULES);
}
return splittingRules;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Variable getTargetVariable() {
if (targetVariable != null && targetVariable.eIsProxy()) {
InternalEObject oldTargetVariable = (InternalEObject)targetVariable;
targetVariable = (Variable)eResolveProxy(oldTargetVariable);
if (targetVariable != oldTargetVariable) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, LowcodersPackage.GROUND_TRUTH_EXTRACTION__TARGET_VARIABLE, oldTargetVariable, targetVariable));
}
}
return targetVariable;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Variable basicGetTargetVariable() {
return targetVariable;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setTargetVariable(Variable newTargetVariable) {
Variable oldTargetVariable = targetVariable;
targetVariable = newTargetVariable;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, LowcodersPackage.GROUND_TRUTH_EXTRACTION__TARGET_VARIABLE, oldTargetVariable, targetVariable));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case LowcodersPackage.GROUND_TRUTH_EXTRACTION__SIZE_GT:
return getSizeGT();
case LowcodersPackage.GROUND_TRUTH_EXTRACTION__SPLITTING_RULES:
return getSplittingRules();
case LowcodersPackage.GROUND_TRUTH_EXTRACTION__TARGET_VARIABLE:
if (resolve) return getTargetVariable();
return basicGetTargetVariable();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case LowcodersPackage.GROUND_TRUTH_EXTRACTION__SIZE_GT:
setSizeGT((String)newValue);
return;
case LowcodersPackage.GROUND_TRUTH_EXTRACTION__SPLITTING_RULES:
getSplittingRules().clear();
getSplittingRules().addAll((Collection<? extends String>)newValue);
return;
case LowcodersPackage.GROUND_TRUTH_EXTRACTION__TARGET_VARIABLE:
setTargetVariable((Variable)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case LowcodersPackage.GROUND_TRUTH_EXTRACTION__SIZE_GT:
setSizeGT(SIZE_GT_EDEFAULT);
return;
case LowcodersPackage.GROUND_TRUTH_EXTRACTION__SPLITTING_RULES:
getSplittingRules().clear();
return;
case LowcodersPackage.GROUND_TRUTH_EXTRACTION__TARGET_VARIABLE:
setTargetVariable((Variable)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case LowcodersPackage.GROUND_TRUTH_EXTRACTION__SIZE_GT:
return SIZE_GT_EDEFAULT == null ? sizeGT != null : !SIZE_GT_EDEFAULT.equals(sizeGT);
case LowcodersPackage.GROUND_TRUTH_EXTRACTION__SPLITTING_RULES:
return splittingRules != null && !splittingRules.isEmpty();
case LowcodersPackage.GROUND_TRUTH_EXTRACTION__TARGET_VARIABLE:
return targetVariable != null;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuilder result = new StringBuilder(super.toString());
result.append(" (sizeGT: ");
result.append(sizeGT);
result.append(", splittingRules: ");
result.append(splittingRules);
result.append(')');
return result.toString();
}
} //GroundTruthExtractionImpl
| MDEGroup/LEV4REC-Tool | lev4rec/bundles/lev4rec.model/src/lowcoders/impl/GroundTruthExtractionImpl.java | 2,560 | /**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/ | block_comment | nl | /**
*/
package lowcoders.impl;
import java.util.Collection;
import lowcoders.GroundTruthExtraction;
import lowcoders.LowcodersPackage;
import lowcoders.Variable;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.eclipse.emf.ecore.util.EDataTypeUniqueEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Ground Truth Extraction</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link lowcoders.impl.GroundTruthExtractionImpl#getSizeGT <em>Size GT</em>}</li>
* <li>{@link lowcoders.impl.GroundTruthExtractionImpl#getSplittingRules <em>Splitting Rules</em>}</li>
* <li>{@link lowcoders.impl.GroundTruthExtractionImpl#getTargetVariable <em>Target Variable</em>}</li>
* </ul>
*
* @generated
*/
public class GroundTruthExtractionImpl extends MinimalEObjectImpl.Container implements GroundTruthExtraction {
/**
* The default value of the '{@link #getSizeGT() <em>Size GT</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSizeGT()
* @generated
* @ordered
*/
protected static final String SIZE_GT_EDEFAULT = null;
/**
* The cached value of the '{@link #getSizeGT() <em>Size GT</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSizeGT()
* @generated
* @ordered
*/
protected String sizeGT = SIZE_GT_EDEFAULT;
/**
* The cached value of the '{@link #getSplittingRules() <em>Splitting Rules</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSplittingRules()
* @generated
* @ordered
*/
protected EList<String> splittingRules;
/**
* The cached value of the '{@link #getTargetVariable() <em>Target Variable</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTargetVariable()
* @generated
* @ordered
*/
protected Variable targetVariable;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected GroundTruthExtractionImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return LowcodersPackage.Literals.GROUND_TRUTH_EXTRACTION;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getSizeGT() {
return sizeGT;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setSizeGT(String newSizeGT) {
String oldSizeGT = sizeGT;
sizeGT = newSizeGT;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, LowcodersPackage.GROUND_TRUTH_EXTRACTION__SIZE_GT, oldSizeGT, sizeGT));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public EList<String> getSplittingRules() {
if (splittingRules == null) {
splittingRules = new EDataTypeUniqueEList<String>(String.class, this, LowcodersPackage.GROUND_TRUTH_EXTRACTION__SPLITTING_RULES);
}
return splittingRules;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Variable getTargetVariable() {
if (targetVariable != null && targetVariable.eIsProxy()) {
InternalEObject oldTargetVariable = (InternalEObject)targetVariable;
targetVariable = (Variable)eResolveProxy(oldTargetVariable);
if (targetVariable != oldTargetVariable) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, LowcodersPackage.GROUND_TRUTH_EXTRACTION__TARGET_VARIABLE, oldTargetVariable, targetVariable));
}
}
return targetVariable;
}
/**
* <!-- begin-user-doc --><SUF>*/
public Variable basicGetTargetVariable() {
return targetVariable;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setTargetVariable(Variable newTargetVariable) {
Variable oldTargetVariable = targetVariable;
targetVariable = newTargetVariable;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, LowcodersPackage.GROUND_TRUTH_EXTRACTION__TARGET_VARIABLE, oldTargetVariable, targetVariable));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case LowcodersPackage.GROUND_TRUTH_EXTRACTION__SIZE_GT:
return getSizeGT();
case LowcodersPackage.GROUND_TRUTH_EXTRACTION__SPLITTING_RULES:
return getSplittingRules();
case LowcodersPackage.GROUND_TRUTH_EXTRACTION__TARGET_VARIABLE:
if (resolve) return getTargetVariable();
return basicGetTargetVariable();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case LowcodersPackage.GROUND_TRUTH_EXTRACTION__SIZE_GT:
setSizeGT((String)newValue);
return;
case LowcodersPackage.GROUND_TRUTH_EXTRACTION__SPLITTING_RULES:
getSplittingRules().clear();
getSplittingRules().addAll((Collection<? extends String>)newValue);
return;
case LowcodersPackage.GROUND_TRUTH_EXTRACTION__TARGET_VARIABLE:
setTargetVariable((Variable)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case LowcodersPackage.GROUND_TRUTH_EXTRACTION__SIZE_GT:
setSizeGT(SIZE_GT_EDEFAULT);
return;
case LowcodersPackage.GROUND_TRUTH_EXTRACTION__SPLITTING_RULES:
getSplittingRules().clear();
return;
case LowcodersPackage.GROUND_TRUTH_EXTRACTION__TARGET_VARIABLE:
setTargetVariable((Variable)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case LowcodersPackage.GROUND_TRUTH_EXTRACTION__SIZE_GT:
return SIZE_GT_EDEFAULT == null ? sizeGT != null : !SIZE_GT_EDEFAULT.equals(sizeGT);
case LowcodersPackage.GROUND_TRUTH_EXTRACTION__SPLITTING_RULES:
return splittingRules != null && !splittingRules.isEmpty();
case LowcodersPackage.GROUND_TRUTH_EXTRACTION__TARGET_VARIABLE:
return targetVariable != null;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuilder result = new StringBuilder(super.toString());
result.append(" (sizeGT: ");
result.append(sizeGT);
result.append(", splittingRules: ");
result.append(splittingRules);
result.append(')');
return result.toString();
}
} //GroundTruthExtractionImpl
|
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;
}
}
|
7438_4 | import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Main {
// Deze 4 constanten worden gebruikt om tekst met kleur te printen in de console.
// Hier hoef je niks mee te doen
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_BLACK = "\u001B[30m";
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";
// Dit zijn de Pokemons die je tot je beschikking hebt
private static final FirePokemon charizard = new FirePokemon("Charrizard", 76, 150, "firenougats", "GRRRRRRRRRRRRRRR");
private static final WaterPokemon blastoise = new WaterPokemon("Blastoise", 40, 110, "Pokeflakes", "Blaaaaasssssstooooiiiiissss");
private static final GrassPokemon venusaur = new GrassPokemon("Venusaur", 50, 135, "Pokeleafs", "Veeeeeeeeennnnnuuuuuusaur");
private static final GrassPokemon ditto = new GrassPokemon("Ditto", 60, 140, "Everything", "Dittto diiiito ");
private static final ElectricPokemon raichu = new ElectricPokemon("Raichu", 80, 160, "Pokebrocks", "Raaaaiiiiicccchhhhuuuuuuu!!!!");
private static final WaterPokemon gyarados = new WaterPokemon("Gyarados", 90, 180, "Pokeflakes", "Gyaaaaaaaaarrrraaaadoooos");
private static List<Pokemon> pokemons = Arrays.asList(charizard, blastoise, venusaur, ditto, raichu, gyarados);
// Los in de main methode alle foutmeldigen op door (abstracte) klassen met variabelen en methoden te maken (en soms een import).
// In de main methode en de Main klasse hoef je niks te veranderen.
public static void main(String[] args) {
Scanner speler_A = new Scanner(System.in);
PokemonGymImpl pokemonGym = new PokemonGymImpl(pokemons);
System.out.println("First player please enter your name: ");
String userA = speler_A.nextLine();
PokemonTrainer player1 = new PokemonTrainer(userA, pokemons);
System.out.println("To start your game, we have given you 6 Pokemons use");
System.out.println("these are the Pokemons you get:");
pokemonGym.printPokemon(pokemons);
System.out.println("Would you like to enter a gym looking for a fight?");
System.out.println("Please enter yes or no");
if (speler_A.nextLine().equals("yes")) {
pokemonGym.enteredTheGym(player1);
}
}
}
| MFarrah/backend-java-pokemon-interface-uitwerkingen | src/Main.java | 806 | // In de main methode en de Main klasse hoef je niks te veranderen. | line_comment | nl | import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Main {
// Deze 4 constanten worden gebruikt om tekst met kleur te printen in de console.
// Hier hoef je niks mee te doen
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_BLACK = "\u001B[30m";
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";
// Dit zijn de Pokemons die je tot je beschikking hebt
private static final FirePokemon charizard = new FirePokemon("Charrizard", 76, 150, "firenougats", "GRRRRRRRRRRRRRRR");
private static final WaterPokemon blastoise = new WaterPokemon("Blastoise", 40, 110, "Pokeflakes", "Blaaaaasssssstooooiiiiissss");
private static final GrassPokemon venusaur = new GrassPokemon("Venusaur", 50, 135, "Pokeleafs", "Veeeeeeeeennnnnuuuuuusaur");
private static final GrassPokemon ditto = new GrassPokemon("Ditto", 60, 140, "Everything", "Dittto diiiito ");
private static final ElectricPokemon raichu = new ElectricPokemon("Raichu", 80, 160, "Pokebrocks", "Raaaaiiiiicccchhhhuuuuuuu!!!!");
private static final WaterPokemon gyarados = new WaterPokemon("Gyarados", 90, 180, "Pokeflakes", "Gyaaaaaaaaarrrraaaadoooos");
private static List<Pokemon> pokemons = Arrays.asList(charizard, blastoise, venusaur, ditto, raichu, gyarados);
// Los in de main methode alle foutmeldigen op door (abstracte) klassen met variabelen en methoden te maken (en soms een import).
// In de<SUF>
public static void main(String[] args) {
Scanner speler_A = new Scanner(System.in);
PokemonGymImpl pokemonGym = new PokemonGymImpl(pokemons);
System.out.println("First player please enter your name: ");
String userA = speler_A.nextLine();
PokemonTrainer player1 = new PokemonTrainer(userA, pokemons);
System.out.println("To start your game, we have given you 6 Pokemons use");
System.out.println("these are the Pokemons you get:");
pokemonGym.printPokemon(pokemons);
System.out.println("Would you like to enter a gym looking for a fight?");
System.out.println("Please enter yes or no");
if (speler_A.nextLine().equals("yes")) {
pokemonGym.enteredTheGym(player1);
}
}
}
|
168575_1 | package de.danielluedecke.zettelkasten.tasks;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.danielluedecke.zettelkasten.ZettelkastenView;
import de.danielluedecke.zettelkasten.database.Settings;
import de.danielluedecke.zettelkasten.util.Constants;
import de.danielluedecke.zettelkasten.util.Version;
import org.kohsuke.github.*;
import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Luedeke
*/
public class CheckForUpdateTask extends org.jdesktop.application.Task<Object, Void> {
// indicates whether the zettelkasten has updates or not.
private boolean updateavailable = false;
private boolean showUpdateMsg = true;
private String updateBuildNr = "0";
private long cachingDuration = 4*60*60*1000;
private final Settings settingsObj;
/**
* Reference to the main frame.
*/
private final ZettelkastenView zknframe;
public CheckForUpdateTask(org.jdesktop.application.Application app,
ZettelkastenView zkn, Settings s) {
// Runs on the EDT. Copy GUI state that
// doInBackground() depends on from parameters
// to ImportFileTask fields, here.
super(app);
zknframe = zkn;
settingsObj = s;
}
protected String accessUpdateFile(URL updatetext) {
// input stream that will read the update text
InputStream is = null;
// stringbuilder that will contain the content of the update-file
StringBuilder updateinfo = new StringBuilder("");
try {
// open update-file on server
is = updatetext.openStream();
// buffer for stream
int buff = 0;
// read update-file and copy content to string builder
while (buff != -1) {
buff = is.read();
if (buff != -1) {
updateinfo.append((char) buff);
}
}
} catch (IOException e) {
// tell about fail
Constants.zknlogger.log(Level.INFO, "No access to Zettelkasten-Website. Automatic update-check failed.");
updateavailable = false;
return null;
} finally {
try {
if (is != null) {
is.close();
}
}catch(IOException e) {
Constants.zknlogger.log(Level.WARNING, e.getLocalizedMessage());
}
}
return updateinfo.toString();
}
@Override
protected Object doInBackground() throws IOException {
Path zkdir = Paths.get(System.getProperty("user.home") + File.separatorChar + ".Zettelkasten");
Path versionPath = zkdir.resolve("version.properties");
Properties versionProperties = new Properties();
String versionName;
String releaseUrl;
if (!zkdir.toFile().exists()) {
zkdir.toFile().mkdirs();
}
if (versionPath.toFile().exists()
&& (new Date().getTime()-versionPath.toFile().lastModified() <= cachingDuration)) {
try (FileInputStream fos = new FileInputStream(versionPath.toAbsolutePath().toString())) {
versionProperties.load(fos);
versionName = versionProperties.getProperty("version");
updateBuildNr = versionProperties.getProperty("buildNr");
releaseUrl = versionProperties.getProperty("releaseUrl");
}
Constants.zknlogger.info("Found and loaded version properties file.");
} else {
if (versionPath.toFile().exists()){
Constants.zknlogger.info("Found version properties file, but it is older than "
+ cachingDuration/1000/60/60 + " hours.");
} else {
Constants.zknlogger.info("Did not find any version properties file.");
}
Constants.zknlogger.info("Loading version information from github.");
GitHub github = GitHub.connectAnonymously();
GHRelease release = null;
GHRepository zettelkasten = github.getUser("sjPlot").getRepository("Zettelkasten");
PagedIterable<GHRelease> ghReleases = zettelkasten.listReleases();
PagedIterable<GHTag> ghTags = zettelkasten.listTags();
for (GHRelease r : ghReleases) {
if (r.isPrerelease() && settingsObj.getAutoNightlyUpdate()) {
release = r;
} else if (!r.isDraft()) {
release = r;
}
if (release != null) break;
}
if (release == null) return null;
for (GHTag tag : ghTags) {
if (tag.getName().equals(release.getName())) {
updateBuildNr = tag.getCommit().getSHA1().substring(0, 7);
break;
}
}
versionName = release.getName();
releaseUrl = release.getHtmlUrl().toString();
}
versionProperties.setProperty("version", versionName);
versionProperties.setProperty("buildNr", updateBuildNr);
versionProperties.setProperty("releaseUrl", releaseUrl);
try (FileOutputStream fos = new FileOutputStream(versionPath.toAbsolutePath().toString())){
versionProperties.store(fos, null);
Constants.zknlogger.fine("stored version properties file.");
} catch(IOException e) {
Constants.zknlogger.warning("Could not write version file.");
}
Version otherVersion = new Version();
otherVersion.setBuild(updateBuildNr);
otherVersion.setVersion(versionName);
updateavailable = Version.get().compare(otherVersion) < 0;
showUpdateMsg = (updateBuildNr.compareTo(settingsObj.getShowUpdateHintVersion()) != 0);
zknframe.setUpdateURI(releaseUrl);
return null; // return your result
}
@Override
protected void succeeded(Object result) {
// Runs on the EDT. Update the GUI based on
// the result computed by doInBackground().
}
@Override
protected void finished() {
if (updateavailable) {
//log info
Constants.zknlogger.log(Level.INFO, "A new version of the Zettelkasten is available!");
if (showUpdateMsg) {
zknframe.updateZettelkasten(updateBuildNr);
}
}
}
}
| MHohenberg/Zettelkasten | src/main/java/de/danielluedecke/zettelkasten/tasks/CheckForUpdateTask.java | 1,858 | /**
*
* @author Luedeke
*/ | block_comment | nl | package de.danielluedecke.zettelkasten.tasks;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.danielluedecke.zettelkasten.ZettelkastenView;
import de.danielluedecke.zettelkasten.database.Settings;
import de.danielluedecke.zettelkasten.util.Constants;
import de.danielluedecke.zettelkasten.util.Version;
import org.kohsuke.github.*;
import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Luedeke
<SUF>*/
public class CheckForUpdateTask extends org.jdesktop.application.Task<Object, Void> {
// indicates whether the zettelkasten has updates or not.
private boolean updateavailable = false;
private boolean showUpdateMsg = true;
private String updateBuildNr = "0";
private long cachingDuration = 4*60*60*1000;
private final Settings settingsObj;
/**
* Reference to the main frame.
*/
private final ZettelkastenView zknframe;
public CheckForUpdateTask(org.jdesktop.application.Application app,
ZettelkastenView zkn, Settings s) {
// Runs on the EDT. Copy GUI state that
// doInBackground() depends on from parameters
// to ImportFileTask fields, here.
super(app);
zknframe = zkn;
settingsObj = s;
}
protected String accessUpdateFile(URL updatetext) {
// input stream that will read the update text
InputStream is = null;
// stringbuilder that will contain the content of the update-file
StringBuilder updateinfo = new StringBuilder("");
try {
// open update-file on server
is = updatetext.openStream();
// buffer for stream
int buff = 0;
// read update-file and copy content to string builder
while (buff != -1) {
buff = is.read();
if (buff != -1) {
updateinfo.append((char) buff);
}
}
} catch (IOException e) {
// tell about fail
Constants.zknlogger.log(Level.INFO, "No access to Zettelkasten-Website. Automatic update-check failed.");
updateavailable = false;
return null;
} finally {
try {
if (is != null) {
is.close();
}
}catch(IOException e) {
Constants.zknlogger.log(Level.WARNING, e.getLocalizedMessage());
}
}
return updateinfo.toString();
}
@Override
protected Object doInBackground() throws IOException {
Path zkdir = Paths.get(System.getProperty("user.home") + File.separatorChar + ".Zettelkasten");
Path versionPath = zkdir.resolve("version.properties");
Properties versionProperties = new Properties();
String versionName;
String releaseUrl;
if (!zkdir.toFile().exists()) {
zkdir.toFile().mkdirs();
}
if (versionPath.toFile().exists()
&& (new Date().getTime()-versionPath.toFile().lastModified() <= cachingDuration)) {
try (FileInputStream fos = new FileInputStream(versionPath.toAbsolutePath().toString())) {
versionProperties.load(fos);
versionName = versionProperties.getProperty("version");
updateBuildNr = versionProperties.getProperty("buildNr");
releaseUrl = versionProperties.getProperty("releaseUrl");
}
Constants.zknlogger.info("Found and loaded version properties file.");
} else {
if (versionPath.toFile().exists()){
Constants.zknlogger.info("Found version properties file, but it is older than "
+ cachingDuration/1000/60/60 + " hours.");
} else {
Constants.zknlogger.info("Did not find any version properties file.");
}
Constants.zknlogger.info("Loading version information from github.");
GitHub github = GitHub.connectAnonymously();
GHRelease release = null;
GHRepository zettelkasten = github.getUser("sjPlot").getRepository("Zettelkasten");
PagedIterable<GHRelease> ghReleases = zettelkasten.listReleases();
PagedIterable<GHTag> ghTags = zettelkasten.listTags();
for (GHRelease r : ghReleases) {
if (r.isPrerelease() && settingsObj.getAutoNightlyUpdate()) {
release = r;
} else if (!r.isDraft()) {
release = r;
}
if (release != null) break;
}
if (release == null) return null;
for (GHTag tag : ghTags) {
if (tag.getName().equals(release.getName())) {
updateBuildNr = tag.getCommit().getSHA1().substring(0, 7);
break;
}
}
versionName = release.getName();
releaseUrl = release.getHtmlUrl().toString();
}
versionProperties.setProperty("version", versionName);
versionProperties.setProperty("buildNr", updateBuildNr);
versionProperties.setProperty("releaseUrl", releaseUrl);
try (FileOutputStream fos = new FileOutputStream(versionPath.toAbsolutePath().toString())){
versionProperties.store(fos, null);
Constants.zknlogger.fine("stored version properties file.");
} catch(IOException e) {
Constants.zknlogger.warning("Could not write version file.");
}
Version otherVersion = new Version();
otherVersion.setBuild(updateBuildNr);
otherVersion.setVersion(versionName);
updateavailable = Version.get().compare(otherVersion) < 0;
showUpdateMsg = (updateBuildNr.compareTo(settingsObj.getShowUpdateHintVersion()) != 0);
zknframe.setUpdateURI(releaseUrl);
return null; // return your result
}
@Override
protected void succeeded(Object result) {
// Runs on the EDT. Update the GUI based on
// the result computed by doInBackground().
}
@Override
protected void finished() {
if (updateavailable) {
//log info
Constants.zknlogger.log(Level.INFO, "A new version of the Zettelkasten is available!");
if (showUpdateMsg) {
zknframe.updateZettelkasten(updateBuildNr);
}
}
}
}
|
35808_33 | /*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.oned;
import java.util.Hashtable;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.ResultPoint;
import com.google.zxing.common.BitArray;
/**
* <p>Decodes Codabar barcodes.</p>
*
* @author Bas Vijfwinkel
*/
public final class CodaBarReader extends OneDReader {
private static final String ALPHABET_STRING = "0123456789-$:/.+ABCDTN";
private static final char[] ALPHABET = ALPHABET_STRING.toCharArray();
/**
* These represent the encodings of characters, as patterns of wide and narrow bars. The 7 least-significant bits of
* each int correspond to the pattern of wide and narrow, with 1s representing "wide" and 0s representing narrow. NOTE
* : c is equal to the * pattern NOTE : d is equal to the e pattern
*/
private static final int[] CHARACTER_ENCODINGS = {
0x003, 0x006, 0x009, 0x060, 0x012, 0x042, 0x021, 0x024, 0x030, 0x048, // 0-9
0x00c, 0x018, 0x025, 0x051, 0x054, 0x015, 0x01A, 0x029, 0x00B, 0x00E, // -$:/.+ABCD
0x01A, 0x029 //TN
};
// minimal number of characters that should be present (inclusing start and stop characters)
// this check has been added to reduce the number of false positive on other formats
// until the cause for this behaviour has been determined
// under normal circumstances this should be set to 3
private static final int minCharacterLength = 6;
// multiple start/end patterns
// official start and end patterns
private static final char[] STARTEND_ENCODING = {'E', '*', 'A', 'B', 'C', 'D', 'T', 'N'};
// some codabar generator allow the codabar string to be closed by every character
//private static final char[] STARTEND_ENCODING = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '$', ':', '/', '.', '+', 'A', 'B', 'C', 'D', 'T', 'N'};
// some industries use a checksum standard but this is not part of the original codabar standard
// for more information see : http://www.mecsw.com/specs/codabar.html
@Override
public Result decodeRow(int rowNumber, BitArray row, @SuppressWarnings("rawtypes") Hashtable hints) throws NotFoundException {
int[] start = findAsteriskPattern(row);
start[1] = 0; // BAS: settings this to 0 improves the recognition rate somehow?
int nextStart = start[1];
int end = row.getSize();
// Read off white space
while (nextStart < end && !row.get(nextStart)) {
nextStart++;
}
StringBuffer result = new StringBuffer();
//int[] counters = new int[7];
int[] counters;
int lastStart;
do {
counters = new int[]{0, 0, 0, 0, 0, 0, 0}; // reset counters
recordPattern(row, nextStart, counters);
char decodedChar = toNarrowWidePattern(counters);
if (decodedChar == '!') {
throw NotFoundException.getNotFoundInstance();
}
result.append(decodedChar);
lastStart = nextStart;
for (int i = 0; i < counters.length; i++) {
nextStart += counters[i];
}
// Read off white space
while (nextStart < end && !row.get(nextStart)) {
nextStart++;
}
} while (nextStart < end); // no fixed end pattern so keep on reading while data is available
// Look for whitespace after pattern:
int lastPatternSize = 0;
for (int i = 0; i < counters.length; i++) {
lastPatternSize += counters[i];
}
int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
// If 50% of last pattern size, following last pattern, is not whitespace, fail
// (but if it's whitespace to the very end of the image, that's OK)
if ((nextStart) != end && (whiteSpaceAfterEnd / 2 < lastPatternSize)) {
throw NotFoundException.getNotFoundInstance();
}
// valid result?
if (result.length() < 2)
{
throw NotFoundException.getNotFoundInstance();
}
char startchar = result.charAt(0);
if (!arrayContains(STARTEND_ENCODING, startchar))
{
//invalid start character
throw NotFoundException.getNotFoundInstance();
}
// find stop character
for (int k = 1;k < result.length() ;k++)
{
if (result.charAt(k) == startchar)
{
// found stop character -> discard rest of the string
if ((k+1) != result.length())
{
result.delete(k+1,result.length()-1);
k = result.length();// break out of loop
}
}
}
// remove stop/start characters character and check if a string longer than 5 characters is contained
if (result.length() > minCharacterLength)
{
result.deleteCharAt(result.length()-1);
result.deleteCharAt(0);
}
else
{
// Almost surely a false positive ( start + stop + at least 1 character)
throw NotFoundException.getNotFoundInstance();
}
float left = (float) (start[1] + start[0]) / 2.0f;
float right = (float) (nextStart + lastStart) / 2.0f;
return new Result(
result.toString(),
null,
new ResultPoint[]{
new ResultPoint(left, (float) rowNumber),
new ResultPoint(right, (float) rowNumber)},
BarcodeFormat.CODABAR);
}
private static int[] findAsteriskPattern(BitArray row) throws NotFoundException {
int width = row.getSize();
int rowOffset = 0;
while (rowOffset < width) {
if (row.get(rowOffset)) {
break;
}
rowOffset++;
}
int counterPosition = 0;
int[] counters = new int[7];
int patternStart = rowOffset;
boolean isWhite = false;
int patternLength = counters.length;
for (int i = rowOffset; i < width; i++) {
boolean pixel = row.get(i);
if (pixel ^ isWhite) {
counters[counterPosition]++;
} else {
if (counterPosition == patternLength - 1) {
try {
if (arrayContains(STARTEND_ENCODING, toNarrowWidePattern(counters))) {
// Look for whitespace before start pattern, >= 50% of width of start pattern
if (row.isRange(Math.max(0, patternStart - (i - patternStart) / 2), patternStart, false)) {
return new int[]{patternStart, i};
}
}
} catch (IllegalArgumentException re) {
// no match, continue
}
patternStart += counters[0] + counters[1];
for (int y = 2; y < patternLength; y++) {
counters[y - 2] = counters[y];
}
counters[patternLength - 2] = 0;
counters[patternLength - 1] = 0;
counterPosition--;
} else {
counterPosition++;
}
counters[counterPosition] = 1;
isWhite ^= true; // isWhite = !isWhite;
}
}
throw NotFoundException.getNotFoundInstance();
}
private static boolean arrayContains(char[] array, char key) {
if (array != null) {
for (int i = 0; i < array.length; i++) {
if (array[i] == key) {
return true;
}
}
}
return false;
}
private static char toNarrowWidePattern(int[] counters) {
// BAS : I have changed the following part because some codabar images would fail with the original routine
// I took from the Code39Reader.java file
// ----------- change start
int numCounters = counters.length;
int maxNarrowCounter = 0;
int minCounter = Integer.MAX_VALUE;
for (int i = 0; i < numCounters; i++) {
if (counters[i] < minCounter) {
minCounter = counters[i];
}
if (counters[i] > maxNarrowCounter) {
maxNarrowCounter = counters[i];
}
}
// ---------- change end
do {
int wideCounters = 0;
int pattern = 0;
for (int i = 0; i < numCounters; i++) {
if (counters[i] > maxNarrowCounter) {
pattern |= 1 << (numCounters - 1 - i);
wideCounters++;
}
}
if ((wideCounters == 2) || (wideCounters == 3)) {
for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) {
if (CHARACTER_ENCODINGS[i] == pattern) {
return ALPHABET[i];
}
}
}
maxNarrowCounter--;
} while (maxNarrowCounter > minCounter);
return '!';
}
}
| MIT-Mobile/MIT-Mobile-for-Android | src/com/google/zxing/oned/CodaBarReader.java | 2,941 | // ---------- change end
| line_comment | nl | /*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.oned;
import java.util.Hashtable;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.ResultPoint;
import com.google.zxing.common.BitArray;
/**
* <p>Decodes Codabar barcodes.</p>
*
* @author Bas Vijfwinkel
*/
public final class CodaBarReader extends OneDReader {
private static final String ALPHABET_STRING = "0123456789-$:/.+ABCDTN";
private static final char[] ALPHABET = ALPHABET_STRING.toCharArray();
/**
* These represent the encodings of characters, as patterns of wide and narrow bars. The 7 least-significant bits of
* each int correspond to the pattern of wide and narrow, with 1s representing "wide" and 0s representing narrow. NOTE
* : c is equal to the * pattern NOTE : d is equal to the e pattern
*/
private static final int[] CHARACTER_ENCODINGS = {
0x003, 0x006, 0x009, 0x060, 0x012, 0x042, 0x021, 0x024, 0x030, 0x048, // 0-9
0x00c, 0x018, 0x025, 0x051, 0x054, 0x015, 0x01A, 0x029, 0x00B, 0x00E, // -$:/.+ABCD
0x01A, 0x029 //TN
};
// minimal number of characters that should be present (inclusing start and stop characters)
// this check has been added to reduce the number of false positive on other formats
// until the cause for this behaviour has been determined
// under normal circumstances this should be set to 3
private static final int minCharacterLength = 6;
// multiple start/end patterns
// official start and end patterns
private static final char[] STARTEND_ENCODING = {'E', '*', 'A', 'B', 'C', 'D', 'T', 'N'};
// some codabar generator allow the codabar string to be closed by every character
//private static final char[] STARTEND_ENCODING = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '$', ':', '/', '.', '+', 'A', 'B', 'C', 'D', 'T', 'N'};
// some industries use a checksum standard but this is not part of the original codabar standard
// for more information see : http://www.mecsw.com/specs/codabar.html
@Override
public Result decodeRow(int rowNumber, BitArray row, @SuppressWarnings("rawtypes") Hashtable hints) throws NotFoundException {
int[] start = findAsteriskPattern(row);
start[1] = 0; // BAS: settings this to 0 improves the recognition rate somehow?
int nextStart = start[1];
int end = row.getSize();
// Read off white space
while (nextStart < end && !row.get(nextStart)) {
nextStart++;
}
StringBuffer result = new StringBuffer();
//int[] counters = new int[7];
int[] counters;
int lastStart;
do {
counters = new int[]{0, 0, 0, 0, 0, 0, 0}; // reset counters
recordPattern(row, nextStart, counters);
char decodedChar = toNarrowWidePattern(counters);
if (decodedChar == '!') {
throw NotFoundException.getNotFoundInstance();
}
result.append(decodedChar);
lastStart = nextStart;
for (int i = 0; i < counters.length; i++) {
nextStart += counters[i];
}
// Read off white space
while (nextStart < end && !row.get(nextStart)) {
nextStart++;
}
} while (nextStart < end); // no fixed end pattern so keep on reading while data is available
// Look for whitespace after pattern:
int lastPatternSize = 0;
for (int i = 0; i < counters.length; i++) {
lastPatternSize += counters[i];
}
int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
// If 50% of last pattern size, following last pattern, is not whitespace, fail
// (but if it's whitespace to the very end of the image, that's OK)
if ((nextStart) != end && (whiteSpaceAfterEnd / 2 < lastPatternSize)) {
throw NotFoundException.getNotFoundInstance();
}
// valid result?
if (result.length() < 2)
{
throw NotFoundException.getNotFoundInstance();
}
char startchar = result.charAt(0);
if (!arrayContains(STARTEND_ENCODING, startchar))
{
//invalid start character
throw NotFoundException.getNotFoundInstance();
}
// find stop character
for (int k = 1;k < result.length() ;k++)
{
if (result.charAt(k) == startchar)
{
// found stop character -> discard rest of the string
if ((k+1) != result.length())
{
result.delete(k+1,result.length()-1);
k = result.length();// break out of loop
}
}
}
// remove stop/start characters character and check if a string longer than 5 characters is contained
if (result.length() > minCharacterLength)
{
result.deleteCharAt(result.length()-1);
result.deleteCharAt(0);
}
else
{
// Almost surely a false positive ( start + stop + at least 1 character)
throw NotFoundException.getNotFoundInstance();
}
float left = (float) (start[1] + start[0]) / 2.0f;
float right = (float) (nextStart + lastStart) / 2.0f;
return new Result(
result.toString(),
null,
new ResultPoint[]{
new ResultPoint(left, (float) rowNumber),
new ResultPoint(right, (float) rowNumber)},
BarcodeFormat.CODABAR);
}
private static int[] findAsteriskPattern(BitArray row) throws NotFoundException {
int width = row.getSize();
int rowOffset = 0;
while (rowOffset < width) {
if (row.get(rowOffset)) {
break;
}
rowOffset++;
}
int counterPosition = 0;
int[] counters = new int[7];
int patternStart = rowOffset;
boolean isWhite = false;
int patternLength = counters.length;
for (int i = rowOffset; i < width; i++) {
boolean pixel = row.get(i);
if (pixel ^ isWhite) {
counters[counterPosition]++;
} else {
if (counterPosition == patternLength - 1) {
try {
if (arrayContains(STARTEND_ENCODING, toNarrowWidePattern(counters))) {
// Look for whitespace before start pattern, >= 50% of width of start pattern
if (row.isRange(Math.max(0, patternStart - (i - patternStart) / 2), patternStart, false)) {
return new int[]{patternStart, i};
}
}
} catch (IllegalArgumentException re) {
// no match, continue
}
patternStart += counters[0] + counters[1];
for (int y = 2; y < patternLength; y++) {
counters[y - 2] = counters[y];
}
counters[patternLength - 2] = 0;
counters[patternLength - 1] = 0;
counterPosition--;
} else {
counterPosition++;
}
counters[counterPosition] = 1;
isWhite ^= true; // isWhite = !isWhite;
}
}
throw NotFoundException.getNotFoundInstance();
}
private static boolean arrayContains(char[] array, char key) {
if (array != null) {
for (int i = 0; i < array.length; i++) {
if (array[i] == key) {
return true;
}
}
}
return false;
}
private static char toNarrowWidePattern(int[] counters) {
// BAS : I have changed the following part because some codabar images would fail with the original routine
// I took from the Code39Reader.java file
// ----------- change start
int numCounters = counters.length;
int maxNarrowCounter = 0;
int minCounter = Integer.MAX_VALUE;
for (int i = 0; i < numCounters; i++) {
if (counters[i] < minCounter) {
minCounter = counters[i];
}
if (counters[i] > maxNarrowCounter) {
maxNarrowCounter = counters[i];
}
}
// ---------- change<SUF>
do {
int wideCounters = 0;
int pattern = 0;
for (int i = 0; i < numCounters; i++) {
if (counters[i] > maxNarrowCounter) {
pattern |= 1 << (numCounters - 1 - i);
wideCounters++;
}
}
if ((wideCounters == 2) || (wideCounters == 3)) {
for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) {
if (CHARACTER_ENCODINGS[i] == pattern) {
return ALPHABET[i];
}
}
}
maxNarrowCounter--;
} while (maxNarrowCounter > minCounter);
return '!';
}
}
|
91775_3 | package database;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Centraliseert gedeelde database bewerkingen
* @author Remi De Boer, Gerke de Boer, Michael Oosterhout
*/
public abstract class AbstractDAO {
protected DBaccess dBaccess;
protected PreparedStatement preparedStatement;
public AbstractDAO(DBaccess dBaccess) {
this.dBaccess = dBaccess;
}
/**
* Maakt een preparedStatement voor de sql string. Een DAO gebruikt dit om de parameters te vullen.
*
* @param sql,
* de SQl query
*/
protected void setupPreparedStatement(String sql) throws SQLException {
preparedStatement = dBaccess.getConnection().prepareStatement(sql);
}
/**
* Voert de preparedStatement uit zonder een ResultSet. Wordt gebruikt voor insert, update en
* delete statements.
*
*/
protected void executeManipulateStatement() throws SQLException {
preparedStatement.executeUpdate();
}
/**
* Voert de preparedStatement uit met een ResultSet. Wordt gebruikt voor select statements.
*
*/
protected ResultSet executeSelectStatement() throws SQLException {
return preparedStatement.executeQuery();
}
/**
* Maakt een preparedStatement voor de sql string, die een gegenereerde sleutel terug moet geven.
* @param sql,
* de SQL query
*/
protected void setupPreparedStatementWithKey(String sql) throws SQLException {
preparedStatement = dBaccess.getConnection().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
}
/**
* Voert de prepared statement uit en geeft de gegenereerde sleutel terug.
* Wordt gebruikt voor een insert in een AutoIncrement tabel
*/
protected int executeInsertStatementWithKey() throws SQLException {
preparedStatement.executeUpdate();
ResultSet resultSet = preparedStatement.getGeneratedKeys();
int gegenereerdeSleutel = 0;
while (resultSet.next()) {
gegenereerdeSleutel = resultSet.getInt(1);
}
return gegenereerdeSleutel;
}
}
| MIW-G-C6/Meetkunde | src/database/AbstractDAO.java | 613 | /**
* Voert de preparedStatement uit met een ResultSet. Wordt gebruikt voor select statements.
*
*/ | block_comment | nl | package database;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Centraliseert gedeelde database bewerkingen
* @author Remi De Boer, Gerke de Boer, Michael Oosterhout
*/
public abstract class AbstractDAO {
protected DBaccess dBaccess;
protected PreparedStatement preparedStatement;
public AbstractDAO(DBaccess dBaccess) {
this.dBaccess = dBaccess;
}
/**
* Maakt een preparedStatement voor de sql string. Een DAO gebruikt dit om de parameters te vullen.
*
* @param sql,
* de SQl query
*/
protected void setupPreparedStatement(String sql) throws SQLException {
preparedStatement = dBaccess.getConnection().prepareStatement(sql);
}
/**
* Voert de preparedStatement uit zonder een ResultSet. Wordt gebruikt voor insert, update en
* delete statements.
*
*/
protected void executeManipulateStatement() throws SQLException {
preparedStatement.executeUpdate();
}
/**
* Voert de preparedStatement<SUF>*/
protected ResultSet executeSelectStatement() throws SQLException {
return preparedStatement.executeQuery();
}
/**
* Maakt een preparedStatement voor de sql string, die een gegenereerde sleutel terug moet geven.
* @param sql,
* de SQL query
*/
protected void setupPreparedStatementWithKey(String sql) throws SQLException {
preparedStatement = dBaccess.getConnection().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
}
/**
* Voert de prepared statement uit en geeft de gegenereerde sleutel terug.
* Wordt gebruikt voor een insert in een AutoIncrement tabel
*/
protected int executeInsertStatementWithKey() throws SQLException {
preparedStatement.executeUpdate();
ResultSet resultSet = preparedStatement.getGeneratedKeys();
int gegenereerdeSleutel = 0;
while (resultSet.next()) {
gegenereerdeSleutel = resultSet.getInt(1);
}
return gegenereerdeSleutel;
}
}
|
23901_7 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package thegame;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.shape.Rectangle;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javafx.animation.AnimationTimer;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import javafx.scene.text.FontWeight;
import thegame.com.Game.Map;
import thegame.com.Game.Objects.Characters.Enemy;
import thegame.com.Game.Objects.Characters.Player;
import thegame.com.Game.Objects.MapObject;
import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.scene.canvas.Canvas;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import thegame.com.Game.Objects.Block;
import thegame.com.Game.Objects.BlockType;
import thegame.com.Game.Objects.Characters.CharacterGame;
/**
*
* @author laurens
*/
public class TheGame extends Application {
private Map play;
private Player me;
private Scene scene;
private List<KeyCode> keys = new ArrayList<>();
// MAP
private float dx;
private float dy;
private int startX;
private int startY;
private int offsetBlocks;
// FPS
private final long ONE_SECOND = 1000000000;
private long currentTime = 0;
private long lastTime = 0;
private int fps = 0;
private double delta = 0;
private final EventHandler<KeyEvent> keyListener = (KeyEvent event) ->
{
if (event.getCode() == KeyCode.W || event.getCode() == KeyCode.D || event.getCode() == KeyCode.A)
{
if (event.getEventType() == KeyEvent.KEY_PRESSED && !keys.contains(event.getCode()))
{
keys.add(event.getCode());
if (event.getCode() == KeyCode.A && keys.contains(KeyCode.D))
{
keys.remove(KeyCode.D);
}
if (event.getCode() == KeyCode.D && keys.contains(KeyCode.A))
{
keys.remove(KeyCode.A);
}
} else if (event.getEventType() == KeyEvent.KEY_RELEASED)
{
keys.remove(event.getCode());
if(event.getCode() == KeyCode.W)
me.stopJump();
}
} else
{
if (event.getCode() == KeyCode.DIGIT1 && event.getEventType() == KeyEvent.KEY_PRESSED )
{
play.addObject(new Enemy("Loser", 100, null, play.getSpawnX(), play.getSpawnY(), null, 1, 1, play));
}
if (event.getCode() == KeyCode.DIGIT2 && event.getEventType() == KeyEvent.KEY_PRESSED )
{
float x = Math.round(me.getX());
float y = Math.round(me.getY())-1;
Block block = new Block(BlockType.Dirt, x, y, play);
play.addObject(block);
}
}
};
private final EventHandler<MouseEvent> mouseListener = (MouseEvent event) ->
{
if (event.getButton().equals(MouseButton.PRIMARY))
{
double clickX = (event.getSceneX() + dx) / config.block.val - startX;
double clickY = (scene.getHeight() - event.getSceneY() + dy) / config.block.val - startY;
me.useTool((float) clickX, (float) clickY);
}
};
private Stage stages;
@Override
public void start(Stage primaryStage)
{
Scene scene = new Scene(createContent());
primaryStage.setTitle("Menu");
primaryStage.setScene(scene);
primaryStage.show();
stages = primaryStage;
}
private void draw(GraphicsContext g)
{
float pX = me.getX();
float pY = me.getY();
float pW = me.getW();
float pH = me.getH();
int playH = play.getHeight();
int playW = play.getWidth();
// Get viewables
List<MapObject> view = viewable();
// Clear scene
clear(g);
// Get amount of blocks that fit on screen
int blockHorizontal = (int) Math.ceil(scene.getWidth() / config.block.val) + offsetBlocks;
int blockVertical = (int) Math.ceil(scene.getHeight() / config.block.val) + offsetBlocks;
// preset Delta values
dx = 0;
dy = 0;
// once the player's center is on the middle
if ((pX + pW / 2) * config.block.val > scene.getWidth() / 2 && (pX + pW / 2) * config.block.val < playW * config.block.val - scene.getWidth() / 2)
{
// DX will be the center of the map
dx = (pX + pW / 2) * config.block.val;
dx -= (scene.getWidth() / 2);
// If you are no longer on the right side of the map
if (startX >= 0)
{
dx += (startX) * config.block.val;
}
} else if ((pX + pW / 2) * config.block.val >= playW * config.block.val - scene.getWidth() / 2)
{
// Dit is het goede moment. Hier moet iets gebeuren waardoor de aller laatste blok helemaal rechts wordt getekent en niet meer beweegt
dx = (playW - blockHorizontal + 2) * config.block.val * 2;
}
// once the player's center is on the middle
if ((pY - pH / 2) * config.block.val > scene.getHeight() / 2
&& (pY - pH / 2) * config.block.val < playH * config.block.val - scene.getHeight() / 2)
{
// DX will be the center of the map
dy = (pY - pH / 2) * config.block.val;
dy -= (scene.getHeight() / 2);
// If you are no longer on the right side of the map
if (startX >= 0)
{
dy += (startY) * config.block.val;
}
} else if ((pY - pH / 2) * config.block.val >= playH * config.block.val - scene.getHeight() / 2)
{
// Dit is het goede moment. Hier moet iets gebeuren waardoor de aller laatste blok helemaal rechts wordt getekent en niet meer beweegt
dy = (playH - blockVertical + 2) * config.block.val * 2;
}
for (MapObject draw : view)
{
float x;
float y;
if (!draw.equals(me))
{
x = (draw.getX() + startX) * config.block.val - dx;
y = ((float) scene.getHeight() - (draw.getY() + startY) * config.block.val) + dy;
} else
{
x = (pX + startX) * config.block.val - dx;
y = ((float) scene.getHeight() - (pY + startY) * config.block.val) + dy;
}
if (draw instanceof Player || draw instanceof Enemy)
{
float width = config.block.val * draw.getW();
float height = config.block.val * draw.getH();
// CHARACTER
g.beginPath();
if (draw instanceof Player)
{
g.setFill(Color.BLACK);
} else if (draw instanceof Enemy)
{
g.setFill(Color.RED);
}
g.rect(x, y, width, height);
g.fill();
// ARROW
double[] xPoints = new double[3];
double[] yPoints = new double[3];
CharacterGame enemy = (CharacterGame) draw;
yPoints[0] = y + (height / 2);
yPoints[1] = y;
yPoints[2] = y + height;
switch (enemy.getDirection())
{
case LEFT:
xPoints[0] = x;
xPoints[1] = x + width;
xPoints[2] = x + width;
break;
case RIGHT:
xPoints[0] = x + width;
xPoints[1] = x;
xPoints[2] = x;
break;
}
g.setFill(Color.GREEN);
g.fillPolygon(xPoints, yPoints, 3);
g.closePath();
} else
{
g.beginPath();
g.drawImage(draw.getSkin().show(), x, y);
g.closePath();
}
}
/*
// Calibration lines
g.setLineWidth(1);
g.setStroke(Color.rgb(0, 0, 0, 0.2));
g.strokeLine(scene.getWidth() / 2, 0, scene.getWidth() / 2, scene.getHeight());
g.strokeLine(0, scene.getHeight()/ 2, scene.getWidth(), scene.getHeight() / 2);
*/
}
private void clear(GraphicsContext g)
{
g.clearRect(0, 0, scene.getWidth(), scene.getHeight());
}
private List<MapObject> viewable()
{
// Get amount of blocks that need te be loaded
int blockHorizontal = (int) Math.ceil(scene.getWidth() / config.block.val) + offsetBlocks;
int blockVertical = (int) Math.ceil(scene.getHeight() / config.block.val) + offsetBlocks;
// Calculate the mid position of the player
int midX = (int) Math.floor(me.getX() + (me.getW() / 2));
int midY = (int) Math.ceil(me.getY() - (me.getH() / 2));
// Calculate at what block we should start drawing (the player object should be centered)
startX = (int) Math.ceil(midX - blockHorizontal / 2);
startY = (int) Math.ceil(midY - blockVertical / 2);
// And what will the ending blocks be
int endX = startX + blockHorizontal;
int endY = startY + blockVertical;
// If we are on the left side on the map, draw the map more to the right
while (startX < 0)
{
startX++;
endX++;
}
// If we are to the top side of the map, draw the map more to the bottom
while (startY < 0)
{
startY++;
endY++;
}
// If we are on the right side of the map, draw the map more to the left
while (endX > play.getWidth())
{
startX--;
endX--;
}
// If we are to the bottom side of the map, draw the map more to the top
while (endY > play.getWidth())
{
startY--;
endY--;
}
// If there are less blocks than could be displayed, just display less
if (startX < 0 && endX > play.getWidth())
{
startX = 0;
endX = play.getWidth();
}
// Same for height
if (startY < 0 && endY > play.getHeight())
{
startY = 0;
endY = play.getHeight();
}
// Ask the map for the blocks and objects that should be drawn in this area.
return play.getBlocksAndObjects(startX, startY, endX, endY);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
public void startagame(Stage primaryStage)
{
// Declare variables
play = new Map();
play.generateMap();
me = new Player(null, "Dummy", 100, null, null, play.getSpawnX(), play.getSpawnY(), null, 2, 2, play);
play.addObject(me);
offsetBlocks = 4;
StackPane root = new StackPane();
scene = new Scene(root, 1400, 800, Color.LIGHTBLUE);
scene.addEventHandler(KeyEvent.ANY, keyListener);
scene.addEventHandler(MouseEvent.MOUSE_CLICKED, mouseListener);
final Canvas canvas = new Canvas(scene.getWidth(), scene.getHeight());
GraphicsContext gc = canvas.getGraphicsContext2D();
// Action Listeners
scene.widthProperty().addListener((ObservableValue<? extends Number> observableValue, Number oldSceneWidth, Number newSceneWidth) ->
{
canvas.setWidth((double) newSceneWidth);
});
scene.heightProperty().addListener((ObservableValue<? extends Number> observableValue, Number oldSceneHeight, Number newSceneHeight) ->
{
canvas.setHeight((double) newSceneHeight);
});
// Set stage visiable
root.getChildren().add(canvas);
primaryStage.setScene(scene);
primaryStage.show();
primaryStage.setOnCloseRequest(event ->
{
System.exit(0);
});
// Update screen when animationtimer says it is possible
lastTime = System.nanoTime();
AnimationTimer loop = new AnimationTimer() {
@Override
public void handle(long now)
{
// Calculate fps
currentTime = now;
fps++;
delta += currentTime - lastTime;
draw(gc);
if (delta > ONE_SECOND)
{
primaryStage.setTitle("FPS : " + fps);
delta -= ONE_SECOND;
fps = 0;
}
lastTime = currentTime;
}
};
loop.start();
// TEMP : update all objects that we say may be updated. Will be changed in next itteration
Timer update = new Timer();
update.schedule(new TimerTask() {
@Override
public void run()
{
if (keys.contains(KeyCode.A))
{
me.walkLeft();
} else if (keys.contains(KeyCode.D))
{
me.walkRight();
}
if (keys.contains(KeyCode.W))
{
me.jump();
}
me.update();
play.updateEnemy();
}
}, 0, 1000 / 60);
}
private Parent createContent()
{
Pane root = new Pane();
root.setPrefSize(860, 600);
try (InputStream is = Files.newInputStream(Paths.get("src/resources//menu.jpg")))
{
ImageView img = new ImageView(new Image(is));
img.setFitWidth(860);
img.setFitHeight(600);
root.getChildren().add(img);
} catch (Exception e)
{
System.out.println("Couldnt load image");
}
Title title = new Title("The Game");
title.setTranslateX(75);
title.setTranslateY(200);
MenuItem itemExit = new MenuItem("EXIT");
itemExit.setOnMouseClicked(event -> System.exit((0)));
MenuItem startThegame = new MenuItem("SINGLE PLAYER");
startThegame.setOnMouseClicked(event -> startagame(stages));
MenuBox menu = new MenuBox(
startThegame,
new MenuItem("MULTIPLAYER [soon]"),
new MenuItem("CHARACTERS [soon]"),
new MenuItem("OPTIONS [soon]"),
itemExit);
menu.setTranslateX(100);
menu.setTranslateY(300);
root.getChildren().addAll(title, menu);
return root;
}
private static class MenuItem extends StackPane {
public MenuItem(String name)
{
LinearGradient gradient = new LinearGradient(0, 0, 1, 0, true, CycleMethod.NO_CYCLE, new Stop[]
{
new Stop(0, Color.DARKVIOLET),
new Stop(0.1, Color.BLACK),
new Stop(0.9, Color.BLACK),
new Stop(01, Color.DARKVIOLET)
});
Rectangle bg = new Rectangle(200, 30);
bg.setOpacity(0.4);
Text text = new Text(name);
text.setFill(Color.DARKGREY);
text.setFont(Font.font("Tw Cen MT Condensed", FontWeight.SEMI_BOLD, 22));
setAlignment(Pos.CENTER);
getChildren().addAll(bg, text);
setOnMouseEntered(event ->
{
bg.setFill(gradient);
text.setFill(Color.WHITE);
});
setOnMouseDragExited(event ->
{
bg.setFill(Color.BLACK);
text.setFill(Color.DARKGREY);
});
setOnMousePressed(event ->
{
bg.setFill(Color.DARKGREY);
});
setOnMouseReleased(event ->
{
bg.setFill(gradient);
});
}
}
private static class MenuBox extends VBox {
public MenuBox(MenuItem... items)
{
getChildren().add(createSeparator());
for (MenuItem item : items)
{
getChildren().addAll(item, createSeparator());
}
}
private Line createSeparator()
{
Line sep = new Line();
sep.setEndX(200);
sep.setStroke(Color.DARKGREY);
return sep;
}
}
private static class Title extends StackPane {
public Title(String name)
{
Rectangle bg = new Rectangle(250, 60);
bg.setStroke(Color.WHITE);
bg.setStrokeWidth(2);
bg.setFill(null);
Text text = new Text(name);
text.setFill(Color.WHITE);
text.setFont(Font.font("Tw Cen MT Condensed", FontWeight.SEMI_BOLD, 50));
setAlignment(Pos.CENTER);
getChildren().addAll(bg, text);
}
}
}
| MJJH/EmagEht | TheGame - Iteratie 1/src/thegame/TheGame.java | 5,355 | // Dit is het goede moment. Hier moet iets gebeuren waardoor de aller laatste blok helemaal rechts wordt getekent en niet meer beweegt | line_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package thegame;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.shape.Rectangle;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javafx.animation.AnimationTimer;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import javafx.scene.text.FontWeight;
import thegame.com.Game.Map;
import thegame.com.Game.Objects.Characters.Enemy;
import thegame.com.Game.Objects.Characters.Player;
import thegame.com.Game.Objects.MapObject;
import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.scene.canvas.Canvas;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import thegame.com.Game.Objects.Block;
import thegame.com.Game.Objects.BlockType;
import thegame.com.Game.Objects.Characters.CharacterGame;
/**
*
* @author laurens
*/
public class TheGame extends Application {
private Map play;
private Player me;
private Scene scene;
private List<KeyCode> keys = new ArrayList<>();
// MAP
private float dx;
private float dy;
private int startX;
private int startY;
private int offsetBlocks;
// FPS
private final long ONE_SECOND = 1000000000;
private long currentTime = 0;
private long lastTime = 0;
private int fps = 0;
private double delta = 0;
private final EventHandler<KeyEvent> keyListener = (KeyEvent event) ->
{
if (event.getCode() == KeyCode.W || event.getCode() == KeyCode.D || event.getCode() == KeyCode.A)
{
if (event.getEventType() == KeyEvent.KEY_PRESSED && !keys.contains(event.getCode()))
{
keys.add(event.getCode());
if (event.getCode() == KeyCode.A && keys.contains(KeyCode.D))
{
keys.remove(KeyCode.D);
}
if (event.getCode() == KeyCode.D && keys.contains(KeyCode.A))
{
keys.remove(KeyCode.A);
}
} else if (event.getEventType() == KeyEvent.KEY_RELEASED)
{
keys.remove(event.getCode());
if(event.getCode() == KeyCode.W)
me.stopJump();
}
} else
{
if (event.getCode() == KeyCode.DIGIT1 && event.getEventType() == KeyEvent.KEY_PRESSED )
{
play.addObject(new Enemy("Loser", 100, null, play.getSpawnX(), play.getSpawnY(), null, 1, 1, play));
}
if (event.getCode() == KeyCode.DIGIT2 && event.getEventType() == KeyEvent.KEY_PRESSED )
{
float x = Math.round(me.getX());
float y = Math.round(me.getY())-1;
Block block = new Block(BlockType.Dirt, x, y, play);
play.addObject(block);
}
}
};
private final EventHandler<MouseEvent> mouseListener = (MouseEvent event) ->
{
if (event.getButton().equals(MouseButton.PRIMARY))
{
double clickX = (event.getSceneX() + dx) / config.block.val - startX;
double clickY = (scene.getHeight() - event.getSceneY() + dy) / config.block.val - startY;
me.useTool((float) clickX, (float) clickY);
}
};
private Stage stages;
@Override
public void start(Stage primaryStage)
{
Scene scene = new Scene(createContent());
primaryStage.setTitle("Menu");
primaryStage.setScene(scene);
primaryStage.show();
stages = primaryStage;
}
private void draw(GraphicsContext g)
{
float pX = me.getX();
float pY = me.getY();
float pW = me.getW();
float pH = me.getH();
int playH = play.getHeight();
int playW = play.getWidth();
// Get viewables
List<MapObject> view = viewable();
// Clear scene
clear(g);
// Get amount of blocks that fit on screen
int blockHorizontal = (int) Math.ceil(scene.getWidth() / config.block.val) + offsetBlocks;
int blockVertical = (int) Math.ceil(scene.getHeight() / config.block.val) + offsetBlocks;
// preset Delta values
dx = 0;
dy = 0;
// once the player's center is on the middle
if ((pX + pW / 2) * config.block.val > scene.getWidth() / 2 && (pX + pW / 2) * config.block.val < playW * config.block.val - scene.getWidth() / 2)
{
// DX will be the center of the map
dx = (pX + pW / 2) * config.block.val;
dx -= (scene.getWidth() / 2);
// If you are no longer on the right side of the map
if (startX >= 0)
{
dx += (startX) * config.block.val;
}
} else if ((pX + pW / 2) * config.block.val >= playW * config.block.val - scene.getWidth() / 2)
{
// Dit is<SUF>
dx = (playW - blockHorizontal + 2) * config.block.val * 2;
}
// once the player's center is on the middle
if ((pY - pH / 2) * config.block.val > scene.getHeight() / 2
&& (pY - pH / 2) * config.block.val < playH * config.block.val - scene.getHeight() / 2)
{
// DX will be the center of the map
dy = (pY - pH / 2) * config.block.val;
dy -= (scene.getHeight() / 2);
// If you are no longer on the right side of the map
if (startX >= 0)
{
dy += (startY) * config.block.val;
}
} else if ((pY - pH / 2) * config.block.val >= playH * config.block.val - scene.getHeight() / 2)
{
// Dit is het goede moment. Hier moet iets gebeuren waardoor de aller laatste blok helemaal rechts wordt getekent en niet meer beweegt
dy = (playH - blockVertical + 2) * config.block.val * 2;
}
for (MapObject draw : view)
{
float x;
float y;
if (!draw.equals(me))
{
x = (draw.getX() + startX) * config.block.val - dx;
y = ((float) scene.getHeight() - (draw.getY() + startY) * config.block.val) + dy;
} else
{
x = (pX + startX) * config.block.val - dx;
y = ((float) scene.getHeight() - (pY + startY) * config.block.val) + dy;
}
if (draw instanceof Player || draw instanceof Enemy)
{
float width = config.block.val * draw.getW();
float height = config.block.val * draw.getH();
// CHARACTER
g.beginPath();
if (draw instanceof Player)
{
g.setFill(Color.BLACK);
} else if (draw instanceof Enemy)
{
g.setFill(Color.RED);
}
g.rect(x, y, width, height);
g.fill();
// ARROW
double[] xPoints = new double[3];
double[] yPoints = new double[3];
CharacterGame enemy = (CharacterGame) draw;
yPoints[0] = y + (height / 2);
yPoints[1] = y;
yPoints[2] = y + height;
switch (enemy.getDirection())
{
case LEFT:
xPoints[0] = x;
xPoints[1] = x + width;
xPoints[2] = x + width;
break;
case RIGHT:
xPoints[0] = x + width;
xPoints[1] = x;
xPoints[2] = x;
break;
}
g.setFill(Color.GREEN);
g.fillPolygon(xPoints, yPoints, 3);
g.closePath();
} else
{
g.beginPath();
g.drawImage(draw.getSkin().show(), x, y);
g.closePath();
}
}
/*
// Calibration lines
g.setLineWidth(1);
g.setStroke(Color.rgb(0, 0, 0, 0.2));
g.strokeLine(scene.getWidth() / 2, 0, scene.getWidth() / 2, scene.getHeight());
g.strokeLine(0, scene.getHeight()/ 2, scene.getWidth(), scene.getHeight() / 2);
*/
}
private void clear(GraphicsContext g)
{
g.clearRect(0, 0, scene.getWidth(), scene.getHeight());
}
private List<MapObject> viewable()
{
// Get amount of blocks that need te be loaded
int blockHorizontal = (int) Math.ceil(scene.getWidth() / config.block.val) + offsetBlocks;
int blockVertical = (int) Math.ceil(scene.getHeight() / config.block.val) + offsetBlocks;
// Calculate the mid position of the player
int midX = (int) Math.floor(me.getX() + (me.getW() / 2));
int midY = (int) Math.ceil(me.getY() - (me.getH() / 2));
// Calculate at what block we should start drawing (the player object should be centered)
startX = (int) Math.ceil(midX - blockHorizontal / 2);
startY = (int) Math.ceil(midY - blockVertical / 2);
// And what will the ending blocks be
int endX = startX + blockHorizontal;
int endY = startY + blockVertical;
// If we are on the left side on the map, draw the map more to the right
while (startX < 0)
{
startX++;
endX++;
}
// If we are to the top side of the map, draw the map more to the bottom
while (startY < 0)
{
startY++;
endY++;
}
// If we are on the right side of the map, draw the map more to the left
while (endX > play.getWidth())
{
startX--;
endX--;
}
// If we are to the bottom side of the map, draw the map more to the top
while (endY > play.getWidth())
{
startY--;
endY--;
}
// If there are less blocks than could be displayed, just display less
if (startX < 0 && endX > play.getWidth())
{
startX = 0;
endX = play.getWidth();
}
// Same for height
if (startY < 0 && endY > play.getHeight())
{
startY = 0;
endY = play.getHeight();
}
// Ask the map for the blocks and objects that should be drawn in this area.
return play.getBlocksAndObjects(startX, startY, endX, endY);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
public void startagame(Stage primaryStage)
{
// Declare variables
play = new Map();
play.generateMap();
me = new Player(null, "Dummy", 100, null, null, play.getSpawnX(), play.getSpawnY(), null, 2, 2, play);
play.addObject(me);
offsetBlocks = 4;
StackPane root = new StackPane();
scene = new Scene(root, 1400, 800, Color.LIGHTBLUE);
scene.addEventHandler(KeyEvent.ANY, keyListener);
scene.addEventHandler(MouseEvent.MOUSE_CLICKED, mouseListener);
final Canvas canvas = new Canvas(scene.getWidth(), scene.getHeight());
GraphicsContext gc = canvas.getGraphicsContext2D();
// Action Listeners
scene.widthProperty().addListener((ObservableValue<? extends Number> observableValue, Number oldSceneWidth, Number newSceneWidth) ->
{
canvas.setWidth((double) newSceneWidth);
});
scene.heightProperty().addListener((ObservableValue<? extends Number> observableValue, Number oldSceneHeight, Number newSceneHeight) ->
{
canvas.setHeight((double) newSceneHeight);
});
// Set stage visiable
root.getChildren().add(canvas);
primaryStage.setScene(scene);
primaryStage.show();
primaryStage.setOnCloseRequest(event ->
{
System.exit(0);
});
// Update screen when animationtimer says it is possible
lastTime = System.nanoTime();
AnimationTimer loop = new AnimationTimer() {
@Override
public void handle(long now)
{
// Calculate fps
currentTime = now;
fps++;
delta += currentTime - lastTime;
draw(gc);
if (delta > ONE_SECOND)
{
primaryStage.setTitle("FPS : " + fps);
delta -= ONE_SECOND;
fps = 0;
}
lastTime = currentTime;
}
};
loop.start();
// TEMP : update all objects that we say may be updated. Will be changed in next itteration
Timer update = new Timer();
update.schedule(new TimerTask() {
@Override
public void run()
{
if (keys.contains(KeyCode.A))
{
me.walkLeft();
} else if (keys.contains(KeyCode.D))
{
me.walkRight();
}
if (keys.contains(KeyCode.W))
{
me.jump();
}
me.update();
play.updateEnemy();
}
}, 0, 1000 / 60);
}
private Parent createContent()
{
Pane root = new Pane();
root.setPrefSize(860, 600);
try (InputStream is = Files.newInputStream(Paths.get("src/resources//menu.jpg")))
{
ImageView img = new ImageView(new Image(is));
img.setFitWidth(860);
img.setFitHeight(600);
root.getChildren().add(img);
} catch (Exception e)
{
System.out.println("Couldnt load image");
}
Title title = new Title("The Game");
title.setTranslateX(75);
title.setTranslateY(200);
MenuItem itemExit = new MenuItem("EXIT");
itemExit.setOnMouseClicked(event -> System.exit((0)));
MenuItem startThegame = new MenuItem("SINGLE PLAYER");
startThegame.setOnMouseClicked(event -> startagame(stages));
MenuBox menu = new MenuBox(
startThegame,
new MenuItem("MULTIPLAYER [soon]"),
new MenuItem("CHARACTERS [soon]"),
new MenuItem("OPTIONS [soon]"),
itemExit);
menu.setTranslateX(100);
menu.setTranslateY(300);
root.getChildren().addAll(title, menu);
return root;
}
private static class MenuItem extends StackPane {
public MenuItem(String name)
{
LinearGradient gradient = new LinearGradient(0, 0, 1, 0, true, CycleMethod.NO_CYCLE, new Stop[]
{
new Stop(0, Color.DARKVIOLET),
new Stop(0.1, Color.BLACK),
new Stop(0.9, Color.BLACK),
new Stop(01, Color.DARKVIOLET)
});
Rectangle bg = new Rectangle(200, 30);
bg.setOpacity(0.4);
Text text = new Text(name);
text.setFill(Color.DARKGREY);
text.setFont(Font.font("Tw Cen MT Condensed", FontWeight.SEMI_BOLD, 22));
setAlignment(Pos.CENTER);
getChildren().addAll(bg, text);
setOnMouseEntered(event ->
{
bg.setFill(gradient);
text.setFill(Color.WHITE);
});
setOnMouseDragExited(event ->
{
bg.setFill(Color.BLACK);
text.setFill(Color.DARKGREY);
});
setOnMousePressed(event ->
{
bg.setFill(Color.DARKGREY);
});
setOnMouseReleased(event ->
{
bg.setFill(gradient);
});
}
}
private static class MenuBox extends VBox {
public MenuBox(MenuItem... items)
{
getChildren().add(createSeparator());
for (MenuItem item : items)
{
getChildren().addAll(item, createSeparator());
}
}
private Line createSeparator()
{
Line sep = new Line();
sep.setEndX(200);
sep.setStroke(Color.DARKGREY);
return sep;
}
}
private static class Title extends StackPane {
public Title(String name)
{
Rectangle bg = new Rectangle(250, 60);
bg.setStroke(Color.WHITE);
bg.setStrokeWidth(2);
bg.setFill(null);
Text text = new Text(name);
text.setFill(Color.WHITE);
text.setFont(Font.font("Tw Cen MT Condensed", FontWeight.SEMI_BOLD, 50));
setAlignment(Pos.CENTER);
getChildren().addAll(bg, text);
}
}
}
|
150660_19 | package eu.interedition.collatex.MatrixLinker;
import java.io.PrintWriter;
import java.util.ArrayList;
public class ArchipelagoWithVersions extends Archipelago {
private static final String newLine = System.getProperty("line.separator");
private ArrayList<Archipelago> nonConflVersions;
private Integer[] isl2;
public ArchipelagoWithVersions() {
islands = new ArrayList<Island>();
nonConflVersions = new ArrayList<Archipelago>();
}
public ArchipelagoWithVersions(Island isl) {
islands = new ArrayList<Island>();
nonConflVersions = new ArrayList<Archipelago>();
add(isl);
}
public void add(Island island) {
super.add(island);
}
public void createNonConflictingVersions() {
boolean debug = false;
// PrintWriter logging = null;
// File logFile = new File(File.separator + "c:\\logfile.txt");
// try {
// logging = new PrintWriter(new FileOutputStream(logFile));
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
nonConflVersions = new ArrayList<Archipelago>();
int tel = 0;
for(Island island : islands) {
tel++;
// if(tel>22)
debug = false;
// System.out.println("nonConflVersions.size(): "+nonConflVersions.size());
// int tel_version = 0;
// for(Archipelago arch : nonConflVersions) {
// System.out.println("arch version ("+(tel_version++)+"): " + arch);
// }
// TODO
// if(tel>22) {
// int tel_version = 0;
// for(Archipelago arch : nonConflVersions) {
// System.out.println("arch version ("+(tel_version++)+"): " + arch);
// }
// System.exit(1);
// }
if(nonConflVersions.size()==0) {
if(debug)
System.out.println("nonConflVersions.size()==0");
Archipelago version = new Archipelago();
version.add(island);
nonConflVersions.add(version);
} else {
boolean found_one = false;
ArrayList<Archipelago> new_versions = new ArrayList<Archipelago>();
int tel_loop = 0;
for(Archipelago version : nonConflVersions) {
if(debug)
System.out.println("loop 1: "+tel_loop++);
if(!version.conflictsWith(island)) {
if(debug)
System.out.println("!version.conflictsWith(island)");
version.add(island);
found_one = true;
}
}
if(!found_one) {
if(debug)
System.out.println("!found_one");
// try to find a existing version in which the new island fits
// after removing some points
tel_loop = 0;
for(Archipelago version : nonConflVersions) {
if(debug)
System.out.println("loop 2: "+tel_loop++);
Island island_copy = island.copy();
for(Island isl : version.iterator()) {
island_copy = island_copy.removePoints(isl);
}
if(island_copy.size()>0) {
version.add(island_copy);
found_one = true;
}
}
// create a new version with the new island and (parts of) existing islands
tel_loop = 0;
for(Archipelago version : nonConflVersions) {
if(debug)
System.out.println("loop 3: "+tel_loop++);
Archipelago new_version = new Archipelago();
new_version.add(island);
for(Island isl : version.iterator()) {
Island di = isl.copy();
if(debug)
System.out.println("di: "+di);
Island res = di.removePoints(island);
if(debug)
System.out.println("res: "+res);
if(res.size()>0) {
found_one = true;
new_version.add(res);
}
}
new_versions.add(new_version);
}
if(new_versions.size()>0) {
tel_loop = 0;
for(Archipelago arch : new_versions) {
if(debug)
System.out.println("loop 4: "+tel_loop++);
addVersion(arch);
}
}
}
if(!found_one) {
if(debug)
System.out.println("!found_one");
Archipelago version = new Archipelago();
version.add(island);
addVersion(version);
}
}
}
// int tel_version = 0;
// for(Archipelago arch : nonConflVersions) {
// logging.println("arch version ("+(tel_version++)+"): " + arch);
// }
// tel_version = 0;
// for(Archipelago arch : nonConflVersions) {
// logging.println("version "+(tel_version++)+": " + arch.value());
// }
// logging.close();
}
private void addVersion(Archipelago version) {
int pos = 0;
// int tel_loop = 0;
// System.out.println("addVersion - num of versions: "+nonConflVersions.size());
for(pos = 0; pos<nonConflVersions.size(); pos++) {
if(version.equals(nonConflVersions.get(pos)))
return;
// System.out.println("loop 5: "+tel_loop++);
if(version.value()>nonConflVersions.get(pos).value()) {
nonConflVersions.add(pos,version);
return;
}
}
nonConflVersions.add(version);
}
public int numOfNonConflConstell() {
return nonConflVersions.size();
}
public ArchipelagoWithVersions copy() {
ArchipelagoWithVersions result = new ArchipelagoWithVersions();
for(Island isl: islands) {
result.add((Island) isl.copy());
}
return result;
}
public Archipelago getVersion(int i) {
try {
if(nonConflVersions.isEmpty())
createNonConflictingVersions();
return nonConflVersions.get(i);
} catch(IndexOutOfBoundsException exc) {
return null;
}
}
public ArrayList<Archipelago> getNonConflVersions() {
return nonConflVersions;
}
/*
* Create a non-conflicting version by simply taken all the islands
* that to not conflict with each other, largest first. This presuming
* that Archipelago will have a high value if it contains the largest
* possible islands
*/
public Archipelago createFirstVersion() {
Archipelago result = new Archipelago();
for(Island isl: islands) {
int i=0;
int res_size = result.size();
boolean confl = false;
for(i=0; i<res_size; i++) {
if(result.get(i).isCompetitor(isl)) {
confl = true;
// System.out.println("confl: "+isl+" with: "+i+" : "+result.get(i));
break;
}
}
if(!confl)
result.add(isl);
else {
Island island1 = result.get(i);
if(island1.size()<=isl.size()) {
double dist_1_a = 0.0;
double dist_1_b = 0.0;
double dist_2_a = 0.0;
double dist_2_b = 0.0;
for(int j=0; j<i; j++) {
Island island2 = result.get(j);
double d = distance(island2,island1);
if(dist_1_a==0.0 || d < dist_1_a) {
dist_1_a = d;
} else if(dist_1_b==0.0 || d < dist_1_b) {
dist_1_b = d;
}
d = distance(island2,isl);
if(dist_2_a==0.0 || d < dist_2_a) {
dist_2_a = d;
} else if(dist_2_b==0.0 || d < dist_2_b) {
dist_2_b = d;
}
}
double tot_d_1 = dist_1_a + dist_1_b;
double tot_d_2 = dist_2_a + dist_2_b;
// System.out.println("tot_d_1: "+tot_d_1);
// System.out.println("tot_d_2: "+tot_d_2);
if(tot_d_2<tot_d_1) {
result.remove(i);
result.add(isl);
}
}
}
}
return result;
}
private double distance(Island isl1, Island isl2) {
double result = 0.0;
int isl1_L_x = isl1.getLeftEnd().col;
int isl1_L_y = isl1.getLeftEnd().row;
int isl1_R_x = isl1.getRightEnd().col;
int isl1_R_y = isl1.getRightEnd().row;
int isl2_L_x = isl2.getLeftEnd().col;
int isl2_L_y = isl2.getLeftEnd().row;
int isl2_R_x = isl2.getRightEnd().col;
int isl2_R_y = isl2.getRightEnd().row;
result = distance(isl1_L_x,isl1_L_y,isl2_L_x,isl2_L_y);
double d = distance(isl1_L_x,isl1_L_y,isl2_R_x,isl2_R_y);
if(d<result)
result = d;
d = distance(isl1_R_x,isl1_R_y,isl2_L_x,isl2_L_y);
if(d<result)
result = d;
d = distance(isl1_R_x,isl1_R_y,isl2_R_x,isl2_R_y);
if(d<result)
result = d;
return result;
}
private double distance(int a_x, int a_y, int b_x, int b_y) {
double result = 0.0;
result = Math.sqrt((a_x - b_x)*(a_x - b_x) + (a_y - b_y)*(a_y - b_y));
return result;
}
public String createXML(SparseMatrix mat, PrintWriter output) {
String result = "";
ArrayList<String> columnLabels = mat.columnLabels();
ArrayList<String> rowLabels = mat.rowLabels();
ArrayList<Coordinate> list = new ArrayList<Coordinate>();
int rowNum = rowLabels.size();
int colNum = columnLabels.size();
list.add(new Coordinate(0, 0));
list.add(new Coordinate(colNum-1, rowNum-1));
// System.out.println("1");
Archipelago createFirstVersion = createFirstVersion();
System.out.println("2: " + createFirstVersion);
// output.println(mat.toHtml(this));
output.println(mat.toHtml(createFirstVersion));
// System.out.println("3");
ArrayList<Coordinate> gaps = createFirstVersion.findGaps(list);
System.out.println("4");
ArrayList<Integer[]> listOrderedByCol = new ArrayList<Integer[]>();
int teller = 0;
Integer[] isl = {0,0,0,0,0};
for(Coordinate c : gaps) {
teller++;
if(teller%2==0) {
isl[0] = teller/2;
isl[3] = c.col;
isl[4] = c.row;
listOrderedByCol.add(isl.clone());
} else {
isl[1] = c.col;
isl[2] = c.row;
}
}
ArrayList<Integer[]> listOrderedByRow = new ArrayList<Integer[]>();
for(Integer[] a: listOrderedByCol) {
System.out.println(a[0]+": "+a[1]+"-"+a[2]);
boolean added = false;
for(int i=0; i<listOrderedByRow.size(); i++) {
Integer row_a = a[2];
Integer row_b = listOrderedByRow.get(i)[2];
if(row_a<row_b) {
listOrderedByRow.add(i, a);
added = true;
break;
}
}
if(!added) {
listOrderedByRow.add(a);
}
}
for(Integer[] a: listOrderedByRow) {
System.out.println(a[0]+": "+a[1]+"-"+a[2]);
}
int rowPos = 0;
int colPos = 0;
int gapsPos = 0;
output.println("<xml>");
result += "<xml>" + newLine;
String res = "";
/* inspecteer inhoud gaps */
teller = 0;
Coordinate vorige = new Coordinate(0,0);
for(Coordinate c : gaps) {
teller++;
if(teller%2==0) {
System.out.print(" " + c + " ");
for(int i = vorige.col; i<=c.col ; i++ )
System.out.print(" " + columnLabels.get(i));
System.out.println();
vorige = c;
} else {
// vergelijk c met vorige
if(c.col<vorige.col || c.row<vorige.row)
System.out.println("sprong");
System.out.print(c);
vorige = c;
}
}
// while(true) {
// /**
// * Hier anders aanpakken?
// * Bijv eerst de stukken tussen de eilanden simpel als varianten opvatten?
// * Probleem (bijvoorbeeld text 4): de eerste woorden in 'lem' matchen met
// * woorden veel verderop in de 'rdg' (en zijn geen echte match).
// * Dus proberen kijken of eerst de eilanden nogmaals gewaardeerd worden
// * om zo eilanden die niet in de 'archipel' passen er buiten te laten.
// */
// /** */
// int islStart = gaps.get(gapsPos).col;
// int islStartRow = gaps.get(gapsPos).row;
// int islEnd = gaps.get(gapsPos+1).col;
// if(colPos<islStart || rowPos<gaps.get(gapsPos).row) {
// String lem ="";
// String rdg = "";
// while(colPos<gaps.get(gapsPos).col)
// lem += columnLabels.get(colPos++) + " ";
// while(rowPos<gaps.get(gapsPos).row)
// rdg += rowLabels.get(rowPos++) + " ";
// result += printApp(output,lem, rdg);
// res = " ";
// }
// if(colPos==islStart && rowPos>islStartRow) {
// String lem ="";
// String rdg = "";
// while(colPos<gaps.get(gapsPos).col)
// lem += columnLabels.get(colPos++) + " ";
// result += printApp(output,lem, rdg);
// gapsPos += 2;
// } else {
// while(islStart<=islEnd)
// res += columnLabels.get(islStart++)+" ";
// output.println(res);
// if(!res.trim().isEmpty())
// result += res + newLine;
// res = "";
// colPos = gaps.get(gapsPos+1).col + 1;
// rowPos = gaps.get(gapsPos+1).row + 1;
// gapsPos += 2;
// }
// if(gapsPos>=gaps.size() || colPos==colNum)
// break;
// }
// String lem = "";
// while(colPos<colNum-1){
// lem += columnLabels.get(colPos) + " ";
// colPos++;
// }
// String rdg = "";
// while(rowPos<rowNum-1){
// rdg += rowLabels.get(rowPos) + " ";
// rowPos++;
// }
// if(!(lem.isEmpty() && rdg.isEmpty())) {
// result += printApp(output,lem,rdg);
// }
// output.println("</xml>");
// result += "</xml>";
return doeiets(output,listOrderedByCol,listOrderedByRow,columnLabels,rowLabels);
}
private String doeiets(PrintWriter output, ArrayList<Integer[]> listOrderedByCol,
ArrayList<Integer[]> listOrderedByRow, ArrayList<String> columnLabels,
ArrayList<String> rowLabels) {
String result = new String("<xml>\n");
int rowCount = 0;
int colCount = 0;
int lastCol = -1;
int lastRow = -1;
boolean sprong = false;
boolean finished = false;
while(!finished) {
System.out.println("col: "+colCount+" ("+drukAfArray(listOrderedByCol.get(colCount))+") - row: "+rowCount+" ("+drukAfArray(listOrderedByRow.get(rowCount))+")");
String lem = "";
String rdg = "";
if(colCount>lastCol) {
int a = -1;
try {
a = listOrderedByCol.get(lastCol)[3];
} catch(ArrayIndexOutOfBoundsException excep) { }
int b = listOrderedByCol.get(colCount)[1];
if((b-a)>1)
lem = getTekst(columnLabels,(a+1),(b-1));
lastCol = colCount;
}
if(rowCount>lastRow) {
int a = -1;
try {
a = listOrderedByRow.get(lastRow)[4];
} catch(ArrayIndexOutOfBoundsException excep) { }
int b = listOrderedByRow.get(rowCount)[2];
if((b-a)>1)
rdg = getTekst(rowLabels,(a+1),(b-1));
lastRow = rowCount;
}
String app = printApp(output, lem, rdg);
result += app;
System.out.println(app);
int colIslNo = listOrderedByCol.get(colCount)[0];
int rowIslNo = listOrderedByRow.get(rowCount)[0];
if(colIslNo==rowIslNo) {
String tekst = getTekst(columnLabels,listOrderedByCol.get(colCount)[1],listOrderedByCol.get(colCount)[3]);
result += tekst;
System.out.println(tekst);
output.println(tekst);
rowCount++;
colCount++;
} else if(colIslNo>rowIslNo) {
String message ="<!-- er is iets mis -->";
output.println(message);
result += message + "\n";
System.out.println("!!! colIslNo (" +colIslNo + ") > rowIslNo ("+ rowIslNo + ")");
lem = "";
rdg = "";
if(listOrderedByCol.get(colCount+1)[0]<colIslNo) {
lem = getTekst(columnLabels,listOrderedByCol.get(colCount)[1],listOrderedByCol.get(colCount)[3]);
rdg = "[VERPLAATST"+colIslNo+"]";
colCount++;
} else {
lem = "[VERPLAATST"+rowIslNo+"]";
rdg = getTekst(rowLabels,listOrderedByRow.get(rowCount)[2],listOrderedByRow.get(rowCount)[4]);
rowCount++;
}
app = printApp(output, lem, rdg);
result += app;
System.out.println(app);
} else if(colIslNo<rowIslNo) {
// System.out.println("colIslNo (" +colIslNo + ") < rowIslNo ("+ rowIslNo + ")");
lem = "";
rdg = "";
if((rowCount+1)< listOrderedByRow.size() && listOrderedByRow.get(rowCount+1)[0]<rowIslNo) {
lem = "[VERPLAATST"+rowIslNo+"]";
rdg = getTekst(rowLabels,listOrderedByRow.get(rowCount)[2],listOrderedByRow.get(rowCount)[4]);
rowCount++;
} else {
lem = getTekst(columnLabels,listOrderedByCol.get(colCount)[1],listOrderedByCol.get(colCount)[3]);
rdg = "[VERPLAATST"+colIslNo+"]";
colCount++;
}
app = printApp(output, lem, rdg);
result += app;
System.out.println(app);
}
// for(Integer[] a : listOrderedByCol) {
// if((a[0]-lastCol)>1)
// sprong = true;
// if(!sprong)
// while(listOrderedByRow.get(rowCount)[0]<a[0]) {
// rowCount++;
// }
// else {
// String lem = "";
// for(int i=a[1];i<=a[3];i++)
// lem += " " + columnLabels.get(i);
// result += printApp(output,lem,"[VERPLAATST?"+a[0]+"]");
// sprong = false;
// }
// }
if(rowCount>= listOrderedByRow.size() || colCount>=listOrderedByCol.size())
finished = true;
}
output.println("</xml>");
output.flush();
return result + "\n</xml>";
}
private String drukAfArray(Integer[] integers) {
String result = "[";
for(Integer i : integers) {
result += "," + i;
}
return result.replace("[,", "[") + "]";
}
private String getTekst(ArrayList<String> rowLabels, Integer start,
Integer einde) {
String result = "";
for(int i = start; i<=einde; i++) {
result += " " + rowLabels.get(i);
}
return result.trim();
}
private String printApp(PrintWriter output, String lem,String rdg) {
String result = "";
if(!(lem.isEmpty() && rdg.isEmpty())) {
if(lem.isEmpty())
lem = "[WEGGELATEN]";
if(rdg.isEmpty())
rdg = "[WEGGELATEN]";
result += "\n <app>"+ newLine;
result += " <lem>"+lem.trim()+"</lem>" + newLine;
result += " <rdg>"+rdg.trim()+"</rdg>" + newLine;
result += " </app>" + newLine;
output.print(result);
}
return result;
}
} | MKroese/microservices | collatex/src/main/java/eu/interedition/collatex/MatrixLinker/ArchipelagoWithVersions.java | 6,954 | // int tel_loop = 0;
| line_comment | nl | package eu.interedition.collatex.MatrixLinker;
import java.io.PrintWriter;
import java.util.ArrayList;
public class ArchipelagoWithVersions extends Archipelago {
private static final String newLine = System.getProperty("line.separator");
private ArrayList<Archipelago> nonConflVersions;
private Integer[] isl2;
public ArchipelagoWithVersions() {
islands = new ArrayList<Island>();
nonConflVersions = new ArrayList<Archipelago>();
}
public ArchipelagoWithVersions(Island isl) {
islands = new ArrayList<Island>();
nonConflVersions = new ArrayList<Archipelago>();
add(isl);
}
public void add(Island island) {
super.add(island);
}
public void createNonConflictingVersions() {
boolean debug = false;
// PrintWriter logging = null;
// File logFile = new File(File.separator + "c:\\logfile.txt");
// try {
// logging = new PrintWriter(new FileOutputStream(logFile));
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
nonConflVersions = new ArrayList<Archipelago>();
int tel = 0;
for(Island island : islands) {
tel++;
// if(tel>22)
debug = false;
// System.out.println("nonConflVersions.size(): "+nonConflVersions.size());
// int tel_version = 0;
// for(Archipelago arch : nonConflVersions) {
// System.out.println("arch version ("+(tel_version++)+"): " + arch);
// }
// TODO
// if(tel>22) {
// int tel_version = 0;
// for(Archipelago arch : nonConflVersions) {
// System.out.println("arch version ("+(tel_version++)+"): " + arch);
// }
// System.exit(1);
// }
if(nonConflVersions.size()==0) {
if(debug)
System.out.println("nonConflVersions.size()==0");
Archipelago version = new Archipelago();
version.add(island);
nonConflVersions.add(version);
} else {
boolean found_one = false;
ArrayList<Archipelago> new_versions = new ArrayList<Archipelago>();
int tel_loop = 0;
for(Archipelago version : nonConflVersions) {
if(debug)
System.out.println("loop 1: "+tel_loop++);
if(!version.conflictsWith(island)) {
if(debug)
System.out.println("!version.conflictsWith(island)");
version.add(island);
found_one = true;
}
}
if(!found_one) {
if(debug)
System.out.println("!found_one");
// try to find a existing version in which the new island fits
// after removing some points
tel_loop = 0;
for(Archipelago version : nonConflVersions) {
if(debug)
System.out.println("loop 2: "+tel_loop++);
Island island_copy = island.copy();
for(Island isl : version.iterator()) {
island_copy = island_copy.removePoints(isl);
}
if(island_copy.size()>0) {
version.add(island_copy);
found_one = true;
}
}
// create a new version with the new island and (parts of) existing islands
tel_loop = 0;
for(Archipelago version : nonConflVersions) {
if(debug)
System.out.println("loop 3: "+tel_loop++);
Archipelago new_version = new Archipelago();
new_version.add(island);
for(Island isl : version.iterator()) {
Island di = isl.copy();
if(debug)
System.out.println("di: "+di);
Island res = di.removePoints(island);
if(debug)
System.out.println("res: "+res);
if(res.size()>0) {
found_one = true;
new_version.add(res);
}
}
new_versions.add(new_version);
}
if(new_versions.size()>0) {
tel_loop = 0;
for(Archipelago arch : new_versions) {
if(debug)
System.out.println("loop 4: "+tel_loop++);
addVersion(arch);
}
}
}
if(!found_one) {
if(debug)
System.out.println("!found_one");
Archipelago version = new Archipelago();
version.add(island);
addVersion(version);
}
}
}
// int tel_version = 0;
// for(Archipelago arch : nonConflVersions) {
// logging.println("arch version ("+(tel_version++)+"): " + arch);
// }
// tel_version = 0;
// for(Archipelago arch : nonConflVersions) {
// logging.println("version "+(tel_version++)+": " + arch.value());
// }
// logging.close();
}
private void addVersion(Archipelago version) {
int pos = 0;
// int tel_loop<SUF>
// System.out.println("addVersion - num of versions: "+nonConflVersions.size());
for(pos = 0; pos<nonConflVersions.size(); pos++) {
if(version.equals(nonConflVersions.get(pos)))
return;
// System.out.println("loop 5: "+tel_loop++);
if(version.value()>nonConflVersions.get(pos).value()) {
nonConflVersions.add(pos,version);
return;
}
}
nonConflVersions.add(version);
}
public int numOfNonConflConstell() {
return nonConflVersions.size();
}
public ArchipelagoWithVersions copy() {
ArchipelagoWithVersions result = new ArchipelagoWithVersions();
for(Island isl: islands) {
result.add((Island) isl.copy());
}
return result;
}
public Archipelago getVersion(int i) {
try {
if(nonConflVersions.isEmpty())
createNonConflictingVersions();
return nonConflVersions.get(i);
} catch(IndexOutOfBoundsException exc) {
return null;
}
}
public ArrayList<Archipelago> getNonConflVersions() {
return nonConflVersions;
}
/*
* Create a non-conflicting version by simply taken all the islands
* that to not conflict with each other, largest first. This presuming
* that Archipelago will have a high value if it contains the largest
* possible islands
*/
public Archipelago createFirstVersion() {
Archipelago result = new Archipelago();
for(Island isl: islands) {
int i=0;
int res_size = result.size();
boolean confl = false;
for(i=0; i<res_size; i++) {
if(result.get(i).isCompetitor(isl)) {
confl = true;
// System.out.println("confl: "+isl+" with: "+i+" : "+result.get(i));
break;
}
}
if(!confl)
result.add(isl);
else {
Island island1 = result.get(i);
if(island1.size()<=isl.size()) {
double dist_1_a = 0.0;
double dist_1_b = 0.0;
double dist_2_a = 0.0;
double dist_2_b = 0.0;
for(int j=0; j<i; j++) {
Island island2 = result.get(j);
double d = distance(island2,island1);
if(dist_1_a==0.0 || d < dist_1_a) {
dist_1_a = d;
} else if(dist_1_b==0.0 || d < dist_1_b) {
dist_1_b = d;
}
d = distance(island2,isl);
if(dist_2_a==0.0 || d < dist_2_a) {
dist_2_a = d;
} else if(dist_2_b==0.0 || d < dist_2_b) {
dist_2_b = d;
}
}
double tot_d_1 = dist_1_a + dist_1_b;
double tot_d_2 = dist_2_a + dist_2_b;
// System.out.println("tot_d_1: "+tot_d_1);
// System.out.println("tot_d_2: "+tot_d_2);
if(tot_d_2<tot_d_1) {
result.remove(i);
result.add(isl);
}
}
}
}
return result;
}
private double distance(Island isl1, Island isl2) {
double result = 0.0;
int isl1_L_x = isl1.getLeftEnd().col;
int isl1_L_y = isl1.getLeftEnd().row;
int isl1_R_x = isl1.getRightEnd().col;
int isl1_R_y = isl1.getRightEnd().row;
int isl2_L_x = isl2.getLeftEnd().col;
int isl2_L_y = isl2.getLeftEnd().row;
int isl2_R_x = isl2.getRightEnd().col;
int isl2_R_y = isl2.getRightEnd().row;
result = distance(isl1_L_x,isl1_L_y,isl2_L_x,isl2_L_y);
double d = distance(isl1_L_x,isl1_L_y,isl2_R_x,isl2_R_y);
if(d<result)
result = d;
d = distance(isl1_R_x,isl1_R_y,isl2_L_x,isl2_L_y);
if(d<result)
result = d;
d = distance(isl1_R_x,isl1_R_y,isl2_R_x,isl2_R_y);
if(d<result)
result = d;
return result;
}
private double distance(int a_x, int a_y, int b_x, int b_y) {
double result = 0.0;
result = Math.sqrt((a_x - b_x)*(a_x - b_x) + (a_y - b_y)*(a_y - b_y));
return result;
}
public String createXML(SparseMatrix mat, PrintWriter output) {
String result = "";
ArrayList<String> columnLabels = mat.columnLabels();
ArrayList<String> rowLabels = mat.rowLabels();
ArrayList<Coordinate> list = new ArrayList<Coordinate>();
int rowNum = rowLabels.size();
int colNum = columnLabels.size();
list.add(new Coordinate(0, 0));
list.add(new Coordinate(colNum-1, rowNum-1));
// System.out.println("1");
Archipelago createFirstVersion = createFirstVersion();
System.out.println("2: " + createFirstVersion);
// output.println(mat.toHtml(this));
output.println(mat.toHtml(createFirstVersion));
// System.out.println("3");
ArrayList<Coordinate> gaps = createFirstVersion.findGaps(list);
System.out.println("4");
ArrayList<Integer[]> listOrderedByCol = new ArrayList<Integer[]>();
int teller = 0;
Integer[] isl = {0,0,0,0,0};
for(Coordinate c : gaps) {
teller++;
if(teller%2==0) {
isl[0] = teller/2;
isl[3] = c.col;
isl[4] = c.row;
listOrderedByCol.add(isl.clone());
} else {
isl[1] = c.col;
isl[2] = c.row;
}
}
ArrayList<Integer[]> listOrderedByRow = new ArrayList<Integer[]>();
for(Integer[] a: listOrderedByCol) {
System.out.println(a[0]+": "+a[1]+"-"+a[2]);
boolean added = false;
for(int i=0; i<listOrderedByRow.size(); i++) {
Integer row_a = a[2];
Integer row_b = listOrderedByRow.get(i)[2];
if(row_a<row_b) {
listOrderedByRow.add(i, a);
added = true;
break;
}
}
if(!added) {
listOrderedByRow.add(a);
}
}
for(Integer[] a: listOrderedByRow) {
System.out.println(a[0]+": "+a[1]+"-"+a[2]);
}
int rowPos = 0;
int colPos = 0;
int gapsPos = 0;
output.println("<xml>");
result += "<xml>" + newLine;
String res = "";
/* inspecteer inhoud gaps */
teller = 0;
Coordinate vorige = new Coordinate(0,0);
for(Coordinate c : gaps) {
teller++;
if(teller%2==0) {
System.out.print(" " + c + " ");
for(int i = vorige.col; i<=c.col ; i++ )
System.out.print(" " + columnLabels.get(i));
System.out.println();
vorige = c;
} else {
// vergelijk c met vorige
if(c.col<vorige.col || c.row<vorige.row)
System.out.println("sprong");
System.out.print(c);
vorige = c;
}
}
// while(true) {
// /**
// * Hier anders aanpakken?
// * Bijv eerst de stukken tussen de eilanden simpel als varianten opvatten?
// * Probleem (bijvoorbeeld text 4): de eerste woorden in 'lem' matchen met
// * woorden veel verderop in de 'rdg' (en zijn geen echte match).
// * Dus proberen kijken of eerst de eilanden nogmaals gewaardeerd worden
// * om zo eilanden die niet in de 'archipel' passen er buiten te laten.
// */
// /** */
// int islStart = gaps.get(gapsPos).col;
// int islStartRow = gaps.get(gapsPos).row;
// int islEnd = gaps.get(gapsPos+1).col;
// if(colPos<islStart || rowPos<gaps.get(gapsPos).row) {
// String lem ="";
// String rdg = "";
// while(colPos<gaps.get(gapsPos).col)
// lem += columnLabels.get(colPos++) + " ";
// while(rowPos<gaps.get(gapsPos).row)
// rdg += rowLabels.get(rowPos++) + " ";
// result += printApp(output,lem, rdg);
// res = " ";
// }
// if(colPos==islStart && rowPos>islStartRow) {
// String lem ="";
// String rdg = "";
// while(colPos<gaps.get(gapsPos).col)
// lem += columnLabels.get(colPos++) + " ";
// result += printApp(output,lem, rdg);
// gapsPos += 2;
// } else {
// while(islStart<=islEnd)
// res += columnLabels.get(islStart++)+" ";
// output.println(res);
// if(!res.trim().isEmpty())
// result += res + newLine;
// res = "";
// colPos = gaps.get(gapsPos+1).col + 1;
// rowPos = gaps.get(gapsPos+1).row + 1;
// gapsPos += 2;
// }
// if(gapsPos>=gaps.size() || colPos==colNum)
// break;
// }
// String lem = "";
// while(colPos<colNum-1){
// lem += columnLabels.get(colPos) + " ";
// colPos++;
// }
// String rdg = "";
// while(rowPos<rowNum-1){
// rdg += rowLabels.get(rowPos) + " ";
// rowPos++;
// }
// if(!(lem.isEmpty() && rdg.isEmpty())) {
// result += printApp(output,lem,rdg);
// }
// output.println("</xml>");
// result += "</xml>";
return doeiets(output,listOrderedByCol,listOrderedByRow,columnLabels,rowLabels);
}
private String doeiets(PrintWriter output, ArrayList<Integer[]> listOrderedByCol,
ArrayList<Integer[]> listOrderedByRow, ArrayList<String> columnLabels,
ArrayList<String> rowLabels) {
String result = new String("<xml>\n");
int rowCount = 0;
int colCount = 0;
int lastCol = -1;
int lastRow = -1;
boolean sprong = false;
boolean finished = false;
while(!finished) {
System.out.println("col: "+colCount+" ("+drukAfArray(listOrderedByCol.get(colCount))+") - row: "+rowCount+" ("+drukAfArray(listOrderedByRow.get(rowCount))+")");
String lem = "";
String rdg = "";
if(colCount>lastCol) {
int a = -1;
try {
a = listOrderedByCol.get(lastCol)[3];
} catch(ArrayIndexOutOfBoundsException excep) { }
int b = listOrderedByCol.get(colCount)[1];
if((b-a)>1)
lem = getTekst(columnLabels,(a+1),(b-1));
lastCol = colCount;
}
if(rowCount>lastRow) {
int a = -1;
try {
a = listOrderedByRow.get(lastRow)[4];
} catch(ArrayIndexOutOfBoundsException excep) { }
int b = listOrderedByRow.get(rowCount)[2];
if((b-a)>1)
rdg = getTekst(rowLabels,(a+1),(b-1));
lastRow = rowCount;
}
String app = printApp(output, lem, rdg);
result += app;
System.out.println(app);
int colIslNo = listOrderedByCol.get(colCount)[0];
int rowIslNo = listOrderedByRow.get(rowCount)[0];
if(colIslNo==rowIslNo) {
String tekst = getTekst(columnLabels,listOrderedByCol.get(colCount)[1],listOrderedByCol.get(colCount)[3]);
result += tekst;
System.out.println(tekst);
output.println(tekst);
rowCount++;
colCount++;
} else if(colIslNo>rowIslNo) {
String message ="<!-- er is iets mis -->";
output.println(message);
result += message + "\n";
System.out.println("!!! colIslNo (" +colIslNo + ") > rowIslNo ("+ rowIslNo + ")");
lem = "";
rdg = "";
if(listOrderedByCol.get(colCount+1)[0]<colIslNo) {
lem = getTekst(columnLabels,listOrderedByCol.get(colCount)[1],listOrderedByCol.get(colCount)[3]);
rdg = "[VERPLAATST"+colIslNo+"]";
colCount++;
} else {
lem = "[VERPLAATST"+rowIslNo+"]";
rdg = getTekst(rowLabels,listOrderedByRow.get(rowCount)[2],listOrderedByRow.get(rowCount)[4]);
rowCount++;
}
app = printApp(output, lem, rdg);
result += app;
System.out.println(app);
} else if(colIslNo<rowIslNo) {
// System.out.println("colIslNo (" +colIslNo + ") < rowIslNo ("+ rowIslNo + ")");
lem = "";
rdg = "";
if((rowCount+1)< listOrderedByRow.size() && listOrderedByRow.get(rowCount+1)[0]<rowIslNo) {
lem = "[VERPLAATST"+rowIslNo+"]";
rdg = getTekst(rowLabels,listOrderedByRow.get(rowCount)[2],listOrderedByRow.get(rowCount)[4]);
rowCount++;
} else {
lem = getTekst(columnLabels,listOrderedByCol.get(colCount)[1],listOrderedByCol.get(colCount)[3]);
rdg = "[VERPLAATST"+colIslNo+"]";
colCount++;
}
app = printApp(output, lem, rdg);
result += app;
System.out.println(app);
}
// for(Integer[] a : listOrderedByCol) {
// if((a[0]-lastCol)>1)
// sprong = true;
// if(!sprong)
// while(listOrderedByRow.get(rowCount)[0]<a[0]) {
// rowCount++;
// }
// else {
// String lem = "";
// for(int i=a[1];i<=a[3];i++)
// lem += " " + columnLabels.get(i);
// result += printApp(output,lem,"[VERPLAATST?"+a[0]+"]");
// sprong = false;
// }
// }
if(rowCount>= listOrderedByRow.size() || colCount>=listOrderedByCol.size())
finished = true;
}
output.println("</xml>");
output.flush();
return result + "\n</xml>";
}
private String drukAfArray(Integer[] integers) {
String result = "[";
for(Integer i : integers) {
result += "," + i;
}
return result.replace("[,", "[") + "]";
}
private String getTekst(ArrayList<String> rowLabels, Integer start,
Integer einde) {
String result = "";
for(int i = start; i<=einde; i++) {
result += " " + rowLabels.get(i);
}
return result.trim();
}
private String printApp(PrintWriter output, String lem,String rdg) {
String result = "";
if(!(lem.isEmpty() && rdg.isEmpty())) {
if(lem.isEmpty())
lem = "[WEGGELATEN]";
if(rdg.isEmpty())
rdg = "[WEGGELATEN]";
result += "\n <app>"+ newLine;
result += " <lem>"+lem.trim()+"</lem>" + newLine;
result += " <rdg>"+rdg.trim()+"</rdg>" + newLine;
result += " </app>" + newLine;
output.print(result);
}
return result;
}
} |
170389_3 | package sociedad;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.Map;
import java.util.HashMap;
public class Sociedad {
private Map<String, Set<Socio>> membersInActivities;
private Set<Socio> membersNotInActivities;
public Sociedad() {
membersInActivities = new HashMap<>();
membersNotInActivities = new HashSet<>();
}
public void leerDeFichero(String filePath) {
try {
List<String> linesInFile = Files.readAllLines(Path.of(filePath));
for (String line : linesInFile) {
try {
String[] lineSp = line.split("%");
if (lineSp.length == 3) {
String name = lineSp[0];
Set<String> sInt = new HashSet<>();
try (Scanner intSc = new Scanner(lineSp[1])) {
intSc.useDelimiter(",");
while (intSc.hasNext()) {
sInt.add(intSc.next());
}
}
int id = Integer.parseInt(lineSp[2]);
nuevoSocio(new Socio(name, sInt, id));
}
}catch(Exception e) {
// ignore line and keep processing the rest of the file
}
}
} catch (IOException e) {
throw new SociedadException("IOException " + e.getMessage() +
" al leer del fichero " + filePath);
}
}
public void nuevoSocio(Socio m){
Set<String> activities = membersInActivities.keySet();
Iterator<String> iterAct = activities.iterator();
boolean found = false;
while(!found && iterAct.hasNext()) {
found = membersInActivities.get(iterAct.next()).contains(m);
}
if (!found && !membersNotInActivities.contains(m)) {
membersNotInActivities.add(m);
}
}
/**
*
* Eliminado del examen porque era demasiado largo
*
*/
// public int inscritos() {
// int enr = 0;
// for (Set<Socio> sm : membersInActivities.values()) {
// enr += sm.size();
// }
// return enr;
// }
public Set<Socio> inscritos(String activity) {
return membersInActivities.get(activity.toLowerCase());
}
/**
*
* Eliminado del examen porque era demasiado largo
*
*/
// public Set<Socio> sociosInteresados(String interest){
// Set<Socio>interestedInActivity = new HashSet<Socio>();
// for (Socio m : membersNotInActivities) {
// if (m.getIntereses().contains(interest.toLowerCase())) {
// interestedInActivity.add(m);
// }
// }
// return interestedInActivity;
// }
protected Socio buscarSocioEnConjunto(Socio m, Set<Socio> sm) {
boolean found = false;
Socio presentMember = null;
if(sm != null) {
Iterator<Socio> itMem = sm.iterator();
while(!found && itMem.hasNext()) {
presentMember = itMem.next();
if(presentMember.equals(m)) {
found = true;
}
}
}
return found?presentMember:null;
}
public void inscribir (String nombre, int id, String activity) {
Socio m = new Socio(nombre, new HashSet<>(), id);
if (membersNotInActivities.contains(m)) {
Socio miembroBase = buscarSocioEnConjunto(m, membersNotInActivities);
membersNotInActivities.remove(miembroBase);
Set<Socio> sm = membersInActivities.get(activity.toLowerCase());
if (sm == null) {
sm = new HashSet<Socio>();
membersInActivities.put(activity.toLowerCase(), sm);
}
sm.add(miembroBase);
}
}
/**
*
* Eliminado del examen porque era demasiado largo
*
*/
// public void anularInscripcion (String nombre, int id, String activity) {
// Socio m = new Socio(nombre, new HashSet<>(), id);
// Set<Socio> sm = membersInActivities.get(activity.toLowerCase());
// if (sm != null && sm.contains(m)) {
// Socio localMember = buscarSocioEnConjunto(m, sm);
// sm.remove(localMember);
// membersNotInActivities.add(localMember);
// }
// }
public void guardarSocios(String filePath) {
try (PrintWriter pw = new PrintWriter(filePath)) {
guardarSocios(pw);
} catch (FileNotFoundException e) {
throw new SociedadException("No encontrado fichero " + filePath + ".");
}
}
public void guardarSocios(PrintWriter pw) {
for (Socio m : membersNotInActivities) {
pw.println(m.toString());
}
pw.flush();
}
}
| MLSMoles/OOP-JavaPrac- | prSociedadRecreativa-2/src/sociedad/Sociedad.java | 1,535 | // int enr = 0; | line_comment | nl | package sociedad;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.Map;
import java.util.HashMap;
public class Sociedad {
private Map<String, Set<Socio>> membersInActivities;
private Set<Socio> membersNotInActivities;
public Sociedad() {
membersInActivities = new HashMap<>();
membersNotInActivities = new HashSet<>();
}
public void leerDeFichero(String filePath) {
try {
List<String> linesInFile = Files.readAllLines(Path.of(filePath));
for (String line : linesInFile) {
try {
String[] lineSp = line.split("%");
if (lineSp.length == 3) {
String name = lineSp[0];
Set<String> sInt = new HashSet<>();
try (Scanner intSc = new Scanner(lineSp[1])) {
intSc.useDelimiter(",");
while (intSc.hasNext()) {
sInt.add(intSc.next());
}
}
int id = Integer.parseInt(lineSp[2]);
nuevoSocio(new Socio(name, sInt, id));
}
}catch(Exception e) {
// ignore line and keep processing the rest of the file
}
}
} catch (IOException e) {
throw new SociedadException("IOException " + e.getMessage() +
" al leer del fichero " + filePath);
}
}
public void nuevoSocio(Socio m){
Set<String> activities = membersInActivities.keySet();
Iterator<String> iterAct = activities.iterator();
boolean found = false;
while(!found && iterAct.hasNext()) {
found = membersInActivities.get(iterAct.next()).contains(m);
}
if (!found && !membersNotInActivities.contains(m)) {
membersNotInActivities.add(m);
}
}
/**
*
* Eliminado del examen porque era demasiado largo
*
*/
// public int inscritos() {
// int enr<SUF>
// for (Set<Socio> sm : membersInActivities.values()) {
// enr += sm.size();
// }
// return enr;
// }
public Set<Socio> inscritos(String activity) {
return membersInActivities.get(activity.toLowerCase());
}
/**
*
* Eliminado del examen porque era demasiado largo
*
*/
// public Set<Socio> sociosInteresados(String interest){
// Set<Socio>interestedInActivity = new HashSet<Socio>();
// for (Socio m : membersNotInActivities) {
// if (m.getIntereses().contains(interest.toLowerCase())) {
// interestedInActivity.add(m);
// }
// }
// return interestedInActivity;
// }
protected Socio buscarSocioEnConjunto(Socio m, Set<Socio> sm) {
boolean found = false;
Socio presentMember = null;
if(sm != null) {
Iterator<Socio> itMem = sm.iterator();
while(!found && itMem.hasNext()) {
presentMember = itMem.next();
if(presentMember.equals(m)) {
found = true;
}
}
}
return found?presentMember:null;
}
public void inscribir (String nombre, int id, String activity) {
Socio m = new Socio(nombre, new HashSet<>(), id);
if (membersNotInActivities.contains(m)) {
Socio miembroBase = buscarSocioEnConjunto(m, membersNotInActivities);
membersNotInActivities.remove(miembroBase);
Set<Socio> sm = membersInActivities.get(activity.toLowerCase());
if (sm == null) {
sm = new HashSet<Socio>();
membersInActivities.put(activity.toLowerCase(), sm);
}
sm.add(miembroBase);
}
}
/**
*
* Eliminado del examen porque era demasiado largo
*
*/
// public void anularInscripcion (String nombre, int id, String activity) {
// Socio m = new Socio(nombre, new HashSet<>(), id);
// Set<Socio> sm = membersInActivities.get(activity.toLowerCase());
// if (sm != null && sm.contains(m)) {
// Socio localMember = buscarSocioEnConjunto(m, sm);
// sm.remove(localMember);
// membersNotInActivities.add(localMember);
// }
// }
public void guardarSocios(String filePath) {
try (PrintWriter pw = new PrintWriter(filePath)) {
guardarSocios(pw);
} catch (FileNotFoundException e) {
throw new SociedadException("No encontrado fichero " + filePath + ".");
}
}
public void guardarSocios(PrintWriter pw) {
for (Socio m : membersNotInActivities) {
pw.println(m.toString());
}
pw.flush();
}
}
|
119267_19 | package com.molvenolakeresort.hotel.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.molvenolakeresort.hotel.model.Guest;
import com.molvenolakeresort.hotel.repository.GuestRepository;
import org.jboss.jandex.JandexAntTask;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static org.hamcrest.Matchers.any;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(MockitoJUnitRunner.class)
@SpringBootTest
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@AutoConfigureMockMvc
public class GuestControllerTest {
@InjectMocks
private GuestController guestController;
@Mock
private GuestRepository guestRepository;
private MockMvc mockMvc;
private Guest guest;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(guestController).build();
}
@Test
public void testGetGuestList() throws Exception {
List<Guest> guests = new ArrayList<>();
guests.add(new Guest("Piet"));
guests.add(new Guest("Klaas"));
when(guestRepository.findAll()).thenReturn(guests);
this.mockMvc.perform(MockMvcRequestBuilders.get("/api/guests"))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.jsonPath("$", hasSize(2)))
.andExpect(MockMvcResultMatchers.jsonPath("$.[0].name").value(guests.get(0).getName()))
.andExpect(MockMvcResultMatchers.status().isOk());
}
@Test
public void testGetGuestById() throws Exception {
// List<Guest> guests = new ArrayList<>();
Guest guest = new Guest("Piet");
guest.setId(1);
when(guestRepository.findById((long)1)).thenReturn(Optional.of(guest));
this.mockMvc.perform(MockMvcRequestBuilders.get("/api/guests/1"))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.jsonPath("$.name").value(guest.getName()))
.andExpect(MockMvcResultMatchers.status().isOk());
}
@Test
public void addGuestTest() throws Exception {
Guest newGuest = new Guest("Piet");
when(guestRepository.save(ArgumentMatchers.any(Guest.class))).thenReturn(newGuest);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(newGuest);
this.mockMvc.perform(MockMvcRequestBuilders.post("/api/guests")
.contentType(MediaType.APPLICATION_JSON)
.content(json))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.jsonPath("$.name").value(newGuest.getName()))
.andExpect(MockMvcResultMatchers.status().isOk());
}
// GuestController guestController;
// Iterable<Guest> guestList = guestController.findAll();
//
// @BeforeEach
// void init() {
// guestController = new GuestController();
//
//// TEST GUEST LIST :
// guestController.postGuest(new Guest("Jan Janssen"));
// guestController.postGuest(new Guest("Alice"));
// guestController.postGuest(new Guest("Bob"));
// }
//
// @Test
// void findById() throws EntityNotFoundException {
// // Gastinformatie ophalen:
// System.out.println("Informatie wordt opgehaald van guest met ID number 1...\n");
// Guest guest;
// guest = guestController.findById(1).getBody();
// System.out.println("Gastinformatie: \nNaam: " + guest.getName() + "\nGeboortedatum: " + guest.getBirthDate() + "\nStad: " + guest.getCity() + "\nBoekingen: " + guest.getBookings().toArray().length);
//
// assertEquals("Jane Doe", guestController.findById(3).getBody().getName());
// }
//
// @Test
// void getGuestList() {
// System.out.println("Gastenlijst wordt opgehaald...");
// for (Guest guest : guestList) {
// System.out.println(guest.getId() + ". " + guest.getName() + ", " + guest.getCity() + ", " + guest.getBookings().toArray().length + " boekingen.");
// }
// List<Guest> newList = ((List<Guest>)guestList);
// assertEquals();
// }
//
// @Test
// void postGuest() {
// try {
// System.out.println("Registreer nieuwe gast: Jane Appleseed, geboren in 2002, afkomstig uit New York. \n");
// guestController.postGuest(new Guest("Jane Appleseed", "January 24th, 2002", "[email protected]", "0316 - 23454321", "AB1234DE", "Chicago Street", "New York"));
//
// System.out.print("Nieuwe gast geregistreerd. ");
//// Guest guest = guestController.getGuest(4);
//// System.out.println("Gastinformatie: \nNaam: " + guest.getName() + "\nGeboortedatum: " + guest.getBirthDate() + "\nStad: " + guest.getCity() + "\nBoekingen: " + guest.getBookings().length);
//// System.out.println(guestController.getGuest(4).toString());
//
// System.out.println("\nNieuwe gastenlijst:");
//// for (Guest guestIterator : guestController.getGuestList()) {
//// System.out.println(guestIterator.getId() + ". " + guestIterator.getName() + ", " + guestIterator.getCity() + ", " + guestIterator.getBookings().length + " boekingen.");
//// }
//// assertEquals("Jane Appleseed", guestController.getGuestList().get(3).getName());
//// } catch (EntityNotFoundException e) {
//// assertEquals(e.toString(),"");
//// }
//// }
//
// @Test
// void putGuest() {
// try {
// System.out.println("Current guest (ID no. 2):");
// System.out.println(guestController.getGuest(2).toString());
// System.out.println("\nUpdating guest and requesting new information...\n");
//
// guestController.putGuest(2,"Alice Smith", "February 20th, 1990", "[email protected]", "031-12345678", "", "Veemarkt 1, 5678 CD", "");
// System.out.println("\n" + guestController.getGuest(2).toString());
//
// assertEquals(guestController.getGuest(2).getName(), "Alice Smith");
//
// } catch (EntityNotFoundException e) {
// assertEquals(e.toString(), "");
// }
// }
//
// @Test
// void deleteGuest() {
// try {
// System.out.println("Guest to be deleted (ID no. 3):");
// System.out.println(guestController.getGuest(3).toString());
//
// System.out.println("\nDeleting guest... Requesting guest information again: ");
// guestController.deleteGuest(3);
// System.out.println(guestController.getGuest(3).toString());
//
// } catch (EntityNotFoundException e) {
// System.out.println(e);
// assertEquals("com.molvenolakeresort.hotel.controller.EntityNotFoundException: Guest was not found for ID: 3",e.toString());
// }
//
// }
}
| MNalbant1/Molveno-Lake-Resort | src/test/java/com/molvenolakeresort/hotel/controller/GuestControllerTest.java | 2,498 | // System.out.print("Nieuwe gast geregistreerd. "); | line_comment | nl | package com.molvenolakeresort.hotel.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.molvenolakeresort.hotel.model.Guest;
import com.molvenolakeresort.hotel.repository.GuestRepository;
import org.jboss.jandex.JandexAntTask;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static org.hamcrest.Matchers.any;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(MockitoJUnitRunner.class)
@SpringBootTest
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@AutoConfigureMockMvc
public class GuestControllerTest {
@InjectMocks
private GuestController guestController;
@Mock
private GuestRepository guestRepository;
private MockMvc mockMvc;
private Guest guest;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(guestController).build();
}
@Test
public void testGetGuestList() throws Exception {
List<Guest> guests = new ArrayList<>();
guests.add(new Guest("Piet"));
guests.add(new Guest("Klaas"));
when(guestRepository.findAll()).thenReturn(guests);
this.mockMvc.perform(MockMvcRequestBuilders.get("/api/guests"))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.jsonPath("$", hasSize(2)))
.andExpect(MockMvcResultMatchers.jsonPath("$.[0].name").value(guests.get(0).getName()))
.andExpect(MockMvcResultMatchers.status().isOk());
}
@Test
public void testGetGuestById() throws Exception {
// List<Guest> guests = new ArrayList<>();
Guest guest = new Guest("Piet");
guest.setId(1);
when(guestRepository.findById((long)1)).thenReturn(Optional.of(guest));
this.mockMvc.perform(MockMvcRequestBuilders.get("/api/guests/1"))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.jsonPath("$.name").value(guest.getName()))
.andExpect(MockMvcResultMatchers.status().isOk());
}
@Test
public void addGuestTest() throws Exception {
Guest newGuest = new Guest("Piet");
when(guestRepository.save(ArgumentMatchers.any(Guest.class))).thenReturn(newGuest);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(newGuest);
this.mockMvc.perform(MockMvcRequestBuilders.post("/api/guests")
.contentType(MediaType.APPLICATION_JSON)
.content(json))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.jsonPath("$.name").value(newGuest.getName()))
.andExpect(MockMvcResultMatchers.status().isOk());
}
// GuestController guestController;
// Iterable<Guest> guestList = guestController.findAll();
//
// @BeforeEach
// void init() {
// guestController = new GuestController();
//
//// TEST GUEST LIST :
// guestController.postGuest(new Guest("Jan Janssen"));
// guestController.postGuest(new Guest("Alice"));
// guestController.postGuest(new Guest("Bob"));
// }
//
// @Test
// void findById() throws EntityNotFoundException {
// // Gastinformatie ophalen:
// System.out.println("Informatie wordt opgehaald van guest met ID number 1...\n");
// Guest guest;
// guest = guestController.findById(1).getBody();
// System.out.println("Gastinformatie: \nNaam: " + guest.getName() + "\nGeboortedatum: " + guest.getBirthDate() + "\nStad: " + guest.getCity() + "\nBoekingen: " + guest.getBookings().toArray().length);
//
// assertEquals("Jane Doe", guestController.findById(3).getBody().getName());
// }
//
// @Test
// void getGuestList() {
// System.out.println("Gastenlijst wordt opgehaald...");
// for (Guest guest : guestList) {
// System.out.println(guest.getId() + ". " + guest.getName() + ", " + guest.getCity() + ", " + guest.getBookings().toArray().length + " boekingen.");
// }
// List<Guest> newList = ((List<Guest>)guestList);
// assertEquals();
// }
//
// @Test
// void postGuest() {
// try {
// System.out.println("Registreer nieuwe gast: Jane Appleseed, geboren in 2002, afkomstig uit New York. \n");
// guestController.postGuest(new Guest("Jane Appleseed", "January 24th, 2002", "[email protected]", "0316 - 23454321", "AB1234DE", "Chicago Street", "New York"));
//
// System.out.print("Nieuwe gast<SUF>
//// Guest guest = guestController.getGuest(4);
//// System.out.println("Gastinformatie: \nNaam: " + guest.getName() + "\nGeboortedatum: " + guest.getBirthDate() + "\nStad: " + guest.getCity() + "\nBoekingen: " + guest.getBookings().length);
//// System.out.println(guestController.getGuest(4).toString());
//
// System.out.println("\nNieuwe gastenlijst:");
//// for (Guest guestIterator : guestController.getGuestList()) {
//// System.out.println(guestIterator.getId() + ". " + guestIterator.getName() + ", " + guestIterator.getCity() + ", " + guestIterator.getBookings().length + " boekingen.");
//// }
//// assertEquals("Jane Appleseed", guestController.getGuestList().get(3).getName());
//// } catch (EntityNotFoundException e) {
//// assertEquals(e.toString(),"");
//// }
//// }
//
// @Test
// void putGuest() {
// try {
// System.out.println("Current guest (ID no. 2):");
// System.out.println(guestController.getGuest(2).toString());
// System.out.println("\nUpdating guest and requesting new information...\n");
//
// guestController.putGuest(2,"Alice Smith", "February 20th, 1990", "[email protected]", "031-12345678", "", "Veemarkt 1, 5678 CD", "");
// System.out.println("\n" + guestController.getGuest(2).toString());
//
// assertEquals(guestController.getGuest(2).getName(), "Alice Smith");
//
// } catch (EntityNotFoundException e) {
// assertEquals(e.toString(), "");
// }
// }
//
// @Test
// void deleteGuest() {
// try {
// System.out.println("Guest to be deleted (ID no. 3):");
// System.out.println(guestController.getGuest(3).toString());
//
// System.out.println("\nDeleting guest... Requesting guest information again: ");
// guestController.deleteGuest(3);
// System.out.println(guestController.getGuest(3).toString());
//
// } catch (EntityNotFoundException e) {
// System.out.println(e);
// assertEquals("com.molvenolakeresort.hotel.controller.EntityNotFoundException: Guest was not found for ID: 3",e.toString());
// }
//
// }
}
|
17161_14 | /*
* Copyright (C) 2016 Max Planck Institute for Psycholinguistics
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package nl.mpi.tg.eg.experimentdesigner.util;
import nl.mpi.tg.eg.experimentdesigner.controller.WizardController;
import nl.mpi.tg.eg.experimentdesigner.model.Experiment;
import nl.mpi.tg.eg.experimentdesigner.model.WizardData;
import nl.mpi.tg.eg.experimentdesigner.model.wizard.WizardAboutScreen;
import nl.mpi.tg.eg.experimentdesigner.model.wizard.WizardAgreementScreen;
import nl.mpi.tg.eg.experimentdesigner.model.wizard.WizardAudioTestScreen;
import nl.mpi.tg.eg.experimentdesigner.model.wizard.WizardCompletionScreen;
import nl.mpi.tg.eg.experimentdesigner.model.wizard.WizardEditUserScreen;
import nl.mpi.tg.eg.experimentdesigner.model.wizard.WizardTextScreen;
import nl.mpi.tg.eg.experimentdesigner.model.wizard.WizardVideoAudioOptionStimulusScreen;
/**
* @since Jun 6, 2016 11:41:41 AM (creation date)
* @author Peter Withers <[email protected]>
*/
public class HRPretest {
// @done: add a worker id entry befor the agree screen
// @done: shift the audio test to InformationScreen1
// @done: make the next button appear only after the audio has played
// @done: remove the Edit_User screen
// @done: add the stimuli counter 1/10 at the top of the screen
// @done: run the stimuli twice and a fresh randomisation for each run
// @todo: participant.csv is missing the UUID
// @todo: add a csv that has a row for each stimuli and the metadata of the user on each row
// @done: remove the restart button
private final WizardController wizardController = new WizardController();
protected boolean showRatingAfterStimuliResponse = false;
protected String getExperimentName() {
return "HRPretest";
}
final String agreementScreenText = "Alvast bedankt voor uw interesse in dit online-experiment! Gedetailleerde instructies over de taak worden op de volgende pagina gegeven. <br/>"
+ "<br/>"
+ "Voordat u begint, dient u eerst te bevestigen dat u toestemt met deelname aan dit experiment. Let erop dat we uw antwoorden opslaan voor latere analyse. We gebruiken de resultaten alleen voor onderzoeksdoeleinden, en zullen ze beschrijven in gespecialiseerde tijdschriften of wellicht in kranten of op onze website. Echter, we zullen de resultaten NOOIT rapporteren op zo'n manier dat u zou kunnen worden geïdentificeerd. <br/>"
+ "<br/>"
+ "U bent tijdens dit experiment op elk moment vrij om de taak af te breken zonder uitleg te geven. Ook kunt u uw gegevens laten verwijderen tot het moment van publicatie, zonder uit te leggen waarom u dat doet. <br/>"
+ "<br/>"
+ "Er zijn geen risico's bekend van het meedoen aan dit experiment. <br/>"
+ "<br/>"
+ "Als u ermee instemt om door te gaan met dit experiment, klikt u op 'Ik ga akkoord'. Als u besluit niet deel te nemen aan het experiment, klikt u op 'Ik ga niet akkoord'. Verlaat het experiment door naar een andere website te gaan of de pagina af te sluiten."
+ "<br/>";
final String informationScreenText1 = "Dit online experiment is een luisterexperiment. Daarom vragen we je nu de geluidsinstellingen van je computersysteem te testen door op de grote ronde knop hieronder te klikken.<br/>"
+ "<br/>"
+ "<b>Hoor je geen geluid?</b> Dan is er iets mis met je huidige geluidsinstellingen. Pas deze zelf aan en probeer het nogmaals.<br/>"
+ "<br/>"
+ "<b>Hoor je een geluid?</b> Dan staan je geluidsinstellingen goed ingesteld. Stel zelf het volume van je computersysteem in op een comfortabel niveau.<br/>"
+ "<br/>"
+ "----------------------------------------------------------------<br/>"
+ "LET OP: Doe dit experiment ALLEEN als je in een rustige omgeving zit zonder achtergrondgeluid. Dit is heel belangrijk!<br/>"
+ "----------------------------------------------------------------<br/>"
+ "<br/>"
+ "<br/>"
+ "<br/>"
+ "[Druk pas op VOLGENDE als de geluidsinstellingen goed zijn...]";
protected String informationScreenText2() {
return "Dit online experiment is een luisterexperiment. Je krijgt telkens een woord te horen dat ofwel een <b>a-klinker</b> bevat (bijv. dan) ofwel een <b>aa-klinker</b> bevat (bijv. Daan). Jouw taak is om aan te geven welk woord je hoort.<br/>"
+ "<br/>"
+ "Bijvoorbeeld:<br/>"
+ "Je hoort het woord [bas] en daarna verschijnen er twee namen op het scherm:<br/>"
+ "links staat “bas” en rechts staat “baas”.<br/>"
+ "Jouw taak is dan om links op “bas” te klikken.<br/>"
+ "<br/>"
+ "Er zijn ongeveer 800 woorden in dit experiment. Een normale sessie duurt daarom ongeveer 30 minuten. Bovenaan elk scherm staat aangegeven hoe ver je in het experiment bent.<br/>"
+ "<br/>"
+ "Let op: je kunt het experiment NIET pauzeren, onderbreken, of later weer hervatten. Doe dit experiment daarom ALLEEN als je ook echt de tijd hebt ervoor. Voer het experiment volledig en serieus uit.<br/>"
+ "<br/>"
+ "Als het experiment helder is en je klaar bent om te beginnen, druk dan op VOLGENDE.<br/>"
+ "Het experiment start dan METEEN!";
}
final String completionScreenText1 = "Dit is het einde van het experiment.<br/>"
+ "<br/>"
+ "<br/>"
+ "Bedankt voor je deelname!";
protected int repeatCount() {
return 4;
}
protected String getStimulusResponseOptions() {
return null;
}
protected String[] getStimuliString() {
return new String[]{
// "list_1/list_2:AV_happy.mpg:prevoicing9_e_440Hz_coda_k.wav:bik,bek",
// "list_2/list_3:AV_sad.mpg:prevoicing9_e_440Hz_coda_t.wav:bid,bed",
"999:tgt_5_1100Hz_100ms.wav:bas,baas",
"999:tgt_5_1100Hz_120ms.wav:bas,baas",
"999:tgt_5_1100Hz_130ms.wav:bas,baas",
"999:tgt_5_1100Hz_140ms.wav:bas,baas",
"999:tgt_5_1100Hz_150ms.wav:bas,baas",
"999:tgt_5_1100Hz_160ms.wav:bas,baas",
"999:tgt_5_1100Hz_180ms.wav:bas,baas",
"999:tgt_5_1150Hz_100ms.wav:bas,baas",
"999:tgt_5_1150Hz_120ms.wav:bas,baas",
"999:tgt_5_1150Hz_130ms.wav:bas,baas",
"999:tgt_5_1150Hz_140ms.wav:bas,baas",
"999:tgt_5_1150Hz_150ms.wav:bas,baas",
"999:tgt_5_1150Hz_160ms.wav:bas,baas",
"999:tgt_5_1150Hz_180ms.wav:bas,baas",
"999:tgt_5_1200Hz_100ms.wav:bas,baas",
"999:tgt_5_1200Hz_120ms.wav:bas,baas",
"999:tgt_5_1200Hz_130ms.wav:bas,baas",
"999:tgt_5_1200Hz_140ms.wav:bas,baas",
"999:tgt_5_1200Hz_150ms.wav:bas,baas",
"999:tgt_5_1200Hz_160ms.wav:bas,baas",
"999:tgt_5_1200Hz_180ms.wav:bas,baas",
"999:tgt_5_1250Hz_100ms.wav:bas,baas",
"999:tgt_5_1250Hz_120ms.wav:bas,baas",
"999:tgt_5_1250Hz_130ms.wav:bas,baas",
"999:tgt_5_1250Hz_140ms.wav:bas,baas",
"999:tgt_5_1250Hz_150ms.wav:bas,baas",
"999:tgt_5_1250Hz_160ms.wav:bas,baas",
"999:tgt_5_1250Hz_180ms.wav:bas,baas",
"999:tgt_5_1300Hz_100ms.wav:bas,baas",
"999:tgt_5_1300Hz_120ms.wav:bas,baas",
"999:tgt_5_1300Hz_130ms.wav:bas,baas",
"999:tgt_5_1300Hz_140ms.wav:bas,baas",
"999:tgt_5_1300Hz_150ms.wav:bas,baas",
"999:tgt_5_1300Hz_160ms.wav:bas,baas",
"999:tgt_5_1300Hz_180ms.wav:bas,baas",
"999:tgt_5_1350Hz_100ms.wav:bas,baas",
"999:tgt_5_1350Hz_120ms.wav:bas,baas",
"999:tgt_5_1350Hz_130ms.wav:bas,baas",
"999:tgt_5_1350Hz_140ms.wav:bas,baas",
"999:tgt_5_1350Hz_150ms.wav:bas,baas",
"999:tgt_5_1350Hz_160ms.wav:bas,baas",
"999:tgt_5_1350Hz_180ms.wav:bas,baas",
"999:tgt_5_1400Hz_100ms.wav:bas,baas",
"999:tgt_5_1400Hz_120ms.wav:bas,baas",
"999:tgt_5_1400Hz_130ms.wav:bas,baas",
"999:tgt_5_1400Hz_140ms.wav:bas,baas",
"999:tgt_5_1400Hz_150ms.wav:bas,baas",
"999:tgt_5_1400Hz_160ms.wav:bas,baas",
"999:tgt_5_1400Hz_180ms.wav:bas,baas",
"999:tgt_6_1100Hz_100ms.wav:ad,aad",
"999:tgt_6_1100Hz_120ms.wav:ad,aad",
"999:tgt_6_1100Hz_130ms.wav:ad,aad",
"999:tgt_6_1100Hz_140ms.wav:ad,aad",
"999:tgt_6_1100Hz_150ms.wav:ad,aad",
"999:tgt_6_1100Hz_160ms.wav:ad,aad",
"999:tgt_6_1100Hz_180ms.wav:ad,aad",
"999:tgt_6_1150Hz_100ms.wav:ad,aad",
"999:tgt_6_1150Hz_120ms.wav:ad,aad",
"999:tgt_6_1150Hz_130ms.wav:ad,aad",
"999:tgt_6_1150Hz_140ms.wav:ad,aad",
"999:tgt_6_1150Hz_150ms.wav:ad,aad",
"999:tgt_6_1150Hz_160ms.wav:ad,aad",
"999:tgt_6_1150Hz_180ms.wav:ad,aad",
"999:tgt_6_1200Hz_100ms.wav:ad,aad",
"999:tgt_6_1200Hz_120ms.wav:ad,aad",
"999:tgt_6_1200Hz_130ms.wav:ad,aad",
"999:tgt_6_1200Hz_140ms.wav:ad,aad",
"999:tgt_6_1200Hz_150ms.wav:ad,aad",
"999:tgt_6_1200Hz_160ms.wav:ad,aad",
"999:tgt_6_1200Hz_180ms.wav:ad,aad",
"999:tgt_6_1250Hz_100ms.wav:ad,aad",
"999:tgt_6_1250Hz_120ms.wav:ad,aad",
"999:tgt_6_1250Hz_130ms.wav:ad,aad",
"999:tgt_6_1250Hz_140ms.wav:ad,aad",
"999:tgt_6_1250Hz_150ms.wav:ad,aad",
"999:tgt_6_1250Hz_160ms.wav:ad,aad",
"999:tgt_6_1250Hz_180ms.wav:ad,aad",
"999:tgt_6_1300Hz_100ms.wav:ad,aad",
"999:tgt_6_1300Hz_120ms.wav:ad,aad",
"999:tgt_6_1300Hz_130ms.wav:ad,aad",
"999:tgt_6_1300Hz_140ms.wav:ad,aad",
"999:tgt_6_1300Hz_150ms.wav:ad,aad",
"999:tgt_6_1300Hz_160ms.wav:ad,aad",
"999:tgt_6_1300Hz_180ms.wav:ad,aad",
"999:tgt_6_1350Hz_100ms.wav:ad,aad",
"999:tgt_6_1350Hz_120ms.wav:ad,aad",
"999:tgt_6_1350Hz_130ms.wav:ad,aad",
"999:tgt_6_1350Hz_140ms.wav:ad,aad",
"999:tgt_6_1350Hz_150ms.wav:ad,aad",
"999:tgt_6_1350Hz_160ms.wav:ad,aad",
"999:tgt_6_1350Hz_180ms.wav:ad,aad",
"999:tgt_6_1400Hz_100ms.wav:ad,aad",
"999:tgt_6_1400Hz_120ms.wav:ad,aad",
"999:tgt_6_1400Hz_130ms.wav:ad,aad",
"999:tgt_6_1400Hz_140ms.wav:ad,aad",
"999:tgt_6_1400Hz_150ms.wav:ad,aad",
"999:tgt_6_1400Hz_160ms.wav:ad,aad",
"999:tgt_6_1400Hz_180ms.wav:ad,aad",
"999:tgt_7_1100Hz_100ms.wav:mart,maart",
"999:tgt_7_1100Hz_120ms.wav:mart,maart",
"999:tgt_7_1100Hz_130ms.wav:mart,maart",
"999:tgt_7_1100Hz_140ms.wav:mart,maart",
"999:tgt_7_1100Hz_150ms.wav:mart,maart",
"999:tgt_7_1100Hz_160ms.wav:mart,maart",
"999:tgt_7_1100Hz_180ms.wav:mart,maart",
"999:tgt_7_1150Hz_100ms.wav:mart,maart",
"999:tgt_7_1150Hz_120ms.wav:mart,maart",
"999:tgt_7_1150Hz_130ms.wav:mart,maart",
"999:tgt_7_1150Hz_140ms.wav:mart,maart",
"999:tgt_7_1150Hz_150ms.wav:mart,maart",
"999:tgt_7_1150Hz_160ms.wav:mart,maart",
"999:tgt_7_1150Hz_180ms.wav:mart,maart",
"999:tgt_7_1200Hz_100ms.wav:mart,maart",
"999:tgt_7_1200Hz_120ms.wav:mart,maart",
"999:tgt_7_1200Hz_130ms.wav:mart,maart",
"999:tgt_7_1200Hz_140ms.wav:mart,maart",
"999:tgt_7_1200Hz_150ms.wav:mart,maart",
"999:tgt_7_1200Hz_160ms.wav:mart,maart",
"999:tgt_7_1200Hz_180ms.wav:mart,maart",
"999:tgt_7_1250Hz_100ms.wav:mart,maart",
"999:tgt_7_1250Hz_120ms.wav:mart,maart",
"999:tgt_7_1250Hz_130ms.wav:mart,maart",
"999:tgt_7_1250Hz_140ms.wav:mart,maart",
"999:tgt_7_1250Hz_150ms.wav:mart,maart",
"999:tgt_7_1250Hz_160ms.wav:mart,maart",
"999:tgt_7_1250Hz_180ms.wav:mart,maart",
"999:tgt_7_1300Hz_100ms.wav:mart,maart",
"999:tgt_7_1300Hz_120ms.wav:mart,maart",
"999:tgt_7_1300Hz_130ms.wav:mart,maart",
"999:tgt_7_1300Hz_140ms.wav:mart,maart",
"999:tgt_7_1300Hz_150ms.wav:mart,maart",
"999:tgt_7_1300Hz_160ms.wav:mart,maart",
"999:tgt_7_1300Hz_180ms.wav:mart,maart",
"999:tgt_7_1350Hz_100ms.wav:mart,maart",
"999:tgt_7_1350Hz_120ms.wav:mart,maart",
"999:tgt_7_1350Hz_130ms.wav:mart,maart",
"999:tgt_7_1350Hz_140ms.wav:mart,maart",
"999:tgt_7_1350Hz_150ms.wav:mart,maart",
"999:tgt_7_1350Hz_160ms.wav:mart,maart",
"999:tgt_7_1350Hz_180ms.wav:mart,maart",
"999:tgt_7_1400Hz_100ms.wav:mart,maart",
"999:tgt_7_1400Hz_120ms.wav:mart,maart",
"999:tgt_7_1400Hz_130ms.wav:mart,maart",
"999:tgt_7_1400Hz_140ms.wav:mart,maart",
"999:tgt_7_1400Hz_150ms.wav:mart,maart",
"999:tgt_7_1400Hz_160ms.wav:mart,maart",
"999:tgt_7_1400Hz_180ms.wav:mart,maart",
"999:tgt_8_1100Hz_100ms.wav:dan,daan",
"999:tgt_8_1100Hz_120ms.wav:dan,daan",
"999:tgt_8_1100Hz_130ms.wav:dan,daan",
"999:tgt_8_1100Hz_140ms.wav:dan,daan",
"999:tgt_8_1100Hz_150ms.wav:dan,daan",
"999:tgt_8_1100Hz_160ms.wav:dan,daan",
"999:tgt_8_1100Hz_180ms.wav:dan,daan",
"999:tgt_8_1150Hz_100ms.wav:dan,daan",
"999:tgt_8_1150Hz_120ms.wav:dan,daan",
"999:tgt_8_1150Hz_130ms.wav:dan,daan",
"999:tgt_8_1150Hz_140ms.wav:dan,daan",
"999:tgt_8_1150Hz_150ms.wav:dan,daan",
"999:tgt_8_1150Hz_160ms.wav:dan,daan",
"999:tgt_8_1150Hz_180ms.wav:dan,daan",
"999:tgt_8_1200Hz_100ms.wav:dan,daan",
"999:tgt_8_1200Hz_120ms.wav:dan,daan",
"999:tgt_8_1200Hz_130ms.wav:dan,daan",
"999:tgt_8_1200Hz_140ms.wav:dan,daan",
"999:tgt_8_1200Hz_150ms.wav:dan,daan",
"999:tgt_8_1200Hz_160ms.wav:dan,daan",
"999:tgt_8_1200Hz_180ms.wav:dan,daan",
"999:tgt_8_1250Hz_100ms.wav:dan,daan",
"999:tgt_8_1250Hz_120ms.wav:dan,daan",
"999:tgt_8_1250Hz_130ms.wav:dan,daan",
"999:tgt_8_1250Hz_140ms.wav:dan,daan",
"999:tgt_8_1250Hz_150ms.wav:dan,daan",
"999:tgt_8_1250Hz_160ms.wav:dan,daan",
"999:tgt_8_1250Hz_180ms.wav:dan,daan",
"999:tgt_8_1300Hz_100ms.wav:dan,daan",
"999:tgt_8_1300Hz_120ms.wav:dan,daan",
"999:tgt_8_1300Hz_130ms.wav:dan,daan",
"999:tgt_8_1300Hz_140ms.wav:dan,daan",
"999:tgt_8_1300Hz_150ms.wav:dan,daan",
"999:tgt_8_1300Hz_160ms.wav:dan,daan",
"999:tgt_8_1300Hz_180ms.wav:dan,daan",
"999:tgt_8_1350Hz_100ms.wav:dan,daan",
"999:tgt_8_1350Hz_120ms.wav:dan,daan",
"999:tgt_8_1350Hz_130ms.wav:dan,daan",
"999:tgt_8_1350Hz_140ms.wav:dan,daan",
"999:tgt_8_1350Hz_150ms.wav:dan,daan",
"999:tgt_8_1350Hz_160ms.wav:dan,daan",
"999:tgt_8_1350Hz_180ms.wav:dan,daan",
"999:tgt_8_1400Hz_100ms.wav:dan,daan",
"999:tgt_8_1400Hz_120ms.wav:dan,daan",
"999:tgt_8_1400Hz_130ms.wav:dan,daan",
"999:tgt_8_1400Hz_140ms.wav:dan,daan",
"999:tgt_8_1400Hz_150ms.wav:dan,daan",
"999:tgt_8_1400Hz_160ms.wav:dan,daan",
"999:tgt_8_1400Hz_180ms.wav:dan,daan"
// "AV_happy.mpg",
// "AV_happy.mpg",
// "prevoicing9_e_440Hz_coda_k.wav",
// "prevoicing9_e_440Hz_coda_t.wav"
};
}
public WizardData getWizardData() {
WizardData wizardData = new WizardData();
wizardData.setAppName(getExperimentName());
wizardData.setShowMenuBar(false);
wizardData.setTextFontSize(17);
wizardData.setObfuscateScreenNames(false);
WizardTextScreen wizardTextScreen2 = new WizardTextScreen("InformationScreen1", informationScreenText2(),
"volgende [ spatiebalk ]"
);
WizardAudioTestScreen wizardTextScreen1 = new WizardAudioTestScreen("AudioTest", informationScreenText1, "volgende [ spatiebalk ]", "welkom");
//Information screen
//Agreement
WizardAgreementScreen agreementScreen = new WizardAgreementScreen("Agreement", agreementScreenText, "Ik ga akkoord");
// wizardData.setAgreementText("agreementText");
// wizardData.setDisagreementScreenText("disagreementScreenText");
//metadata
final WizardEditUserScreen wizardEditUserScreen = new WizardEditUserScreen();
wizardEditUserScreen.setScreenTitle("Edit User");
wizardEditUserScreen.setMenuLabel("Edit User");
wizardEditUserScreen.setScreenTag("Edit_User");
wizardEditUserScreen.setNextButton("Volgende");
wizardEditUserScreen.setScreenText("Vul hier je login code in:");
wizardEditUserScreen.setSendData(true);
wizardEditUserScreen.setOn_Error_Text("Could not contact the server, please check your internet connection and try again.");
wizardEditUserScreen.setCustomFields(new String[]{
"workerId:login code:.'{'3,'}':Voer minimaal drie letters."
// "firstName:Voornaam:.'{'3,'}':Voer minimaal drie letters.",
// "lastName:Achternaam:.'{'3,'}':Voer minimaal drie letters.",
// "age:Leeftijd:[0-9]+:Voer een getal.",
// "gender:Geslacht:|man|vrouw|anders:."
});
wizardData.addScreen(wizardEditUserScreen);
wizardData.addScreen(agreementScreen);
wizardData.addScreen(wizardTextScreen1);
wizardData.addScreen(wizardTextScreen2);
final WizardVideoAudioOptionStimulusScreen list1234Screen = new WizardVideoAudioOptionStimulusScreen("Stimuli", false, getStimuliString(), false, false,
null, 1000, repeatCount(), 20, true, 100, "", "", false);
list1234Screen.setShowRatingAfterStimuliResponse(showRatingAfterStimuliResponse);
list1234Screen.getWizardScreenData().setStimulusResponseOptions(getStimulusResponseOptions());
// list1234Screen.setStimulusResponseOptions("1,2,3,4,5");
// list1234Screen.setStimulusResponseLabelLeft("zeer waarschijnlijk negatief");
// list1234Screen.setStimulusResponseLabelRight("zeer waarschijnlijk positief");
wizardData.addScreen(list1234Screen);
WizardCompletionScreen completionScreen = new WizardCompletionScreen(completionScreenText1, false, true,
null, //Wil nog iemand op dit apparaat deelnemen aan dit onderzoek, klik dan op de onderstaande knop.",
"Opnieuw beginnen",
"Finished",
"Could not contact the server, please check your internet connection and try again.", "Retry");
wizardData.addScreen(completionScreen);
final WizardAboutScreen wizardAboutScreen = new WizardAboutScreen("Over", false);
wizardAboutScreen.setBackWizardScreen(wizardEditUserScreen);
wizardData.addScreen(wizardAboutScreen);
wizardEditUserScreen.setNextWizardScreen(agreementScreen);
agreementScreen.setNextWizardScreen(wizardTextScreen1);
wizardTextScreen1.setNextWizardScreen(wizardTextScreen2);
wizardTextScreen2.setNextWizardScreen(list1234Screen);
list1234Screen.setNextWizardScreen(completionScreen);
return wizardData;
}
public Experiment getExperiment() {
return wizardController.getExperiment(getWizardData());
}
}
| MPI-ExperimentGroup/ExperimentTemplate | ExperimentDesigner/src/main/java/nl/mpi/tg/eg/experimentdesigner/util/HRPretest.java | 8,043 | // "age:Leeftijd:[0-9]+:Voer een getal.", | line_comment | nl | /*
* Copyright (C) 2016 Max Planck Institute for Psycholinguistics
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package nl.mpi.tg.eg.experimentdesigner.util;
import nl.mpi.tg.eg.experimentdesigner.controller.WizardController;
import nl.mpi.tg.eg.experimentdesigner.model.Experiment;
import nl.mpi.tg.eg.experimentdesigner.model.WizardData;
import nl.mpi.tg.eg.experimentdesigner.model.wizard.WizardAboutScreen;
import nl.mpi.tg.eg.experimentdesigner.model.wizard.WizardAgreementScreen;
import nl.mpi.tg.eg.experimentdesigner.model.wizard.WizardAudioTestScreen;
import nl.mpi.tg.eg.experimentdesigner.model.wizard.WizardCompletionScreen;
import nl.mpi.tg.eg.experimentdesigner.model.wizard.WizardEditUserScreen;
import nl.mpi.tg.eg.experimentdesigner.model.wizard.WizardTextScreen;
import nl.mpi.tg.eg.experimentdesigner.model.wizard.WizardVideoAudioOptionStimulusScreen;
/**
* @since Jun 6, 2016 11:41:41 AM (creation date)
* @author Peter Withers <[email protected]>
*/
public class HRPretest {
// @done: add a worker id entry befor the agree screen
// @done: shift the audio test to InformationScreen1
// @done: make the next button appear only after the audio has played
// @done: remove the Edit_User screen
// @done: add the stimuli counter 1/10 at the top of the screen
// @done: run the stimuli twice and a fresh randomisation for each run
// @todo: participant.csv is missing the UUID
// @todo: add a csv that has a row for each stimuli and the metadata of the user on each row
// @done: remove the restart button
private final WizardController wizardController = new WizardController();
protected boolean showRatingAfterStimuliResponse = false;
protected String getExperimentName() {
return "HRPretest";
}
final String agreementScreenText = "Alvast bedankt voor uw interesse in dit online-experiment! Gedetailleerde instructies over de taak worden op de volgende pagina gegeven. <br/>"
+ "<br/>"
+ "Voordat u begint, dient u eerst te bevestigen dat u toestemt met deelname aan dit experiment. Let erop dat we uw antwoorden opslaan voor latere analyse. We gebruiken de resultaten alleen voor onderzoeksdoeleinden, en zullen ze beschrijven in gespecialiseerde tijdschriften of wellicht in kranten of op onze website. Echter, we zullen de resultaten NOOIT rapporteren op zo'n manier dat u zou kunnen worden geïdentificeerd. <br/>"
+ "<br/>"
+ "U bent tijdens dit experiment op elk moment vrij om de taak af te breken zonder uitleg te geven. Ook kunt u uw gegevens laten verwijderen tot het moment van publicatie, zonder uit te leggen waarom u dat doet. <br/>"
+ "<br/>"
+ "Er zijn geen risico's bekend van het meedoen aan dit experiment. <br/>"
+ "<br/>"
+ "Als u ermee instemt om door te gaan met dit experiment, klikt u op 'Ik ga akkoord'. Als u besluit niet deel te nemen aan het experiment, klikt u op 'Ik ga niet akkoord'. Verlaat het experiment door naar een andere website te gaan of de pagina af te sluiten."
+ "<br/>";
final String informationScreenText1 = "Dit online experiment is een luisterexperiment. Daarom vragen we je nu de geluidsinstellingen van je computersysteem te testen door op de grote ronde knop hieronder te klikken.<br/>"
+ "<br/>"
+ "<b>Hoor je geen geluid?</b> Dan is er iets mis met je huidige geluidsinstellingen. Pas deze zelf aan en probeer het nogmaals.<br/>"
+ "<br/>"
+ "<b>Hoor je een geluid?</b> Dan staan je geluidsinstellingen goed ingesteld. Stel zelf het volume van je computersysteem in op een comfortabel niveau.<br/>"
+ "<br/>"
+ "----------------------------------------------------------------<br/>"
+ "LET OP: Doe dit experiment ALLEEN als je in een rustige omgeving zit zonder achtergrondgeluid. Dit is heel belangrijk!<br/>"
+ "----------------------------------------------------------------<br/>"
+ "<br/>"
+ "<br/>"
+ "<br/>"
+ "[Druk pas op VOLGENDE als de geluidsinstellingen goed zijn...]";
protected String informationScreenText2() {
return "Dit online experiment is een luisterexperiment. Je krijgt telkens een woord te horen dat ofwel een <b>a-klinker</b> bevat (bijv. dan) ofwel een <b>aa-klinker</b> bevat (bijv. Daan). Jouw taak is om aan te geven welk woord je hoort.<br/>"
+ "<br/>"
+ "Bijvoorbeeld:<br/>"
+ "Je hoort het woord [bas] en daarna verschijnen er twee namen op het scherm:<br/>"
+ "links staat “bas” en rechts staat “baas”.<br/>"
+ "Jouw taak is dan om links op “bas” te klikken.<br/>"
+ "<br/>"
+ "Er zijn ongeveer 800 woorden in dit experiment. Een normale sessie duurt daarom ongeveer 30 minuten. Bovenaan elk scherm staat aangegeven hoe ver je in het experiment bent.<br/>"
+ "<br/>"
+ "Let op: je kunt het experiment NIET pauzeren, onderbreken, of later weer hervatten. Doe dit experiment daarom ALLEEN als je ook echt de tijd hebt ervoor. Voer het experiment volledig en serieus uit.<br/>"
+ "<br/>"
+ "Als het experiment helder is en je klaar bent om te beginnen, druk dan op VOLGENDE.<br/>"
+ "Het experiment start dan METEEN!";
}
final String completionScreenText1 = "Dit is het einde van het experiment.<br/>"
+ "<br/>"
+ "<br/>"
+ "Bedankt voor je deelname!";
protected int repeatCount() {
return 4;
}
protected String getStimulusResponseOptions() {
return null;
}
protected String[] getStimuliString() {
return new String[]{
// "list_1/list_2:AV_happy.mpg:prevoicing9_e_440Hz_coda_k.wav:bik,bek",
// "list_2/list_3:AV_sad.mpg:prevoicing9_e_440Hz_coda_t.wav:bid,bed",
"999:tgt_5_1100Hz_100ms.wav:bas,baas",
"999:tgt_5_1100Hz_120ms.wav:bas,baas",
"999:tgt_5_1100Hz_130ms.wav:bas,baas",
"999:tgt_5_1100Hz_140ms.wav:bas,baas",
"999:tgt_5_1100Hz_150ms.wav:bas,baas",
"999:tgt_5_1100Hz_160ms.wav:bas,baas",
"999:tgt_5_1100Hz_180ms.wav:bas,baas",
"999:tgt_5_1150Hz_100ms.wav:bas,baas",
"999:tgt_5_1150Hz_120ms.wav:bas,baas",
"999:tgt_5_1150Hz_130ms.wav:bas,baas",
"999:tgt_5_1150Hz_140ms.wav:bas,baas",
"999:tgt_5_1150Hz_150ms.wav:bas,baas",
"999:tgt_5_1150Hz_160ms.wav:bas,baas",
"999:tgt_5_1150Hz_180ms.wav:bas,baas",
"999:tgt_5_1200Hz_100ms.wav:bas,baas",
"999:tgt_5_1200Hz_120ms.wav:bas,baas",
"999:tgt_5_1200Hz_130ms.wav:bas,baas",
"999:tgt_5_1200Hz_140ms.wav:bas,baas",
"999:tgt_5_1200Hz_150ms.wav:bas,baas",
"999:tgt_5_1200Hz_160ms.wav:bas,baas",
"999:tgt_5_1200Hz_180ms.wav:bas,baas",
"999:tgt_5_1250Hz_100ms.wav:bas,baas",
"999:tgt_5_1250Hz_120ms.wav:bas,baas",
"999:tgt_5_1250Hz_130ms.wav:bas,baas",
"999:tgt_5_1250Hz_140ms.wav:bas,baas",
"999:tgt_5_1250Hz_150ms.wav:bas,baas",
"999:tgt_5_1250Hz_160ms.wav:bas,baas",
"999:tgt_5_1250Hz_180ms.wav:bas,baas",
"999:tgt_5_1300Hz_100ms.wav:bas,baas",
"999:tgt_5_1300Hz_120ms.wav:bas,baas",
"999:tgt_5_1300Hz_130ms.wav:bas,baas",
"999:tgt_5_1300Hz_140ms.wav:bas,baas",
"999:tgt_5_1300Hz_150ms.wav:bas,baas",
"999:tgt_5_1300Hz_160ms.wav:bas,baas",
"999:tgt_5_1300Hz_180ms.wav:bas,baas",
"999:tgt_5_1350Hz_100ms.wav:bas,baas",
"999:tgt_5_1350Hz_120ms.wav:bas,baas",
"999:tgt_5_1350Hz_130ms.wav:bas,baas",
"999:tgt_5_1350Hz_140ms.wav:bas,baas",
"999:tgt_5_1350Hz_150ms.wav:bas,baas",
"999:tgt_5_1350Hz_160ms.wav:bas,baas",
"999:tgt_5_1350Hz_180ms.wav:bas,baas",
"999:tgt_5_1400Hz_100ms.wav:bas,baas",
"999:tgt_5_1400Hz_120ms.wav:bas,baas",
"999:tgt_5_1400Hz_130ms.wav:bas,baas",
"999:tgt_5_1400Hz_140ms.wav:bas,baas",
"999:tgt_5_1400Hz_150ms.wav:bas,baas",
"999:tgt_5_1400Hz_160ms.wav:bas,baas",
"999:tgt_5_1400Hz_180ms.wav:bas,baas",
"999:tgt_6_1100Hz_100ms.wav:ad,aad",
"999:tgt_6_1100Hz_120ms.wav:ad,aad",
"999:tgt_6_1100Hz_130ms.wav:ad,aad",
"999:tgt_6_1100Hz_140ms.wav:ad,aad",
"999:tgt_6_1100Hz_150ms.wav:ad,aad",
"999:tgt_6_1100Hz_160ms.wav:ad,aad",
"999:tgt_6_1100Hz_180ms.wav:ad,aad",
"999:tgt_6_1150Hz_100ms.wav:ad,aad",
"999:tgt_6_1150Hz_120ms.wav:ad,aad",
"999:tgt_6_1150Hz_130ms.wav:ad,aad",
"999:tgt_6_1150Hz_140ms.wav:ad,aad",
"999:tgt_6_1150Hz_150ms.wav:ad,aad",
"999:tgt_6_1150Hz_160ms.wav:ad,aad",
"999:tgt_6_1150Hz_180ms.wav:ad,aad",
"999:tgt_6_1200Hz_100ms.wav:ad,aad",
"999:tgt_6_1200Hz_120ms.wav:ad,aad",
"999:tgt_6_1200Hz_130ms.wav:ad,aad",
"999:tgt_6_1200Hz_140ms.wav:ad,aad",
"999:tgt_6_1200Hz_150ms.wav:ad,aad",
"999:tgt_6_1200Hz_160ms.wav:ad,aad",
"999:tgt_6_1200Hz_180ms.wav:ad,aad",
"999:tgt_6_1250Hz_100ms.wav:ad,aad",
"999:tgt_6_1250Hz_120ms.wav:ad,aad",
"999:tgt_6_1250Hz_130ms.wav:ad,aad",
"999:tgt_6_1250Hz_140ms.wav:ad,aad",
"999:tgt_6_1250Hz_150ms.wav:ad,aad",
"999:tgt_6_1250Hz_160ms.wav:ad,aad",
"999:tgt_6_1250Hz_180ms.wav:ad,aad",
"999:tgt_6_1300Hz_100ms.wav:ad,aad",
"999:tgt_6_1300Hz_120ms.wav:ad,aad",
"999:tgt_6_1300Hz_130ms.wav:ad,aad",
"999:tgt_6_1300Hz_140ms.wav:ad,aad",
"999:tgt_6_1300Hz_150ms.wav:ad,aad",
"999:tgt_6_1300Hz_160ms.wav:ad,aad",
"999:tgt_6_1300Hz_180ms.wav:ad,aad",
"999:tgt_6_1350Hz_100ms.wav:ad,aad",
"999:tgt_6_1350Hz_120ms.wav:ad,aad",
"999:tgt_6_1350Hz_130ms.wav:ad,aad",
"999:tgt_6_1350Hz_140ms.wav:ad,aad",
"999:tgt_6_1350Hz_150ms.wav:ad,aad",
"999:tgt_6_1350Hz_160ms.wav:ad,aad",
"999:tgt_6_1350Hz_180ms.wav:ad,aad",
"999:tgt_6_1400Hz_100ms.wav:ad,aad",
"999:tgt_6_1400Hz_120ms.wav:ad,aad",
"999:tgt_6_1400Hz_130ms.wav:ad,aad",
"999:tgt_6_1400Hz_140ms.wav:ad,aad",
"999:tgt_6_1400Hz_150ms.wav:ad,aad",
"999:tgt_6_1400Hz_160ms.wav:ad,aad",
"999:tgt_6_1400Hz_180ms.wav:ad,aad",
"999:tgt_7_1100Hz_100ms.wav:mart,maart",
"999:tgt_7_1100Hz_120ms.wav:mart,maart",
"999:tgt_7_1100Hz_130ms.wav:mart,maart",
"999:tgt_7_1100Hz_140ms.wav:mart,maart",
"999:tgt_7_1100Hz_150ms.wav:mart,maart",
"999:tgt_7_1100Hz_160ms.wav:mart,maart",
"999:tgt_7_1100Hz_180ms.wav:mart,maart",
"999:tgt_7_1150Hz_100ms.wav:mart,maart",
"999:tgt_7_1150Hz_120ms.wav:mart,maart",
"999:tgt_7_1150Hz_130ms.wav:mart,maart",
"999:tgt_7_1150Hz_140ms.wav:mart,maart",
"999:tgt_7_1150Hz_150ms.wav:mart,maart",
"999:tgt_7_1150Hz_160ms.wav:mart,maart",
"999:tgt_7_1150Hz_180ms.wav:mart,maart",
"999:tgt_7_1200Hz_100ms.wav:mart,maart",
"999:tgt_7_1200Hz_120ms.wav:mart,maart",
"999:tgt_7_1200Hz_130ms.wav:mart,maart",
"999:tgt_7_1200Hz_140ms.wav:mart,maart",
"999:tgt_7_1200Hz_150ms.wav:mart,maart",
"999:tgt_7_1200Hz_160ms.wav:mart,maart",
"999:tgt_7_1200Hz_180ms.wav:mart,maart",
"999:tgt_7_1250Hz_100ms.wav:mart,maart",
"999:tgt_7_1250Hz_120ms.wav:mart,maart",
"999:tgt_7_1250Hz_130ms.wav:mart,maart",
"999:tgt_7_1250Hz_140ms.wav:mart,maart",
"999:tgt_7_1250Hz_150ms.wav:mart,maart",
"999:tgt_7_1250Hz_160ms.wav:mart,maart",
"999:tgt_7_1250Hz_180ms.wav:mart,maart",
"999:tgt_7_1300Hz_100ms.wav:mart,maart",
"999:tgt_7_1300Hz_120ms.wav:mart,maart",
"999:tgt_7_1300Hz_130ms.wav:mart,maart",
"999:tgt_7_1300Hz_140ms.wav:mart,maart",
"999:tgt_7_1300Hz_150ms.wav:mart,maart",
"999:tgt_7_1300Hz_160ms.wav:mart,maart",
"999:tgt_7_1300Hz_180ms.wav:mart,maart",
"999:tgt_7_1350Hz_100ms.wav:mart,maart",
"999:tgt_7_1350Hz_120ms.wav:mart,maart",
"999:tgt_7_1350Hz_130ms.wav:mart,maart",
"999:tgt_7_1350Hz_140ms.wav:mart,maart",
"999:tgt_7_1350Hz_150ms.wav:mart,maart",
"999:tgt_7_1350Hz_160ms.wav:mart,maart",
"999:tgt_7_1350Hz_180ms.wav:mart,maart",
"999:tgt_7_1400Hz_100ms.wav:mart,maart",
"999:tgt_7_1400Hz_120ms.wav:mart,maart",
"999:tgt_7_1400Hz_130ms.wav:mart,maart",
"999:tgt_7_1400Hz_140ms.wav:mart,maart",
"999:tgt_7_1400Hz_150ms.wav:mart,maart",
"999:tgt_7_1400Hz_160ms.wav:mart,maart",
"999:tgt_7_1400Hz_180ms.wav:mart,maart",
"999:tgt_8_1100Hz_100ms.wav:dan,daan",
"999:tgt_8_1100Hz_120ms.wav:dan,daan",
"999:tgt_8_1100Hz_130ms.wav:dan,daan",
"999:tgt_8_1100Hz_140ms.wav:dan,daan",
"999:tgt_8_1100Hz_150ms.wav:dan,daan",
"999:tgt_8_1100Hz_160ms.wav:dan,daan",
"999:tgt_8_1100Hz_180ms.wav:dan,daan",
"999:tgt_8_1150Hz_100ms.wav:dan,daan",
"999:tgt_8_1150Hz_120ms.wav:dan,daan",
"999:tgt_8_1150Hz_130ms.wav:dan,daan",
"999:tgt_8_1150Hz_140ms.wav:dan,daan",
"999:tgt_8_1150Hz_150ms.wav:dan,daan",
"999:tgt_8_1150Hz_160ms.wav:dan,daan",
"999:tgt_8_1150Hz_180ms.wav:dan,daan",
"999:tgt_8_1200Hz_100ms.wav:dan,daan",
"999:tgt_8_1200Hz_120ms.wav:dan,daan",
"999:tgt_8_1200Hz_130ms.wav:dan,daan",
"999:tgt_8_1200Hz_140ms.wav:dan,daan",
"999:tgt_8_1200Hz_150ms.wav:dan,daan",
"999:tgt_8_1200Hz_160ms.wav:dan,daan",
"999:tgt_8_1200Hz_180ms.wav:dan,daan",
"999:tgt_8_1250Hz_100ms.wav:dan,daan",
"999:tgt_8_1250Hz_120ms.wav:dan,daan",
"999:tgt_8_1250Hz_130ms.wav:dan,daan",
"999:tgt_8_1250Hz_140ms.wav:dan,daan",
"999:tgt_8_1250Hz_150ms.wav:dan,daan",
"999:tgt_8_1250Hz_160ms.wav:dan,daan",
"999:tgt_8_1250Hz_180ms.wav:dan,daan",
"999:tgt_8_1300Hz_100ms.wav:dan,daan",
"999:tgt_8_1300Hz_120ms.wav:dan,daan",
"999:tgt_8_1300Hz_130ms.wav:dan,daan",
"999:tgt_8_1300Hz_140ms.wav:dan,daan",
"999:tgt_8_1300Hz_150ms.wav:dan,daan",
"999:tgt_8_1300Hz_160ms.wav:dan,daan",
"999:tgt_8_1300Hz_180ms.wav:dan,daan",
"999:tgt_8_1350Hz_100ms.wav:dan,daan",
"999:tgt_8_1350Hz_120ms.wav:dan,daan",
"999:tgt_8_1350Hz_130ms.wav:dan,daan",
"999:tgt_8_1350Hz_140ms.wav:dan,daan",
"999:tgt_8_1350Hz_150ms.wav:dan,daan",
"999:tgt_8_1350Hz_160ms.wav:dan,daan",
"999:tgt_8_1350Hz_180ms.wav:dan,daan",
"999:tgt_8_1400Hz_100ms.wav:dan,daan",
"999:tgt_8_1400Hz_120ms.wav:dan,daan",
"999:tgt_8_1400Hz_130ms.wav:dan,daan",
"999:tgt_8_1400Hz_140ms.wav:dan,daan",
"999:tgt_8_1400Hz_150ms.wav:dan,daan",
"999:tgt_8_1400Hz_160ms.wav:dan,daan",
"999:tgt_8_1400Hz_180ms.wav:dan,daan"
// "AV_happy.mpg",
// "AV_happy.mpg",
// "prevoicing9_e_440Hz_coda_k.wav",
// "prevoicing9_e_440Hz_coda_t.wav"
};
}
public WizardData getWizardData() {
WizardData wizardData = new WizardData();
wizardData.setAppName(getExperimentName());
wizardData.setShowMenuBar(false);
wizardData.setTextFontSize(17);
wizardData.setObfuscateScreenNames(false);
WizardTextScreen wizardTextScreen2 = new WizardTextScreen("InformationScreen1", informationScreenText2(),
"volgende [ spatiebalk ]"
);
WizardAudioTestScreen wizardTextScreen1 = new WizardAudioTestScreen("AudioTest", informationScreenText1, "volgende [ spatiebalk ]", "welkom");
//Information screen
//Agreement
WizardAgreementScreen agreementScreen = new WizardAgreementScreen("Agreement", agreementScreenText, "Ik ga akkoord");
// wizardData.setAgreementText("agreementText");
// wizardData.setDisagreementScreenText("disagreementScreenText");
//metadata
final WizardEditUserScreen wizardEditUserScreen = new WizardEditUserScreen();
wizardEditUserScreen.setScreenTitle("Edit User");
wizardEditUserScreen.setMenuLabel("Edit User");
wizardEditUserScreen.setScreenTag("Edit_User");
wizardEditUserScreen.setNextButton("Volgende");
wizardEditUserScreen.setScreenText("Vul hier je login code in:");
wizardEditUserScreen.setSendData(true);
wizardEditUserScreen.setOn_Error_Text("Could not contact the server, please check your internet connection and try again.");
wizardEditUserScreen.setCustomFields(new String[]{
"workerId:login code:.'{'3,'}':Voer minimaal drie letters."
// "firstName:Voornaam:.'{'3,'}':Voer minimaal drie letters.",
// "lastName:Achternaam:.'{'3,'}':Voer minimaal drie letters.",
// "age:Leeftijd:[0-9]+:Voer een<SUF>
// "gender:Geslacht:|man|vrouw|anders:."
});
wizardData.addScreen(wizardEditUserScreen);
wizardData.addScreen(agreementScreen);
wizardData.addScreen(wizardTextScreen1);
wizardData.addScreen(wizardTextScreen2);
final WizardVideoAudioOptionStimulusScreen list1234Screen = new WizardVideoAudioOptionStimulusScreen("Stimuli", false, getStimuliString(), false, false,
null, 1000, repeatCount(), 20, true, 100, "", "", false);
list1234Screen.setShowRatingAfterStimuliResponse(showRatingAfterStimuliResponse);
list1234Screen.getWizardScreenData().setStimulusResponseOptions(getStimulusResponseOptions());
// list1234Screen.setStimulusResponseOptions("1,2,3,4,5");
// list1234Screen.setStimulusResponseLabelLeft("zeer waarschijnlijk negatief");
// list1234Screen.setStimulusResponseLabelRight("zeer waarschijnlijk positief");
wizardData.addScreen(list1234Screen);
WizardCompletionScreen completionScreen = new WizardCompletionScreen(completionScreenText1, false, true,
null, //Wil nog iemand op dit apparaat deelnemen aan dit onderzoek, klik dan op de onderstaande knop.",
"Opnieuw beginnen",
"Finished",
"Could not contact the server, please check your internet connection and try again.", "Retry");
wizardData.addScreen(completionScreen);
final WizardAboutScreen wizardAboutScreen = new WizardAboutScreen("Over", false);
wizardAboutScreen.setBackWizardScreen(wizardEditUserScreen);
wizardData.addScreen(wizardAboutScreen);
wizardEditUserScreen.setNextWizardScreen(agreementScreen);
agreementScreen.setNextWizardScreen(wizardTextScreen1);
wizardTextScreen1.setNextWizardScreen(wizardTextScreen2);
wizardTextScreen2.setNextWizardScreen(list1234Screen);
list1234Screen.setNextWizardScreen(completionScreen);
return wizardData;
}
public Experiment getExperiment() {
return wizardController.getExperiment(getWizardData());
}
}
|
19787_6 | package nl.mrensen.aoc.days;
import nl.mrensen.aoc.common.Day;
import java.util.*;
public class Day09 implements Day<Integer> {
int inputRow = 0;
// Een handige helper klasse om de positie van (x,y) van de H en T op te schrijven.
// Equals en Hashcode zijn heel belangrijk, anders krijg je dubbele waardes in de Set.
private class Pos{
public int x, y;
public Pos(int x, int y){this.x=x; this.y=y;}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pos pos = (Pos) o;
return x == pos.x && y == pos.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
// x=r/l y=u/d
Pos h = new Pos(0,0);
Pos t = new Pos(0, 0);
int count = 1;
Set<Pos> visited = new HashSet<>();
private void move(String move, Pos head, Pos tail, boolean set){
String dir = move.substring(0,1);
String steps = move.substring(1).trim();
switch(dir){
// voor elke richting die de H op kan gaan een aparte case, omdat het een combinatie van x/y ++/-- kan zijn.
case "R" -> {
// Voor elke stap die de H zet, volgt de T
for(int i = 0; i < Integer.parseInt(steps); i++){
head.x++;
moveT(head, tail, set);
}
}
case "L" -> {
for(int i = 0; i < Integer.parseInt(steps); i++){
head.x--;
moveT(head, tail, set);
}
}
case "U" -> {
for(int i = 0; i < Integer.parseInt(steps); i++){
head.y++;
moveT(head,tail, set);
}
}
case "D" -> {
for(int i = 0; i < Integer.parseInt(steps); i++){
head.y--;
moveT(head, tail, set);
}
}
}
}
private boolean visitedAdd(Pos pos, Boolean set){
Pos toAdd = new Pos(pos.x, pos.y);
// Voeg alleen toAdd toe aan visited als set true is.
return set && visited.add(toAdd);
};
private void moveT(Pos head, Pos tail, boolean set) {
// Als H naar rechts is verplaatst en T en H elkaar niet meer aanraken
if(tail.x<head.x-1){
// verplaats T dan ook naar rechts, zodat T en H elkaar weer aanraken.
tail.x++;
// Als H dan ook nog hoger staat dan T, verplaats T dan schuin omhoog ipv enkel naar rechts.
if(tail.y<head.y){
tail.y++;
}
// Als H ook lager staat dan T, verplaats T dan schuin naar onder ipv enkel naar rechts.
else if(tail.y>head.y){
tail.y--;
}
if(visitedAdd(tail, set)){
count++;
}
}
// Als H naar links is verplaatst en T en H elkaar niet meer aanraken
else if(tail.x>head.x+1){
tail.x--;
if(tail.y>head.y){
tail.y--;
}
else if(tail.y<head.y){
tail.y++;
}
if(visitedAdd(tail, set)){
count++;
}
}
// Als H omhoog is verplaats en T en H elkaar niet meer aanraken
else if(tail.y<head.y-1){
tail.y++;
if(tail.x<head.x){
tail.x++;
}
else if(tail.x>head.x){
tail.x--;
}
if(visitedAdd(tail, set)){
count++;
}
}
// Als H omlaag is verplaatst en T en H elkaar niet meer aanraken
else if(tail.y>head.y+1){
tail.y--;
if(tail.x>head.x){
tail.x--; //Note: Ik had hier ++ en hieronder --, waardoor mijn antwoord 6077 was ipv 5874
}
else if(tail.x<head.x){
tail.x++;
}
if(visitedAdd(tail, set)){
count++;
}
}
}
@Override
public Integer part1(List<String> input) {
// voeg de start positie van T toe aan de set.
visitedAdd(t ,true);
// loop door de input heen en voer elke regel uit.
for(String s : input){
inputRow++; // deze is handig voor debuggen
move(s, h, t, true);
}
// return hoeveel unieke posities T heeft bezocht
return visited.size();
}
@Override
public Integer part2(List<String> input) {
// voeg de start positie van T toe aan de set.
visitedAdd(t, true);
Pos[] tails = new Pos[8];
for(int i = 0; i<tails.length; i++){
tails[i] = new Pos(0, 0);
}
// loop door de input heen en voer elke regel uit voor alle knopen
for(String s : input){
String steps = s.substring(1).trim();
inputRow++;
move(s, h, tails[0], false);
for(int i = 0; i < Integer.parseInt(steps); i++) {
moveT(tails[0], tails[1], false);
moveT(tails[1], tails[2], false);
moveT(tails[2], tails[3], false);
moveT(tails[3], tails[4], false);
moveT(tails[4], tails[5], false);
moveT(tails[5], tails[6], false);
moveT(tails[6], tails[7], false);
moveT(tails[7], t, true);
}
}
// return hoeveel unieke posities T heeft bezocht
return visited.size();
}
}
| MRensen/AoC22 | src/main/java/nl/mrensen/aoc/days/Day09.java | 1,791 | // Als H naar rechts is verplaatst en T en H elkaar niet meer aanraken | line_comment | nl | package nl.mrensen.aoc.days;
import nl.mrensen.aoc.common.Day;
import java.util.*;
public class Day09 implements Day<Integer> {
int inputRow = 0;
// Een handige helper klasse om de positie van (x,y) van de H en T op te schrijven.
// Equals en Hashcode zijn heel belangrijk, anders krijg je dubbele waardes in de Set.
private class Pos{
public int x, y;
public Pos(int x, int y){this.x=x; this.y=y;}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pos pos = (Pos) o;
return x == pos.x && y == pos.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
// x=r/l y=u/d
Pos h = new Pos(0,0);
Pos t = new Pos(0, 0);
int count = 1;
Set<Pos> visited = new HashSet<>();
private void move(String move, Pos head, Pos tail, boolean set){
String dir = move.substring(0,1);
String steps = move.substring(1).trim();
switch(dir){
// voor elke richting die de H op kan gaan een aparte case, omdat het een combinatie van x/y ++/-- kan zijn.
case "R" -> {
// Voor elke stap die de H zet, volgt de T
for(int i = 0; i < Integer.parseInt(steps); i++){
head.x++;
moveT(head, tail, set);
}
}
case "L" -> {
for(int i = 0; i < Integer.parseInt(steps); i++){
head.x--;
moveT(head, tail, set);
}
}
case "U" -> {
for(int i = 0; i < Integer.parseInt(steps); i++){
head.y++;
moveT(head,tail, set);
}
}
case "D" -> {
for(int i = 0; i < Integer.parseInt(steps); i++){
head.y--;
moveT(head, tail, set);
}
}
}
}
private boolean visitedAdd(Pos pos, Boolean set){
Pos toAdd = new Pos(pos.x, pos.y);
// Voeg alleen toAdd toe aan visited als set true is.
return set && visited.add(toAdd);
};
private void moveT(Pos head, Pos tail, boolean set) {
// Als H<SUF>
if(tail.x<head.x-1){
// verplaats T dan ook naar rechts, zodat T en H elkaar weer aanraken.
tail.x++;
// Als H dan ook nog hoger staat dan T, verplaats T dan schuin omhoog ipv enkel naar rechts.
if(tail.y<head.y){
tail.y++;
}
// Als H ook lager staat dan T, verplaats T dan schuin naar onder ipv enkel naar rechts.
else if(tail.y>head.y){
tail.y--;
}
if(visitedAdd(tail, set)){
count++;
}
}
// Als H naar links is verplaatst en T en H elkaar niet meer aanraken
else if(tail.x>head.x+1){
tail.x--;
if(tail.y>head.y){
tail.y--;
}
else if(tail.y<head.y){
tail.y++;
}
if(visitedAdd(tail, set)){
count++;
}
}
// Als H omhoog is verplaats en T en H elkaar niet meer aanraken
else if(tail.y<head.y-1){
tail.y++;
if(tail.x<head.x){
tail.x++;
}
else if(tail.x>head.x){
tail.x--;
}
if(visitedAdd(tail, set)){
count++;
}
}
// Als H omlaag is verplaatst en T en H elkaar niet meer aanraken
else if(tail.y>head.y+1){
tail.y--;
if(tail.x>head.x){
tail.x--; //Note: Ik had hier ++ en hieronder --, waardoor mijn antwoord 6077 was ipv 5874
}
else if(tail.x<head.x){
tail.x++;
}
if(visitedAdd(tail, set)){
count++;
}
}
}
@Override
public Integer part1(List<String> input) {
// voeg de start positie van T toe aan de set.
visitedAdd(t ,true);
// loop door de input heen en voer elke regel uit.
for(String s : input){
inputRow++; // deze is handig voor debuggen
move(s, h, t, true);
}
// return hoeveel unieke posities T heeft bezocht
return visited.size();
}
@Override
public Integer part2(List<String> input) {
// voeg de start positie van T toe aan de set.
visitedAdd(t, true);
Pos[] tails = new Pos[8];
for(int i = 0; i<tails.length; i++){
tails[i] = new Pos(0, 0);
}
// loop door de input heen en voer elke regel uit voor alle knopen
for(String s : input){
String steps = s.substring(1).trim();
inputRow++;
move(s, h, tails[0], false);
for(int i = 0; i < Integer.parseInt(steps); i++) {
moveT(tails[0], tails[1], false);
moveT(tails[1], tails[2], false);
moveT(tails[2], tails[3], false);
moveT(tails[3], tails[4], false);
moveT(tails[4], tails[5], false);
moveT(tails[5], tails[6], false);
moveT(tails[6], tails[7], false);
moveT(tails[7], t, true);
}
}
// return hoeveel unieke posities T heeft bezocht
return visited.size();
}
}
|
22342_0 | package nl.markrensen.aoc.days;
import nl.markrensen.aoc.common.Day;
import org.junit.platform.commons.util.StringUtils;
import java.util.*;
public class Day03 implements Day<Integer> {
int MAX_LENGTH = 3;
Set<Character> symbols;
int counter = 0;
Map<String, Integer> rejects = new TreeMap<>();
@Override
public Integer part1(List<String> input) {
symbols = findAllSymbols(input);
String[][] board = new String[input.size()][input.get(0).length()];
for (int i = 0; i < input.size(); i++){
String[] row = input.get(i).split("");
board[i] = row;
}
for (int i = 0; i < board.length; i++){
for (int j = 0; j < board[i].length; j++){
String current = board[i][j];
if(isSymbol(current)) {
try {
for (int ii = i - 1; ii <= i + 1; ii++) {
for (int jj = j - 1; jj <= j + 1; jj++) {
String check = board[ii][jj];
if (!check.equals(".") && !check.equals(current)) {
int fullneighbour = getFullNeighbour(ii, jj, board);
if(fullneighbour>0){
// if(!neigbours.add(fullneighbour)){
// //een debug ding
// counter++;
// }
rejects.put("["+i+"]["+j+"]"+fullneighbour, fullneighbour);
}
// een debug ding
}
}
}
} catch (IndexOutOfBoundsException ignored){}
}
}
}
int sum = 0;
for(int i : rejects.values()){
sum += i;
}
return sum;
}
Set<Character> findAllSymbols(List<String> input){
StringBuilder sb = new StringBuilder();
for (String s : input){
sb.append(s);
}
String s = sb.toString().replaceAll("\\.","").replaceAll("\\d","");
Set<Character> set = new HashSet<>();
for (Character c : s.toCharArray()){
set.add(c);
}
return set;
}
boolean isSymbol(String s){
char[] ca = s.toCharArray();
assert ca.length == 1;
return symbols.contains(ca[0]);
}
int getFullNeighbour(int i, int j, String[][]board){
String input = board[i][j];
StringBuilder before = new StringBuilder();
StringBuilder after = new StringBuilder();
int min = 1;
try {
while (!board[i][j - min].equals(".") && !isSymbol(board[i][j - min])) {
before.append(board[i][j - min]);
min++;
}
} catch (IndexOutOfBoundsException ignored) {
System.out.println("Index out of bounds for [" + i + "][" + (j-min) + "]");
}
min = 1;
try {
while (!board[i][j + min].equals(".") && !isSymbol(board[i][j + min])) {
after.append(board[i][j + min]);
min++;
}
} catch (IndexOutOfBoundsException ignored) {
System.out.println("Index out of bounds for [" + i + "][" + (j-min) + "]");
}
String resultString = before.reverse().toString() + input + after.toString();
// System.out.println(resultString);
try {
return Integer.parseInt(resultString);
} catch (NumberFormatException e){
return -1;
}
}
@Override
public Integer part2(List<String> input) {
String[][] board = new String[input.size()][input.get(0).length()];
Map<String, Integer> gearRatios = new TreeMap<>();
for (int i = 0; i < input.size(); i++){
String[] row = input.get(i).split("");
board[i] = row;
}
for (int i = 0; i < board.length; i++){
for (int j = 0; j < board[i].length; j++){
String current = board[i][j];
if(isSymbol2(current)) {
Map<String, Integer> doubleNeighbours = new TreeMap<>();
try {
for (int ii = i - 1; ii <= i + 1; ii++) {
for (int jj = j - 1; jj <= j + 1; jj++) {
String check = board[ii][jj];
if (!check.equals(".") && !check.equals(current)) {
int fullneighbour = getFullNeighbour2(ii, jj, board);
if(fullneighbour>0){
doubleNeighbours.put("["+i+"]["+j+"]"+fullneighbour, fullneighbour);
}
}
}
}
} catch (IndexOutOfBoundsException ignored){}
if(doubleNeighbours.size() == 2) {
int prod = 1;
for(int x : doubleNeighbours.values()){
prod *= x;
}
gearRatios.put("[" + i + "][" + j + "]", prod);
}
}
}
}
int sum = 0;
for(int i : gearRatios.values()){
sum += i;
}
return sum;
}
// Deze ziet nu alleen "*" als een geldig symbol
boolean isSymbol2(String s){
char[] ca = s.toCharArray();
assert ca.length == 1;
return ca[0] == '*';
}
// alleen "isSymbol" veranderd naar "isSymbol2"
int getFullNeighbour2(int i, int j, String[][]board){
String input = board[i][j];
StringBuilder before = new StringBuilder();
StringBuilder after = new StringBuilder();
int min = 1;
try {
while (!board[i][j - min].equals(".") && !isSymbol2(board[i][j - min])) {
before.append(board[i][j - min]);
min++;
}
} catch (IndexOutOfBoundsException ignored) {
System.out.println("Index out of bounds for [" + i + "][" + (j-min) + "]");
}
min = 1;
try {
while (!board[i][j + min].equals(".") && !isSymbol2(board[i][j + min])) {
after.append(board[i][j + min]);
min++;
}
} catch (IndexOutOfBoundsException ignored) {
System.out.println("Index out of bounds for [" + i + "][" + (j-min) + "]");
}
String resultString = before.reverse().toString() + input + after.toString();
// System.out.println(resultString);
try {
return Integer.parseInt(resultString);
} catch (NumberFormatException e){
return -1;
}
}
}
| MRensen/aoc2023 | src/main/java/nl/markrensen/aoc/days/Day03.java | 2,018 | // //een debug ding | line_comment | nl | package nl.markrensen.aoc.days;
import nl.markrensen.aoc.common.Day;
import org.junit.platform.commons.util.StringUtils;
import java.util.*;
public class Day03 implements Day<Integer> {
int MAX_LENGTH = 3;
Set<Character> symbols;
int counter = 0;
Map<String, Integer> rejects = new TreeMap<>();
@Override
public Integer part1(List<String> input) {
symbols = findAllSymbols(input);
String[][] board = new String[input.size()][input.get(0).length()];
for (int i = 0; i < input.size(); i++){
String[] row = input.get(i).split("");
board[i] = row;
}
for (int i = 0; i < board.length; i++){
for (int j = 0; j < board[i].length; j++){
String current = board[i][j];
if(isSymbol(current)) {
try {
for (int ii = i - 1; ii <= i + 1; ii++) {
for (int jj = j - 1; jj <= j + 1; jj++) {
String check = board[ii][jj];
if (!check.equals(".") && !check.equals(current)) {
int fullneighbour = getFullNeighbour(ii, jj, board);
if(fullneighbour>0){
// if(!neigbours.add(fullneighbour)){
// //een debug<SUF>
// counter++;
// }
rejects.put("["+i+"]["+j+"]"+fullneighbour, fullneighbour);
}
// een debug ding
}
}
}
} catch (IndexOutOfBoundsException ignored){}
}
}
}
int sum = 0;
for(int i : rejects.values()){
sum += i;
}
return sum;
}
Set<Character> findAllSymbols(List<String> input){
StringBuilder sb = new StringBuilder();
for (String s : input){
sb.append(s);
}
String s = sb.toString().replaceAll("\\.","").replaceAll("\\d","");
Set<Character> set = new HashSet<>();
for (Character c : s.toCharArray()){
set.add(c);
}
return set;
}
boolean isSymbol(String s){
char[] ca = s.toCharArray();
assert ca.length == 1;
return symbols.contains(ca[0]);
}
int getFullNeighbour(int i, int j, String[][]board){
String input = board[i][j];
StringBuilder before = new StringBuilder();
StringBuilder after = new StringBuilder();
int min = 1;
try {
while (!board[i][j - min].equals(".") && !isSymbol(board[i][j - min])) {
before.append(board[i][j - min]);
min++;
}
} catch (IndexOutOfBoundsException ignored) {
System.out.println("Index out of bounds for [" + i + "][" + (j-min) + "]");
}
min = 1;
try {
while (!board[i][j + min].equals(".") && !isSymbol(board[i][j + min])) {
after.append(board[i][j + min]);
min++;
}
} catch (IndexOutOfBoundsException ignored) {
System.out.println("Index out of bounds for [" + i + "][" + (j-min) + "]");
}
String resultString = before.reverse().toString() + input + after.toString();
// System.out.println(resultString);
try {
return Integer.parseInt(resultString);
} catch (NumberFormatException e){
return -1;
}
}
@Override
public Integer part2(List<String> input) {
String[][] board = new String[input.size()][input.get(0).length()];
Map<String, Integer> gearRatios = new TreeMap<>();
for (int i = 0; i < input.size(); i++){
String[] row = input.get(i).split("");
board[i] = row;
}
for (int i = 0; i < board.length; i++){
for (int j = 0; j < board[i].length; j++){
String current = board[i][j];
if(isSymbol2(current)) {
Map<String, Integer> doubleNeighbours = new TreeMap<>();
try {
for (int ii = i - 1; ii <= i + 1; ii++) {
for (int jj = j - 1; jj <= j + 1; jj++) {
String check = board[ii][jj];
if (!check.equals(".") && !check.equals(current)) {
int fullneighbour = getFullNeighbour2(ii, jj, board);
if(fullneighbour>0){
doubleNeighbours.put("["+i+"]["+j+"]"+fullneighbour, fullneighbour);
}
}
}
}
} catch (IndexOutOfBoundsException ignored){}
if(doubleNeighbours.size() == 2) {
int prod = 1;
for(int x : doubleNeighbours.values()){
prod *= x;
}
gearRatios.put("[" + i + "][" + j + "]", prod);
}
}
}
}
int sum = 0;
for(int i : gearRatios.values()){
sum += i;
}
return sum;
}
// Deze ziet nu alleen "*" als een geldig symbol
boolean isSymbol2(String s){
char[] ca = s.toCharArray();
assert ca.length == 1;
return ca[0] == '*';
}
// alleen "isSymbol" veranderd naar "isSymbol2"
int getFullNeighbour2(int i, int j, String[][]board){
String input = board[i][j];
StringBuilder before = new StringBuilder();
StringBuilder after = new StringBuilder();
int min = 1;
try {
while (!board[i][j - min].equals(".") && !isSymbol2(board[i][j - min])) {
before.append(board[i][j - min]);
min++;
}
} catch (IndexOutOfBoundsException ignored) {
System.out.println("Index out of bounds for [" + i + "][" + (j-min) + "]");
}
min = 1;
try {
while (!board[i][j + min].equals(".") && !isSymbol2(board[i][j + min])) {
after.append(board[i][j + min]);
min++;
}
} catch (IndexOutOfBoundsException ignored) {
System.out.println("Index out of bounds for [" + i + "][" + (j-min) + "]");
}
String resultString = before.reverse().toString() + input + after.toString();
// System.out.println(resultString);
try {
return Integer.parseInt(resultString);
} catch (NumberFormatException e){
return -1;
}
}
}
|
209269_11 | package be.ehb.koalaexpress;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import be.ehb.koalaexpress.Tasks.Task_SendOrderToDB;
import be.ehb.koalaexpress.models.WinkelMandje;
import cz.msebera.android.httpclient.Header;
public class CheckoutActivity extends AppCompatActivity {
TextView orderID_label;
TextView payerID_label;
TextView paymentAmount_label;
Button confirm_btn;
Button annuleren_btn;
ProgressBar progressbar;
public String orderID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hiding ActionBar
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
setContentView(R.layout.activity_checkout);
//get the orderID from the query parameter
Uri redirectUri = getIntent().getData();
List<String> segmentsInUrl = redirectUri.getPathSegments();
//hier kan je succes of failure halen uit de segmenstInURL
orderID = redirectUri.getQueryParameter("token");
String payerID = redirectUri.getQueryParameter("PayerID");
progressbar = findViewById(R.id.progressbar);
progressbar.setVisibility(View.INVISIBLE);
//set the orderID string to the UI
orderID_label = (TextView) findViewById(R.id.orderID);
orderID_label.setText("Checkout ID: " +orderID);
payerID_label = (TextView) findViewById(R.id.payerid);
payerID_label.setText("Je Betaler Id is: " +payerID);
paymentAmount_label = (TextView) findViewById(R.id.amt);
paymentAmount_label.setText(String.format("Te betalen: € %.02f", KoalaDataRepository.getInstance().mWinkelMandje.getValue().mTotalPrice));
//add an onClick listener to the confirm button
confirm_btn = findViewById(R.id.confirm_btn);
confirm_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
captureOrder(orderID); //function to finalize the payment
}
});
annuleren_btn= findViewById(R.id.annuleren_btn);
annuleren_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
returnToOrderZonderConfirm();
}
});
}
void captureOrder(String orderID){
//get the accessToken from MainActivity
progressbar.setVisibility(View.VISIBLE);
String accessToken = KoalaDataRepository.getInstance().PaypalAccessToken;
AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Accept", "application/json");
client.addHeader("Content-type", "application/json");
client.addHeader("Authorization", "Bearer " + accessToken);
client.post("https://api-m.sandbox.paypal.com/v2/checkout/orders/"+orderID+"/capture", new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String response, Throwable throwable) {
Log.i("RESPONSE", response);
}
@Override
public void onSuccess(int statusCode, Header[] headers, String response) {
// eerst het resultaat van call verwerken om paymentid op te halen
String paymentId = "";
try {
JSONObject jsonResponse = new JSONObject(response);
String orderId = jsonResponse.getString("id"); // This is the order ID
JSONArray purchaseUnits = jsonResponse.getJSONArray("purchase_units");
if (purchaseUnits.length() > 0) {
JSONObject purchaseUnit = purchaseUnits.getJSONObject(0);
JSONArray payments = purchaseUnit.getJSONObject("payments").getJSONArray("captures");
if (payments.length() > 0) {
JSONObject payment = payments.getJSONObject(0);
paymentId = payment.getString("id"); // dit is de payment id
}
}
} catch (JSONException e) {
e.printStackTrace();
}
KoalaDataRepository repo = KoalaDataRepository.getInstance();
WinkelMandje mandje = repo.mWinkelMandje.getValue();
mandje.mPayPalPaymentId = paymentId;
Date currentDate = new Date();
mandje.mPayedOnDate = new Timestamp(currentDate.getTime());
repo.mWinkelMandje.setValue(mandje);
// order opslaan in db
Task_SendOrderToDB taak = new Task_SendOrderToDB();
taak.execute(mandje);
// 3 seconden wachten vooraleer naar fragment te springen om tijd te geven order op te slaan
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//redirect back to home page of app
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeSucces");
intent.putExtra("AfgeslotenOrderId",orderID);
intent.putExtra("AfgeslotenPaymentId",mandje.mPayPalPaymentId);
progressbar.setVisibility(View.INVISIBLE);
startActivity(intent);
}
}, 3000); // 3000ms delay
}
});
}
public void returnToOrderZonderConfirm() {
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeAnnuleren");
startActivity(intent);
}
} | MRoeland/KoalaExpress | app/src/main/java/be/ehb/koalaexpress/CheckoutActivity.java | 1,762 | // 3 seconden wachten vooraleer naar fragment te springen om tijd te geven order op te slaan | line_comment | nl | package be.ehb.koalaexpress;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import be.ehb.koalaexpress.Tasks.Task_SendOrderToDB;
import be.ehb.koalaexpress.models.WinkelMandje;
import cz.msebera.android.httpclient.Header;
public class CheckoutActivity extends AppCompatActivity {
TextView orderID_label;
TextView payerID_label;
TextView paymentAmount_label;
Button confirm_btn;
Button annuleren_btn;
ProgressBar progressbar;
public String orderID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hiding ActionBar
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
setContentView(R.layout.activity_checkout);
//get the orderID from the query parameter
Uri redirectUri = getIntent().getData();
List<String> segmentsInUrl = redirectUri.getPathSegments();
//hier kan je succes of failure halen uit de segmenstInURL
orderID = redirectUri.getQueryParameter("token");
String payerID = redirectUri.getQueryParameter("PayerID");
progressbar = findViewById(R.id.progressbar);
progressbar.setVisibility(View.INVISIBLE);
//set the orderID string to the UI
orderID_label = (TextView) findViewById(R.id.orderID);
orderID_label.setText("Checkout ID: " +orderID);
payerID_label = (TextView) findViewById(R.id.payerid);
payerID_label.setText("Je Betaler Id is: " +payerID);
paymentAmount_label = (TextView) findViewById(R.id.amt);
paymentAmount_label.setText(String.format("Te betalen: € %.02f", KoalaDataRepository.getInstance().mWinkelMandje.getValue().mTotalPrice));
//add an onClick listener to the confirm button
confirm_btn = findViewById(R.id.confirm_btn);
confirm_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
captureOrder(orderID); //function to finalize the payment
}
});
annuleren_btn= findViewById(R.id.annuleren_btn);
annuleren_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
returnToOrderZonderConfirm();
}
});
}
void captureOrder(String orderID){
//get the accessToken from MainActivity
progressbar.setVisibility(View.VISIBLE);
String accessToken = KoalaDataRepository.getInstance().PaypalAccessToken;
AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Accept", "application/json");
client.addHeader("Content-type", "application/json");
client.addHeader("Authorization", "Bearer " + accessToken);
client.post("https://api-m.sandbox.paypal.com/v2/checkout/orders/"+orderID+"/capture", new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String response, Throwable throwable) {
Log.i("RESPONSE", response);
}
@Override
public void onSuccess(int statusCode, Header[] headers, String response) {
// eerst het resultaat van call verwerken om paymentid op te halen
String paymentId = "";
try {
JSONObject jsonResponse = new JSONObject(response);
String orderId = jsonResponse.getString("id"); // This is the order ID
JSONArray purchaseUnits = jsonResponse.getJSONArray("purchase_units");
if (purchaseUnits.length() > 0) {
JSONObject purchaseUnit = purchaseUnits.getJSONObject(0);
JSONArray payments = purchaseUnit.getJSONObject("payments").getJSONArray("captures");
if (payments.length() > 0) {
JSONObject payment = payments.getJSONObject(0);
paymentId = payment.getString("id"); // dit is de payment id
}
}
} catch (JSONException e) {
e.printStackTrace();
}
KoalaDataRepository repo = KoalaDataRepository.getInstance();
WinkelMandje mandje = repo.mWinkelMandje.getValue();
mandje.mPayPalPaymentId = paymentId;
Date currentDate = new Date();
mandje.mPayedOnDate = new Timestamp(currentDate.getTime());
repo.mWinkelMandje.setValue(mandje);
// order opslaan in db
Task_SendOrderToDB taak = new Task_SendOrderToDB();
taak.execute(mandje);
// 3 seconden<SUF>
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//redirect back to home page of app
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeSucces");
intent.putExtra("AfgeslotenOrderId",orderID);
intent.putExtra("AfgeslotenPaymentId",mandje.mPayPalPaymentId);
progressbar.setVisibility(View.INVISIBLE);
startActivity(intent);
}
}, 3000); // 3000ms delay
}
});
}
public void returnToOrderZonderConfirm() {
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeAnnuleren");
startActivity(intent);
}
} |
121263_0 | //bestandsnaam: Oef2.java //<-- uitzonderlijke zelf importerende bibliotheek (moet dus niet in staan feitelijk)
/**
*De klasse Oef2 is een java applicatie
*
*@author Sophie Moons
*@version 1,0
*/
import java.lang.*;
public class Oef2{
/**
*Dit is een main function, hier start het programma
*@param args -> hiermee kan een array meegegeven worden via command line
*/
public static void main(String args[])
{
String[] dagen={"zondag","maandag","dinsdag","woensdag","donderdag","vrijdag","zaterdag"};
int h=1;
System.out.println("Data februari 2009:\n");
while (h<29) //28 dagen toen
{
for(int i=0;i<dagen.length;i++)
{
System.out.println(dagen[i]+" "+h+" februari");
h++;
}
}
}//einde main
}//einde program | MTA-Digital-Broadcast-2/A-Moons-Sophie-De-Cock-Nicolas-Project-MHP | Sophie Moons/Labo Java/blz19/Oef2.java | 263 | //bestandsnaam: Oef2.java //<-- uitzonderlijke zelf importerende bibliotheek (moet dus niet in staan feitelijk) | line_comment | nl | //bestandsnaam: Oef2.java<SUF>
/**
*De klasse Oef2 is een java applicatie
*
*@author Sophie Moons
*@version 1,0
*/
import java.lang.*;
public class Oef2{
/**
*Dit is een main function, hier start het programma
*@param args -> hiermee kan een array meegegeven worden via command line
*/
public static void main(String args[])
{
String[] dagen={"zondag","maandag","dinsdag","woensdag","donderdag","vrijdag","zaterdag"};
int h=1;
System.out.println("Data februari 2009:\n");
while (h<29) //28 dagen toen
{
for(int i=0;i<dagen.length;i++)
{
System.out.println(dagen[i]+" "+h+" februari");
h++;
}
}
}//einde main
}//einde program |
14027_0 | import java.lang.*;
public class EersteProg
{
public static void main(String args[])
{
System.out.println(~10);
/*
Alle bits worden geinverteerd.
In het (2's complement) systeem is er altijd een tekenbit, als deze 1 is word het getal negatief.
Ook word de werking omgekeerd, de getallen worden aangeduid door 0 i.p.v. 10.
Echter word in het 2's complement systeem op het einde nog +1 gedaan waardoor het getal negatief -10 word.
Dit is hier echter niet gebeurd, daardoor is het resultaat -11;
*/
}
} | MTA-Digital-Broadcast-2/B-Danckers-Koen-Sonck-Joris-Project-MHP | Koen Danckers/Labojava/blz17/EersteProg.java | 188 | /*
Alle bits worden geinverteerd.
In het (2's complement) systeem is er altijd een tekenbit, als deze 1 is word het getal negatief.
Ook word de werking omgekeerd, de getallen worden aangeduid door 0 i.p.v. 10.
Echter word in het 2's complement systeem op het einde nog +1 gedaan waardoor het getal negatief -10 word.
Dit is hier echter niet gebeurd, daardoor is het resultaat -11;
*/ | block_comment | nl | import java.lang.*;
public class EersteProg
{
public static void main(String args[])
{
System.out.println(~10);
/*
Alle bits worden<SUF>*/
}
} |
204127_4 | /**
* Oefening 1.11
* @author Matthew Smet
* @import importeren van nodige libraries
*/
import java.lang.*;
/**
* klasse Eersteprog gebaseerd op oefening 1.11 met 2 methoden
* Methode main met @param args array van strings met meegegeven parameters
* Methode drukaf met @param integer m
*/
public class Eersteprog
{
public static void main(String args[])
{
//Methode drukaf word opgeroepen met parameter 100
drukaf(100);
}
private static void(int m)
{
//Locale variablen wordt aangemaakt(a)
int a;
//herhaalt de lus 100x (meegegeven parameter)
for (a=0;a<m;a++)
{
//print het getal uit in de cmd
System.out.println(a);
}
}
} | MTA-Digital-Broadcast-2/C-Vdovlov-Evgeni-Smet-Matthew-Project-MHP | Matthew smet - Oefeningen Java + mhp/LaboJava/blz12/Eersteprog.java | 249 | //herhaalt de lus 100x (meegegeven parameter) | line_comment | nl | /**
* Oefening 1.11
* @author Matthew Smet
* @import importeren van nodige libraries
*/
import java.lang.*;
/**
* klasse Eersteprog gebaseerd op oefening 1.11 met 2 methoden
* Methode main met @param args array van strings met meegegeven parameters
* Methode drukaf met @param integer m
*/
public class Eersteprog
{
public static void main(String args[])
{
//Methode drukaf word opgeroepen met parameter 100
drukaf(100);
}
private static void(int m)
{
//Locale variablen wordt aangemaakt(a)
int a;
//herhaalt de<SUF>
for (a=0;a<m;a++)
{
//print het getal uit in de cmd
System.out.println(a);
}
}
} |
74028_0 | /**
* @author Van den Heuvel Mike
* @version 1,0
*/
public class oef6{
public static void main(String args[]){
int a[] = {12,34,56,78,123,234,99,88};
int grootste = 0;
for(int i = 0;i<8;i++){
if(a[i]>grootste){
grootste=a[i];
}
}
System.out.println(grootste);
}
} | MTA-Digital-Broadcast-2/D-Van-den-Heuvel-Mike-Project-MHP | Mike Van den Heuvel - oefeningen java/blz19/oef6/oef6.java | 135 | /**
* @author Van den Heuvel Mike
* @version 1,0
*/ | block_comment | nl | /**
* @author Van den<SUF>*/
public class oef6{
public static void main(String args[]){
int a[] = {12,34,56,78,123,234,99,88};
int grootste = 0;
for(int i = 0;i<8;i++){
if(a[i]>grootste){
grootste=a[i];
}
}
System.out.println(grootste);
}
} |
22068_0 | package Oef4;
public class PartTimeWerknemer extends Werknemer {
public int urenGewerkt;
public PartTimeWerknemer( String voornaam, String achternaam, int nr, float sal, int urengw)
{
super(voornaam, achternaam, nr, sal);
this.urenGewerkt=urengw;
}
public float getWeekLoon() {
return this.salaris * (float)urenGewerkt;
}
public void salarisVerhogen(int percentage) {
if (percentage>5) { System.out.println("Fout: parttimewerknemers kunnen niet meer dan 5% opslag krijgen"); }
else
super.salarisVerhogen(percentage); // roep methode van Werknemer aan
}
} | MTA-Digital-Broadcast-2/E-Verberckt-Lenn-Belmans-Robin-Project-MHP | Verberckt-Lenn/blz31/Oef4/PartTimeWerknemer.java | 216 | // roep methode van Werknemer aan | line_comment | nl | package Oef4;
public class PartTimeWerknemer extends Werknemer {
public int urenGewerkt;
public PartTimeWerknemer( String voornaam, String achternaam, int nr, float sal, int urengw)
{
super(voornaam, achternaam, nr, sal);
this.urenGewerkt=urengw;
}
public float getWeekLoon() {
return this.salaris * (float)urenGewerkt;
}
public void salarisVerhogen(int percentage) {
if (percentage>5) { System.out.println("Fout: parttimewerknemers kunnen niet meer dan 5% opslag krijgen"); }
else
super.salarisVerhogen(percentage); // roep methode<SUF>
}
} |
115929_1 | package hellotvxlet;
import java.awt.event.ActionEvent;
import javax.tv.xlet.*;
import org.dvb.event.UserEvent;
import org.havi.ui.*;
import org.davic.resources.*;
import org.dvb.event.EventManager;
import org.havi.ui.event.*;
import org.havi.ui.event.HActionListener;
import org.dvb.event.UserEvent;
import org.dvb.event.UserEventListener;
import org.dvb.event.UserEventRepository;
public class HelloTVXlet implements Xlet, ResourceClient, HBackgroundImageListener, UserEventListener {
private HScreen screen;
private HBackgroundDevice bgDevice;
private HBackgroundConfigTemplate bgTemplate;
private HStillImageBackgroundConfiguration bgConfiguration;
private HBackgroundImage agrondimg = new HBackgroundImage("pizza1.m2v");
private HBackgroundImage agrondimg2 = new HBackgroundImage("pizza2.m2v");
private HBackgroundImage agrondimg3 = new HBackgroundImage("pizza3.m2v");
private HBackgroundImage agrondimg4 = new HBackgroundImage("pizza4.m2v");
public void notifyRelease(ResourceProxy proxy) {}
public void release(ResourceProxy proxy) {}
public boolean requestRelease(ResourceProxy proxy, Object requestData) {
return false;
}
public void imageLoaded(HBackgroundImageEvent e)
{
try {
bgConfiguration.displayImage(agrondimg);
}
catch(Exception s){
System.out.println(s.toString());
}
}
public void imageLoadFailed(HBackgroundImageEvent e)
{
System.out.println("Image kan niet geladen worden.");
}
public void destroyXlet(boolean unconditional) {
System.out.println("DestroyXlet");
agrondimg.flush();
}
public void pauseXlet() {
System.out.println("PauseXlet");
}
public void startXlet() {
System.out.println("StartXlet");
//image laden
agrondimg.load(this);
}
public HelloTVXlet() { }
public void initXlet(XletContext context) {
//HScreen object opvragen
screen = HScreen.getDefaultHScreen();
//HBGDevice opvragen
bgDevice = screen.getDefaultHBackgroundDevice();
//HBGDevice proberen te reserveren
if (bgDevice.reserveDevice(this)){
System.out.println("Background device has been reserved");
}
else {
System.out.println("Background image device cannot be reserved");
}
//template maken
bgTemplate = new HBackgroundConfigTemplate();
//CFGinstelling "STILL_IMAGE"
bgTemplate.setPreference(HBackgroundConfigTemplate.STILL_IMAGE, HBackgroundConfigTemplate.REQUIRED);
//CFG aanvragen en activeren indien OK
bgConfiguration = (HStillImageBackgroundConfiguration)bgDevice.getBestConfiguration(bgTemplate);
try {
bgDevice.setBackgroundConfiguration(bgConfiguration);
}
catch (java.lang.Exception e){
System.out.println(e.toString());
}
UserEventRepository uev = new UserEventRepository("mijn verzameling");
uev.addKey(HRcEvent.VK_LEFT);
uev.addKey(HRcEvent.VK_RIGHT);
EventManager.getInstance().addUserEventListener(this, uev);
}
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
//Tekst = e.getActionCommand();
if (e.getActionCommand().toString().equals("Help"))
{
System.out.println("Help");
// knop1 = (HTextButton) new HStaticText("TestTest");
//scene.validate();
}
}
public void userEventReceived(UserEvent e) {
if (e.getType()==HRcEvent.KEY_PRESSED) {
//enkel indrukken (niet loslaten)
switch (e.getCode())
{
case HRcEvent.VK_LEFT:
System.out.println("Links");
try {
bgConfiguration.displayImage(agrondimg2);
agrondimg2.load(this);
}
catch(Exception s){
System.out.println(s.toString());
}
break;
case HRcEvent.VK_RIGHT:
System.out.println("Rechts");
break;
/* case HRcEvent.VK_DOWN:
System.out.println("Onder");
mc.verplaatssterren(0,10);
break;*/
}
}
}
}
| MTA-Digital-Broadcast-2/G-Cludts-Jasper-Kennes-Mats-Project-MHP | Kennes-Mats/Labo MHP/Blu-ray_Disc_Java_Project_VoorbeeldAchtegrondJuiste/src/hellotvxlet/HelloTVXlet.java | 1,313 | //HBGDevice proberen te reserveren | line_comment | nl | package hellotvxlet;
import java.awt.event.ActionEvent;
import javax.tv.xlet.*;
import org.dvb.event.UserEvent;
import org.havi.ui.*;
import org.davic.resources.*;
import org.dvb.event.EventManager;
import org.havi.ui.event.*;
import org.havi.ui.event.HActionListener;
import org.dvb.event.UserEvent;
import org.dvb.event.UserEventListener;
import org.dvb.event.UserEventRepository;
public class HelloTVXlet implements Xlet, ResourceClient, HBackgroundImageListener, UserEventListener {
private HScreen screen;
private HBackgroundDevice bgDevice;
private HBackgroundConfigTemplate bgTemplate;
private HStillImageBackgroundConfiguration bgConfiguration;
private HBackgroundImage agrondimg = new HBackgroundImage("pizza1.m2v");
private HBackgroundImage agrondimg2 = new HBackgroundImage("pizza2.m2v");
private HBackgroundImage agrondimg3 = new HBackgroundImage("pizza3.m2v");
private HBackgroundImage agrondimg4 = new HBackgroundImage("pizza4.m2v");
public void notifyRelease(ResourceProxy proxy) {}
public void release(ResourceProxy proxy) {}
public boolean requestRelease(ResourceProxy proxy, Object requestData) {
return false;
}
public void imageLoaded(HBackgroundImageEvent e)
{
try {
bgConfiguration.displayImage(agrondimg);
}
catch(Exception s){
System.out.println(s.toString());
}
}
public void imageLoadFailed(HBackgroundImageEvent e)
{
System.out.println("Image kan niet geladen worden.");
}
public void destroyXlet(boolean unconditional) {
System.out.println("DestroyXlet");
agrondimg.flush();
}
public void pauseXlet() {
System.out.println("PauseXlet");
}
public void startXlet() {
System.out.println("StartXlet");
//image laden
agrondimg.load(this);
}
public HelloTVXlet() { }
public void initXlet(XletContext context) {
//HScreen object opvragen
screen = HScreen.getDefaultHScreen();
//HBGDevice opvragen
bgDevice = screen.getDefaultHBackgroundDevice();
//HBGDevice proberen<SUF>
if (bgDevice.reserveDevice(this)){
System.out.println("Background device has been reserved");
}
else {
System.out.println("Background image device cannot be reserved");
}
//template maken
bgTemplate = new HBackgroundConfigTemplate();
//CFGinstelling "STILL_IMAGE"
bgTemplate.setPreference(HBackgroundConfigTemplate.STILL_IMAGE, HBackgroundConfigTemplate.REQUIRED);
//CFG aanvragen en activeren indien OK
bgConfiguration = (HStillImageBackgroundConfiguration)bgDevice.getBestConfiguration(bgTemplate);
try {
bgDevice.setBackgroundConfiguration(bgConfiguration);
}
catch (java.lang.Exception e){
System.out.println(e.toString());
}
UserEventRepository uev = new UserEventRepository("mijn verzameling");
uev.addKey(HRcEvent.VK_LEFT);
uev.addKey(HRcEvent.VK_RIGHT);
EventManager.getInstance().addUserEventListener(this, uev);
}
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
//Tekst = e.getActionCommand();
if (e.getActionCommand().toString().equals("Help"))
{
System.out.println("Help");
// knop1 = (HTextButton) new HStaticText("TestTest");
//scene.validate();
}
}
public void userEventReceived(UserEvent e) {
if (e.getType()==HRcEvent.KEY_PRESSED) {
//enkel indrukken (niet loslaten)
switch (e.getCode())
{
case HRcEvent.VK_LEFT:
System.out.println("Links");
try {
bgConfiguration.displayImage(agrondimg2);
agrondimg2.load(this);
}
catch(Exception s){
System.out.println(s.toString());
}
break;
case HRcEvent.VK_RIGHT:
System.out.println("Rechts");
break;
/* case HRcEvent.VK_DOWN:
System.out.println("Onder");
mc.verplaatssterren(0,10);
break;*/
}
}
}
}
|
32728_0 | import java.lang.*;
/**
*"Eersteprog" is een java applicatie
*@author Alex Spildooren
*/
public class Eersteprog{
/**
*"Main" is de hoofd mothode */
public static void main(String args[])
{
drukaf(100);
}
/**
*"Drukaf" is de mothode die voor de cijferkes zorgt*/
private static void drukaf(int m)
{
int a;
for (a=0;a<m;a++)
{
System.out.println(a);
}
}
}
| MTA-Digital-Broadcast-2/H-Jacobs-Beau-Spildooren-Alex-Project-MHP | Spildooren-Alex/Labojava/blz12/Eersteprog.java | 172 | /**
*"Eersteprog" is een java applicatie
*@author Alex Spildooren
*/ | block_comment | nl | import java.lang.*;
/**
*"Eersteprog" is een<SUF>*/
public class Eersteprog{
/**
*"Main" is de hoofd mothode */
public static void main(String args[])
{
drukaf(100);
}
/**
*"Drukaf" is de mothode die voor de cijferkes zorgt*/
private static void drukaf(int m)
{
int a;
for (a=0;a<m;a++)
{
System.out.println(a);
}
}
}
|
22062_0 | public class PartTimeWerknemer extends Werknemer {
public int urenGewerkt;
public PartTimeWerknemer( String voornaam, String achternaam, int nr, float sal, int urengw)
{
super(voornaam, achternaam, nr, sal);
this.urenGewerkt=urengw;
}
public float getWeekLoon() {
return this.salaris * (float)urenGewerkt;
}
public void salarisVerhogen(int percentage) {
if (percentage>5) { System.out.println("Fout: parttimewerknemer kunnen niet meer dan 5% opslag krijgen"); }
else
super.salarisVerhogen(percentage); // roep methode van Werknemer aan
}
} | MTA-Digital-Broadcast-2/I-Willems-Andy-Hendrickx-Matthias-Project-MHP | Willems-Andy/blz31/Oef7/PartTimeWerknemer.java | 209 | // roep methode van Werknemer aan | line_comment | nl | public class PartTimeWerknemer extends Werknemer {
public int urenGewerkt;
public PartTimeWerknemer( String voornaam, String achternaam, int nr, float sal, int urengw)
{
super(voornaam, achternaam, nr, sal);
this.urenGewerkt=urengw;
}
public float getWeekLoon() {
return this.salaris * (float)urenGewerkt;
}
public void salarisVerhogen(int percentage) {
if (percentage>5) { System.out.println("Fout: parttimewerknemer kunnen niet meer dan 5% opslag krijgen"); }
else
super.salarisVerhogen(percentage); // roep methode<SUF>
}
} |
52528_5 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hellotvxlet;
import java.awt.*;
import org.dvb.ui.*;
import java.awt.*;
import org.dvb.ui.*;
import org.havi.ui.*;
import java.lang.Object;
/**
*
* @author student
*/
public class PlayerBlock extends Sprite {
//Falling
//Deze hoeven geen properties te hebben, want zijn enkel nodig voor PlayerBlock
private boolean _isFalling = true;
private int _velocityY = 20; //Hoe hard je naar beneden valt
//Jump
private boolean _isJumping = false;
private boolean _isStartJumping = false;
private int _jumpForce = 9;
private int _isStartJumpForce = 9;
//getter
public boolean getIsMovingLeft() {
return this._isMovingLeft;
}
//setter
public void setIsMovingLeft(boolean initIsMovingLeft) {
this._isMovingLeft = initIsMovingLeft;
this._isMovingRight = false; //gn 2 toetsen tegelijk indrukken
}
//getter
public boolean getIsMovingRight() {
return this._isMovingRight;
}
//setter
public void setIsMovingRight(boolean initIsMovingRight) {
this._isMovingRight = initIsMovingRight;
this._isMovingLeft = false; //gn 2 toetsen tegelijk indrukken
}
//getter
public boolean getIsJumping()
{
return this._isJumping;
}
//setter
public void setIsJumping(boolean initIsJumping)
{
this._isJumping = initIsJumping;
//this._isFalling = false; //kan niet vallen terwijl hij springt
}
//getter
public int getJumpforce()
{
return this._jumpForce;
}
//setter
public void setJumpForce(int initJumpForce)
{
this._jumpForce = initJumpForce;
}
//getter
public int getStartJumpforce()
{
return this._isStartJumpForce;
}
//getter
public boolean getIsFalling()
{
return this._isFalling;
}
//setter
public void setIsFalling(boolean initIsFalling)
{
this._isFalling = initIsFalling;
}
//getter
public boolean getIsStartJumping() {
return this._isStartJumping;
}
//setter
public void setIsStartJumping(boolean initIsStartJumping)
{
this._isStartJumping = initIsStartJumping;
}
public PlayerBlock(String initBitmapNaam, int initXPos, int initYPos, int initWidth, int initHeight, int initVelocityX )
{
super(initBitmapNaam, initXPos, initYPos, initWidth, initHeight, initVelocityX);
}
public void move()
{
// if (this.getIsBottomCollided())
// {
// System.out.println("bottom coll: " + this.getIsBottomCollided());
// }
// if (this.getIsTopCollided())
// {
// System.out.println("top coll: " + this.getIsTopCollided());
// }
//
// if (this.getIsLeftCollided())
// {
// System.out.println("left coll: " + this.getIsLeftCollided());
// }
//
// if (this.getIsRightCollided())
// {
// System.out.println("right coll: " + this.getIsRightCollided());
// }
//
//
//
//System.out.println("move");
if (this._isMovingLeft == true)
{
// System.out.println("Playerblock is moving left.");
this._posX -= this._velocityX; //Left
}
else if (this._isMovingRight == true)
{
// System.out.println("Playerblock is moving right.");
this._posX += this._velocityX; //right
}
//hij valt altijd
this._posY += this._velocityY;
//vallen wordt tegengewerkt als hij springt
// System.out.println("isjumping : " + this._isJumping);
// System.out.println("isstartjumping : " + this._isStartJumping);
if (this._isJumping == true || this._isStartJumping == true) //jumping
{
if (this._posY < this._posY + this._jumpForce && this._isFalling == false)
{
// System.out.println("jumping");
this._posY -= this._velocityY;
this._posY -= this._velocityY;
this._jumpForce--;
this._isStartJumping = true;
}
else
{
this._isFalling = true;
}
}
//// //tijdelijke oplossing voor implementatie van colliden
//// //als playerblock beneden komt, moet hij stoppen met vallen
//// /*if (this._posY >= this._screenSize.height - 150)
//// {
//// System.out.print("Playerblock stops falling.");
//// this._isFalling = false;
////
//// }*/
////
////
//// /*
//// case 2:
//// this._posY -= this._jumpForce; //Up
//// break;
//// case 3:
////
//// break;
//// case 4:
//// this._posY += this._jumpForce; //down
//// break;*/
////
//// this.setBounds(this._posX, this._posY, _image.getWidth(this), _image.getHeight(this));
// }
//
//
//
// public void move(int direction)
// {
// switch (direction)
// {
// case 1:
// this._posX -= this._velocityX; //Left
// break;
// case 2:
// this._posY -= this._jumpForce; //Up
// break;
// case 3:
// this._posX += this._velocityX; //right
// break;
// case 4:
// this._posY += this._jumpForce; //down
// break;
// }
this.setBounds(this._posX, this._posY, _image.getWidth(this), _image.getHeight(this));
}
public boolean getIsBottomCollided(Sprite sprite)
{
Rectangle otherSpriteRectangle = new Rectangle(sprite._posX, (sprite._posY + sprite._height - this._velocityY), sprite._width, this._velocityY);
Rectangle _playerblockRectangle = new Rectangle(this._posX, this._posY, this._width, this._height);
return otherSpriteRectangle.intersects(_playerblockRectangle);
}
public boolean getIsTopCollided(Sprite sprite)
{
Rectangle otherSpriteRectangle = new Rectangle(sprite._posX, sprite._posY, sprite._width, sprite._height);
Rectangle _playerblockRectangle = new Rectangle(this._posX, this._posY, this._width, this._height);
return otherSpriteRectangle.intersects(_playerblockRectangle);
}
public boolean getIsLeftCollided(Sprite sprite)
{
Rectangle otherSpriteRectangle = new Rectangle(sprite._posX, sprite._posY + this._velocityY, this._velocityX, sprite._height - (2 * this._velocityY));
Rectangle _playerblockRectangle = new Rectangle(this._posX, this._posY, this._width, this._height);
return otherSpriteRectangle.intersects(_playerblockRectangle);
}
public boolean getIsRightCollided(Sprite sprite)
{
Rectangle otherSpriteRectangle = new Rectangle(sprite._posX + sprite._width - this._velocityX, sprite._posY + this._velocityY, this._velocityX, sprite._height - (2 * this._velocityY));
Rectangle _playerblockRectangle = new Rectangle(this._posX, this._posY, this._width, this._height);
return otherSpriteRectangle.intersects(_playerblockRectangle);
}
public boolean getIsCollided(Sprite sprite)
{
Rectangle otherSpriteRectangle = new Rectangle(sprite._posX, sprite._posY, sprite._width, sprite._height);
Rectangle _playerblockRectangle = new Rectangle(this._posX, this._posY, this._width, this._height);
return otherSpriteRectangle.intersects(_playerblockRectangle);
}
}
| MTA-Digital-Broadcast-2/J-Cools-Giele-Peeters-Jim-Project-MHP | project/src/hellotvxlet/PlayerBlock.java | 2,530 | //gn 2 toetsen tegelijk indrukken | line_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hellotvxlet;
import java.awt.*;
import org.dvb.ui.*;
import java.awt.*;
import org.dvb.ui.*;
import org.havi.ui.*;
import java.lang.Object;
/**
*
* @author student
*/
public class PlayerBlock extends Sprite {
//Falling
//Deze hoeven geen properties te hebben, want zijn enkel nodig voor PlayerBlock
private boolean _isFalling = true;
private int _velocityY = 20; //Hoe hard je naar beneden valt
//Jump
private boolean _isJumping = false;
private boolean _isStartJumping = false;
private int _jumpForce = 9;
private int _isStartJumpForce = 9;
//getter
public boolean getIsMovingLeft() {
return this._isMovingLeft;
}
//setter
public void setIsMovingLeft(boolean initIsMovingLeft) {
this._isMovingLeft = initIsMovingLeft;
this._isMovingRight = false; //gn 2 toetsen tegelijk indrukken
}
//getter
public boolean getIsMovingRight() {
return this._isMovingRight;
}
//setter
public void setIsMovingRight(boolean initIsMovingRight) {
this._isMovingRight = initIsMovingRight;
this._isMovingLeft = false; //gn 2<SUF>
}
//getter
public boolean getIsJumping()
{
return this._isJumping;
}
//setter
public void setIsJumping(boolean initIsJumping)
{
this._isJumping = initIsJumping;
//this._isFalling = false; //kan niet vallen terwijl hij springt
}
//getter
public int getJumpforce()
{
return this._jumpForce;
}
//setter
public void setJumpForce(int initJumpForce)
{
this._jumpForce = initJumpForce;
}
//getter
public int getStartJumpforce()
{
return this._isStartJumpForce;
}
//getter
public boolean getIsFalling()
{
return this._isFalling;
}
//setter
public void setIsFalling(boolean initIsFalling)
{
this._isFalling = initIsFalling;
}
//getter
public boolean getIsStartJumping() {
return this._isStartJumping;
}
//setter
public void setIsStartJumping(boolean initIsStartJumping)
{
this._isStartJumping = initIsStartJumping;
}
public PlayerBlock(String initBitmapNaam, int initXPos, int initYPos, int initWidth, int initHeight, int initVelocityX )
{
super(initBitmapNaam, initXPos, initYPos, initWidth, initHeight, initVelocityX);
}
public void move()
{
// if (this.getIsBottomCollided())
// {
// System.out.println("bottom coll: " + this.getIsBottomCollided());
// }
// if (this.getIsTopCollided())
// {
// System.out.println("top coll: " + this.getIsTopCollided());
// }
//
// if (this.getIsLeftCollided())
// {
// System.out.println("left coll: " + this.getIsLeftCollided());
// }
//
// if (this.getIsRightCollided())
// {
// System.out.println("right coll: " + this.getIsRightCollided());
// }
//
//
//
//System.out.println("move");
if (this._isMovingLeft == true)
{
// System.out.println("Playerblock is moving left.");
this._posX -= this._velocityX; //Left
}
else if (this._isMovingRight == true)
{
// System.out.println("Playerblock is moving right.");
this._posX += this._velocityX; //right
}
//hij valt altijd
this._posY += this._velocityY;
//vallen wordt tegengewerkt als hij springt
// System.out.println("isjumping : " + this._isJumping);
// System.out.println("isstartjumping : " + this._isStartJumping);
if (this._isJumping == true || this._isStartJumping == true) //jumping
{
if (this._posY < this._posY + this._jumpForce && this._isFalling == false)
{
// System.out.println("jumping");
this._posY -= this._velocityY;
this._posY -= this._velocityY;
this._jumpForce--;
this._isStartJumping = true;
}
else
{
this._isFalling = true;
}
}
//// //tijdelijke oplossing voor implementatie van colliden
//// //als playerblock beneden komt, moet hij stoppen met vallen
//// /*if (this._posY >= this._screenSize.height - 150)
//// {
//// System.out.print("Playerblock stops falling.");
//// this._isFalling = false;
////
//// }*/
////
////
//// /*
//// case 2:
//// this._posY -= this._jumpForce; //Up
//// break;
//// case 3:
////
//// break;
//// case 4:
//// this._posY += this._jumpForce; //down
//// break;*/
////
//// this.setBounds(this._posX, this._posY, _image.getWidth(this), _image.getHeight(this));
// }
//
//
//
// public void move(int direction)
// {
// switch (direction)
// {
// case 1:
// this._posX -= this._velocityX; //Left
// break;
// case 2:
// this._posY -= this._jumpForce; //Up
// break;
// case 3:
// this._posX += this._velocityX; //right
// break;
// case 4:
// this._posY += this._jumpForce; //down
// break;
// }
this.setBounds(this._posX, this._posY, _image.getWidth(this), _image.getHeight(this));
}
public boolean getIsBottomCollided(Sprite sprite)
{
Rectangle otherSpriteRectangle = new Rectangle(sprite._posX, (sprite._posY + sprite._height - this._velocityY), sprite._width, this._velocityY);
Rectangle _playerblockRectangle = new Rectangle(this._posX, this._posY, this._width, this._height);
return otherSpriteRectangle.intersects(_playerblockRectangle);
}
public boolean getIsTopCollided(Sprite sprite)
{
Rectangle otherSpriteRectangle = new Rectangle(sprite._posX, sprite._posY, sprite._width, sprite._height);
Rectangle _playerblockRectangle = new Rectangle(this._posX, this._posY, this._width, this._height);
return otherSpriteRectangle.intersects(_playerblockRectangle);
}
public boolean getIsLeftCollided(Sprite sprite)
{
Rectangle otherSpriteRectangle = new Rectangle(sprite._posX, sprite._posY + this._velocityY, this._velocityX, sprite._height - (2 * this._velocityY));
Rectangle _playerblockRectangle = new Rectangle(this._posX, this._posY, this._width, this._height);
return otherSpriteRectangle.intersects(_playerblockRectangle);
}
public boolean getIsRightCollided(Sprite sprite)
{
Rectangle otherSpriteRectangle = new Rectangle(sprite._posX + sprite._width - this._velocityX, sprite._posY + this._velocityY, this._velocityX, sprite._height - (2 * this._velocityY));
Rectangle _playerblockRectangle = new Rectangle(this._posX, this._posY, this._width, this._height);
return otherSpriteRectangle.intersects(_playerblockRectangle);
}
public boolean getIsCollided(Sprite sprite)
{
Rectangle otherSpriteRectangle = new Rectangle(sprite._posX, sprite._posY, sprite._width, sprite._height);
Rectangle _playerblockRectangle = new Rectangle(this._posX, this._posY, this._width, this._height);
return otherSpriteRectangle.intersects(_playerblockRectangle);
}
}
|
172967_3 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hellotvxlet;
import org.havi.ui.*;
import java.awt.*;
import org.dvb.ui.*;
/**
*
* @author student
*/
public class Sprite extends HComponent {
private Image spaceship;
private MediaTracker mtrack;
//plaats en lovatie instellen in de constructor
public Sprite(String file, int x, int y)
{
spaceship = this.getToolkit().getImage(file);
mtrack = new MediaTracker(this);
mtrack.addImage(spaceship, 0);
try
{
mtrack.waitForAll(); // wacht tot alle bitmaps geladen zijn
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
this.setBounds(x, y, spaceship.getWidth(null), spaceship.getHeight(null)); //opgeven plaats en afmetingen bitmap
}
//paint methode overschrijven
public void paint(Graphics g)
{
g.drawImage(spaceship, 0, 0, null);
}
public void Verplaats(int x, int y)
{
this.setBounds(x, y, spaceship.getWidth(this), spaceship.getHeight(this));
}
}
| MTA-Digital-Broadcast-2/K-De-Maeyer-Didier-Schuddinck-Sam-Project-MHP | Didier De Maeyer/blz47/Oef1/HelloTVXlet/src/hellotvxlet/Sprite.java | 367 | // wacht tot alle bitmaps geladen zijn | line_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hellotvxlet;
import org.havi.ui.*;
import java.awt.*;
import org.dvb.ui.*;
/**
*
* @author student
*/
public class Sprite extends HComponent {
private Image spaceship;
private MediaTracker mtrack;
//plaats en lovatie instellen in de constructor
public Sprite(String file, int x, int y)
{
spaceship = this.getToolkit().getImage(file);
mtrack = new MediaTracker(this);
mtrack.addImage(spaceship, 0);
try
{
mtrack.waitForAll(); // wacht tot<SUF>
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
this.setBounds(x, y, spaceship.getWidth(null), spaceship.getHeight(null)); //opgeven plaats en afmetingen bitmap
}
//paint methode overschrijven
public void paint(Graphics g)
{
g.drawImage(spaceship, 0, 0, null);
}
public void Verplaats(int x, int y)
{
this.setBounds(x, y, spaceship.getWidth(this), spaceship.getHeight(this));
}
}
|
105966_1 | public class Main
{
public static void main(String args[])
{
Werknemer herman = new Werknemer("Herman", "Hermans", 1, 1000.0f);
Werknemer jan = new Werknemer("Jan", "Janssens", 2, 1000.0f);
Werknemer peter = new Werknemer("Peter", "Peeters", 3, 1000.0f);
Werknemer sander = new Werknemer("Sander", "Peeters", 4, 1000.0f);
//oef2
herman.salarisVerhogen(10);
peter.salarisVerhogen(10);
System.out.println(herman.voornaam + " verdient " + herman.getSalaris());
System.out.println(jan.voornaam + " verdient " + jan.getSalaris());
System.out.println(peter.voornaam + " verdient " + peter.getSalaris());
System.out.println(sander.voornaam + " verdient " + sander.getSalaris());
//oef3
PartTimeMedewerker suzy= new PartTimeMedewerker("Suzy", "Wafels", 5, 10.0f, 20);
PartTimeMedewerker kelly = new PartTimeMedewerker("Kelly", "Luiaerts", 6, 10.0f, 20);
//oef 4
suzy.salarisVerhogen(10);
System.Out.println(suzy.voornaam + "verdient " + suzy.getSalaris());
//oef 5 + 6
System.Out.println(sander.voornaam + "verdient " + sander.getRSZ() + " RSZ");
System.Out.println(suzy.voornaam + "verdient " + suzy.getRSZ() + "% RSZ");
//oef 7
StudentWerknemer bert = new StudentWerknemer ("Bert", "Blokker", 7, 10.0f, 20);
System.out.println(bert.voornaam + " betaalt " + bert.getRSZ() + "% RSZ");
//oef 8+9
koen.betaal();
suzy.betaal();
bert.betaal();
//oef 10
Faktuur fakt1 = new Faktuur (1, 100);
fakt1.betaal();
//DEMO INTERFACES
Betaalbaar[] objecten = new Betaalbaar[4];
objecten[0]=bert;
objecten[1]=sander;
objecten[2]=fakt1; //faktuur!!
objecten[3]=suzy;
for (int i=0;i<=3;i++)
{
objecten[i].betaal(); //alle objecten zijn Betaalbaar
}
}
} | MTA-Digital-Broadcast-2/N-Peeters-Sander-Serrien-Steven-Project-MHP | SanderPeeters/blz31/Main.java | 771 | //alle objecten zijn Betaalbaar | line_comment | nl | public class Main
{
public static void main(String args[])
{
Werknemer herman = new Werknemer("Herman", "Hermans", 1, 1000.0f);
Werknemer jan = new Werknemer("Jan", "Janssens", 2, 1000.0f);
Werknemer peter = new Werknemer("Peter", "Peeters", 3, 1000.0f);
Werknemer sander = new Werknemer("Sander", "Peeters", 4, 1000.0f);
//oef2
herman.salarisVerhogen(10);
peter.salarisVerhogen(10);
System.out.println(herman.voornaam + " verdient " + herman.getSalaris());
System.out.println(jan.voornaam + " verdient " + jan.getSalaris());
System.out.println(peter.voornaam + " verdient " + peter.getSalaris());
System.out.println(sander.voornaam + " verdient " + sander.getSalaris());
//oef3
PartTimeMedewerker suzy= new PartTimeMedewerker("Suzy", "Wafels", 5, 10.0f, 20);
PartTimeMedewerker kelly = new PartTimeMedewerker("Kelly", "Luiaerts", 6, 10.0f, 20);
//oef 4
suzy.salarisVerhogen(10);
System.Out.println(suzy.voornaam + "verdient " + suzy.getSalaris());
//oef 5 + 6
System.Out.println(sander.voornaam + "verdient " + sander.getRSZ() + " RSZ");
System.Out.println(suzy.voornaam + "verdient " + suzy.getRSZ() + "% RSZ");
//oef 7
StudentWerknemer bert = new StudentWerknemer ("Bert", "Blokker", 7, 10.0f, 20);
System.out.println(bert.voornaam + " betaalt " + bert.getRSZ() + "% RSZ");
//oef 8+9
koen.betaal();
suzy.betaal();
bert.betaal();
//oef 10
Faktuur fakt1 = new Faktuur (1, 100);
fakt1.betaal();
//DEMO INTERFACES
Betaalbaar[] objecten = new Betaalbaar[4];
objecten[0]=bert;
objecten[1]=sander;
objecten[2]=fakt1; //faktuur!!
objecten[3]=suzy;
for (int i=0;i<=3;i++)
{
objecten[i].betaal(); //alle objecten<SUF>
}
}
} |
34559_0 | import java.lang.*;
/**
* De klasse StudentWerknemer is een Java klasse.
* @author Jolita Grazyte
*
*/
public class StudentWerknemer extends PartTimeWerknemer {
public int urenGewerkt;
public StudentWerknemer ( String voornaam, String achternaam, int nr, float sal, int urengw)
{
super(voornaam, achternaam, nr, sal, urengw );
this.setRSZ( 5.0f );
}
} | MTA-Digital-Broadcast-2/O-Van-den-Broeck-Jeroen-Gurbuz-Hasan-Project-MHP | Gurbuz_Hasan/Labojava/blz31/Oef7/StudentWerknemer.java | 146 | /**
* De klasse StudentWerknemer is een Java klasse.
* @author Jolita Grazyte
*
*/ | block_comment | nl | import java.lang.*;
/**
* De klasse StudentWerknemer<SUF>*/
public class StudentWerknemer extends PartTimeWerknemer {
public int urenGewerkt;
public StudentWerknemer ( String voornaam, String achternaam, int nr, float sal, int urengw)
{
super(voornaam, achternaam, nr, sal, urengw );
this.setRSZ( 5.0f );
}
} |
108463_1 | /**
* Deze klasse is een java programa
* @author Seppe Goossens
* @version 1.5
*/
import java.lang.*;
public class EersteProg{
/**
* Deze methode is de main methode
* @param args Dit zijn de command line parameters
*/
public static void main(String args[])
{
char c; //16 bits UNICODE ipv ASCII in C
c='E';
c++; //Wordt opgeslagen als een getal, dus dit kan, en zal F als resultaat hebben
System.out.println("c= "+c);
int a; //32 bits signed getal
byte b; //8 bits signed getal
short s; //16 bits
long l; //64 bits signed getal
float f; //32 bits
double d; //64 bits
a=5;
a=a+1;
f=3.3f; //f erachter zette zodat ge geen problemen krijgt
f=f+0.1f;
System.out.print("a="+a+" f="+f);
boolean x= (a>5);
System.out.println(x);
System.out.println("Dit is mijn eerste java programma.");
System.out.println("Dit is een " + "test " + args[0]);
}
} | MTA-Digital-Broadcast-2/P-Meysmans-Benno-Goossens-Seppe-Project-MHP | SeppeGoossens/Java/blz5/EersteProg.java | 351 | /**
* Deze methode is de main methode
* @param args Dit zijn de command line parameters
*/ | block_comment | nl | /**
* Deze klasse is een java programa
* @author Seppe Goossens
* @version 1.5
*/
import java.lang.*;
public class EersteProg{
/**
* Deze methode is<SUF>*/
public static void main(String args[])
{
char c; //16 bits UNICODE ipv ASCII in C
c='E';
c++; //Wordt opgeslagen als een getal, dus dit kan, en zal F als resultaat hebben
System.out.println("c= "+c);
int a; //32 bits signed getal
byte b; //8 bits signed getal
short s; //16 bits
long l; //64 bits signed getal
float f; //32 bits
double d; //64 bits
a=5;
a=a+1;
f=3.3f; //f erachter zette zodat ge geen problemen krijgt
f=f+0.1f;
System.out.print("a="+a+" f="+f);
boolean x= (a>5);
System.out.println(x);
System.out.println("Dit is mijn eerste java programma.");
System.out.println("Dit is een " + "test " + args[0]);
}
} |
11151_1 | import java.lang. *;
/**
* Deze klasse is een java programma
* @author Ruben Wouters
* @version 1,5
*/
public class EersteProg_4{
public static void main(String args[])
{
System.out.println(~10);
}
/* Verklaar het resultaat:
~ duidt op een NOT operator. Deze operator inverteert elke bit van het getal.
Om in 2's complement van 10 naar -10 te gaan, kan je alle bits inverteren en dan +1
Maar de +1 doe je niet hier, dus je komt op -11 uit
*/
} | MTA-Digital-Broadcast-2/Q-Van-Schevensteen-Dries-Wouters-Ruben-Project-MHP | Ruben Wouters/blz17/EersteProg.java | 169 | /* Verklaar het resultaat:
~ duidt op een NOT operator. Deze operator inverteert elke bit van het getal.
Om in 2's complement van 10 naar -10 te gaan, kan je alle bits inverteren en dan +1
Maar de +1 doe je niet hier, dus je komt op -11 uit
*/ | block_comment | nl | import java.lang. *;
/**
* Deze klasse is een java programma
* @author Ruben Wouters
* @version 1,5
*/
public class EersteProg_4{
public static void main(String args[])
{
System.out.println(~10);
}
/* Verklaar het resultaat:<SUF>*/
} |
112741_0 | import java.lang.*;
/**
* De klasse EersteProg is een Java applicatie
*
* @autthor Vic Denys
*
* @version 1.5
*/
public class Oef4 {
/**
* Dit is een main-functie. hier start het programma
* @param args Dit is een array van string waarmee parameters kunnen meegegeven worden.
*/
public static void main(String args[])
{
drukAf();
}
/**
* Negatief van 4302
*/
private static void drukAf()
{
int a = 4302;
int uitkomst = ~a + 1;
System.out.println(uitkomst);
}
} | MTA-Digital-Broadcast-2/R-Meeus-Sharon-Denys-Vic-Project-MHP | Vic Denys - oefeningen java + mhp/blz19/Oef4.java | 192 | /**
* De klasse EersteProg is een Java applicatie
*
* @autthor Vic Denys
*
* @version 1.5
*/ | block_comment | nl | import java.lang.*;
/**
* De klasse EersteProg<SUF>*/
public class Oef4 {
/**
* Dit is een main-functie. hier start het programma
* @param args Dit is een array van string waarmee parameters kunnen meegegeven worden.
*/
public static void main(String args[])
{
drukAf();
}
/**
* Negatief van 4302
*/
private static void drukAf()
{
int a = 4302;
int uitkomst = ~a + 1;
System.out.println(uitkomst);
}
} |
21728_0 | /**
* deze klasse is een java programma
* @author Marijn Brosens
* @version 1.0
*/
import java.lang.*;
public class EersteProg{
public static void main(String args[])
{
System.out.println("dit is mijn eerste programma" );
}
} | MTA-Digital-Broadcast-2/S-Brosens-Marijn-Luijten-Ruud-Project-MHP | marijn/blz5/EersteProg.java | 81 | /**
* deze klasse is een java programma
* @author Marijn Brosens
* @version 1.0
*/ | block_comment | nl | /**
* deze klasse is<SUF>*/
import java.lang.*;
public class EersteProg{
public static void main(String args[])
{
System.out.println("dit is mijn eerste programma" );
}
} |
22468_2 | import java.lang.*;
/**
* De klasse EersteProg is een Java applicatie
* @author Jolita Grazyte
* @version 1.5
*/
public class Oef6{
/**
* Dit is een main-functie, hier start programma
* @param args Dit is een array van strings waarmee parameters kunnen meegegeven worden vanaf de commandline
*/
public static void main(String args[]){
drukaf();
}
/**
* Bewaar het getal 4302 in een integer. Bereken het negatief van dit getal zonder de min operator te gebruiken.
*/
public static void drukaf(){
int nrArr[] = {12, 34, 56, 78, 123, 234, 99, 88};
int grootsteGetal = nrArr[0];
for(int i = 0; i < nrArr.length; i++){
if (grootsteGetal < nrArr[i])
grootsteGetal = nrArr[i];
}
System.out.println(grootsteGetal);
}
}
| MTA-Digital-Broadcast-2/T-Grazyte-Jolita-Van-Roy-Thomas-1-Project-MHP | Jolita Grazyte - oefeningen java + mhp/blz19/Oef6.java | 286 | /**
* Bewaar het getal 4302 in een integer. Bereken het negatief van dit getal zonder de min operator te gebruiken.
*/ | block_comment | nl | import java.lang.*;
/**
* De klasse EersteProg is een Java applicatie
* @author Jolita Grazyte
* @version 1.5
*/
public class Oef6{
/**
* Dit is een main-functie, hier start programma
* @param args Dit is een array van strings waarmee parameters kunnen meegegeven worden vanaf de commandline
*/
public static void main(String args[]){
drukaf();
}
/**
* Bewaar het getal<SUF>*/
public static void drukaf(){
int nrArr[] = {12, 34, 56, 78, 123, 234, 99, 88};
int grootsteGetal = nrArr[0];
for(int i = 0; i < nrArr.length; i++){
if (grootsteGetal < nrArr[i])
grootsteGetal = nrArr[i];
}
System.out.println(grootsteGetal);
}
}
|
34549_0 | /**
* Deze klassen is een Java programma
* @author Jan Willem Cornelis
* @version 1.0
*/
package Oef8;
import java.lang.*;
public class PartTimeWerknemer extends Werknemer {
public int urenGewerkt;
public PartTimeWerknemer(String voornaam, String achternaam, int wNummer, float salaris, int urenGewerkt){
super(voornaam, achternaam, wNummer, salaris);
this.urenGewerkt = urenGewerkt;
}
public float getWeekLoon(){
return this.salaris + this.urenGewerkt;
}
@Override
public void salarisVerhogen(int percentage){
if(percentage > 5){
percentage = 5;
}
float verhogingsfactor = (float) percentage/100;
salaris += salaris * verhogingsfactor;
}
}
| MTA-Digital-Broadcast-2/U-Cornelis-Jan-van-Ruiten-Oscar-Alexander-Project-MHP | Jan Cornelis/blz31/Oef8/PartTimeWerknemer.java | 255 | /**
* Deze klassen is een Java programma
* @author Jan Willem Cornelis
* @version 1.0
*/ | block_comment | nl | /**
* Deze klassen is<SUF>*/
package Oef8;
import java.lang.*;
public class PartTimeWerknemer extends Werknemer {
public int urenGewerkt;
public PartTimeWerknemer(String voornaam, String achternaam, int wNummer, float salaris, int urenGewerkt){
super(voornaam, achternaam, wNummer, salaris);
this.urenGewerkt = urenGewerkt;
}
public float getWeekLoon(){
return this.salaris + this.urenGewerkt;
}
@Override
public void salarisVerhogen(int percentage){
if(percentage > 5){
percentage = 5;
}
float verhogingsfactor = (float) percentage/100;
salaris += salaris * verhogingsfactor;
}
}
|
146043_0 | public class Main {
public static void main(String args[])
{
Werknemer dieter = new Werknemer("Dieter", "Clauwaert", 1, 1000);
Werknemer jasper = new Werknemer("Jasper", "Cludts", 2, 2000);
Werknemer mats = new Werknemer("Mats", "Kennes", 3, 3000);
Werknemer jonah = new Werknemer("Jonah", "Boons", 4, 4000);
PartTimeWerknemer alex = new PartTimeWerknemer("Alex", "Spildooren", 5, 5000, 5);
PartTimeWerknemer alexis = new PartTimeWerknemer("Alexis", "Guiette", 6, 6000, 6);
/*
dieter.salarisVerhogen(10);
jasper.salarisVerhogen(10);
mats.salarisVerhogen(10);
jonah.salarisVerhogen(10);
System.out.println(dieter.voornaam + " verdient " + dieter.getsalaris());
System.out.println(jasper.voornaam + " verdient " + jasper.getsalaris());
System.out.println(mats.voornaam + " verdient " + mats.getsalaris());
System.out.println(jonah.voornaam + " verdient " + jonah.getsalaris());
alex.salarisVerhogen(4);
alexis.salarisVerhogen(4);
System.out.println(alex.voornaam + " verdient " + alex.getsalaris() + " en werkt " + alex.urenGewerkt + " uur ");
System.out.println(alexis.voornaam + " verdient " + alexis.getsalaris() + " en werkt " + alexis.urenGewerkt + " uur ");
*/
System.out.println(alex.voornaam + " betaalt " + alex.getRSZ() + " % RSZ ");
System.out.println(dieter.voornaam + " betaalt " + dieter.getRSZ() + " % RSZ ");
}
} | MTA-Digital-Broadcast-2/V-Clauwaert-Dieter-Boons-Jonah-Project-MHP | Dieter Clauwaert/Oefeningen Java/Labojava/blz31/Oef6/Main.java | 590 | /*
dieter.salarisVerhogen(10);
jasper.salarisVerhogen(10);
mats.salarisVerhogen(10);
jonah.salarisVerhogen(10);
System.out.println(dieter.voornaam + " verdient " + dieter.getsalaris());
System.out.println(jasper.voornaam + " verdient " + jasper.getsalaris());
System.out.println(mats.voornaam + " verdient " + mats.getsalaris());
System.out.println(jonah.voornaam + " verdient " + jonah.getsalaris());
alex.salarisVerhogen(4);
alexis.salarisVerhogen(4);
System.out.println(alex.voornaam + " verdient " + alex.getsalaris() + " en werkt " + alex.urenGewerkt + " uur ");
System.out.println(alexis.voornaam + " verdient " + alexis.getsalaris() + " en werkt " + alexis.urenGewerkt + " uur ");
*/ | block_comment | nl | public class Main {
public static void main(String args[])
{
Werknemer dieter = new Werknemer("Dieter", "Clauwaert", 1, 1000);
Werknemer jasper = new Werknemer("Jasper", "Cludts", 2, 2000);
Werknemer mats = new Werknemer("Mats", "Kennes", 3, 3000);
Werknemer jonah = new Werknemer("Jonah", "Boons", 4, 4000);
PartTimeWerknemer alex = new PartTimeWerknemer("Alex", "Spildooren", 5, 5000, 5);
PartTimeWerknemer alexis = new PartTimeWerknemer("Alexis", "Guiette", 6, 6000, 6);
/*
dieter.salarisVerhogen(10);
<SUF>*/
System.out.println(alex.voornaam + " betaalt " + alex.getRSZ() + " % RSZ ");
System.out.println(dieter.voornaam + " betaalt " + dieter.getRSZ() + " % RSZ ");
}
} |
153837_6 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package botsingen;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
public class Animatiepaneel extends JPanel {
private ArrayList<SimCirkel> lijst;
private javax.swing.Timer timer;
private int aantalPersonen = 50;
private int aantalBesmet = 0;
private int aantalImmuun =0;
private int tijdPaniek = 0;
private int tijdPaniek80 = 0;
public Animatiepaneel() {
double t;
int r;
int x, y, dx, dy;
setSize( 1180, 980 );
timer = new javax.swing.Timer( 10, new TimerHandler() );
lijst = new ArrayList<SimCirkel>();
for (int i=0; i<aantalPersonen; i++){
t=Math.random();
t*=1180;
x = (int)t;
t=Math.random();
t*=980;
y = (int)t;
t = Math.random();
t*=8;
r=(int)t;
switch(r){
case 0:
{
dx=0; dy=1; break;
}
case 1:
{
dx=1; dy=1; break;
}
case 2:
{
dx=1; dy=0; break;
}
case 3:
{
dx=1; dy=-1; break;
}
case 4:
{
dx=0; dy=-1; break;
}
case 5:
{
dx=-1; dy=-1; break;
}
case 6:
{
dx=-1; dy=0; break;
}
case 7:
{
dx=-1; dy=1; break;
}
default:
{
dx=0; dy=0;
System.out.println("geen geldig resultaat");
}
}
//dx = (int)t-1;
//t = Math.random();
//t*=3;
//dy = (int)t-1;
lijst.add(new SimCirkel(x,y,dx,dy,getBounds()));
//System.out.println(dx);
//System.out.println(dy);
}
lijst.add( new SimCirkel( 200, 120, 1, 1, getBounds(), true ));
timer.start();
}
public void paintComponent( Graphics g ) {
super.paintComponent( g );
setBackground( Color.WHITE );
for( SimCirkel p : lijst ) {
p.teken( g );
}
}
private void verplaatsAlles() {
for( SimCirkel p : lijst ) {
p.verplaats();
}
}
public int aantalBesmet(){
int n = 0;
for (SimCirkel p: lijst){
if (p.getBesmet()){
n+=1;
}
}
return n;
}
public int aantalImmuun(){
int n=0;
for (SimCirkel p: lijst){
if (p.getImmuun()){
n=n+1;
}
}
return n;
}
public int aantalResterend(){
int n = 0;
for (SimCirkel p: lijst){
if (!p.getImmuun()){
n+=1;
}
}
return n;
}
private void controleerBotsingen() {
int pos = 0;
for( SimCirkel p : lijst ) {
pos++;
java.util.List<SimCirkel> sublijst =
lijst.subList( pos, lijst.size() );
for( SimCirkel q : sublijst ) {
if( p.botstMet( q ) ) {
Point pRichting = p.getRichting();
p.setRichting( q.getRichting() );
q.setRichting( pRichting );
if (p.getBesmet()){//als p besmet is
if (!q.getBesmet()&&!q.getImmuun()){ //en q is niet besmet, en niet immuun
q.setBesmet(true); //dan wordt q besmet door p
break;//
}
}
if (q.getBesmet()){//als q besmet is
if (!p.getBesmet()&&!p.getImmuun()){//en p is niet besmet, en niet immuun
p.setBesmet(true);//dan wordt p besmet door q
}
}
}
}
}
}
class TimerHandler implements ActionListener{
public void actionPerformed( ActionEvent e ) {
int d = (int)(aantalPersonen*0.8);
int f = (int)(aantalPersonen*0.1);
if (aantalBesmet()!=0){
verplaatsAlles();
controleerBotsingen();
if (aantalBesmet()>f){
if (aantalImmuun()>d){
tijdPaniek80+=1;
}
else {
tijdPaniek+=1;
}
}
repaint();
}
else
{
System.out.println(aantalResterend());
System.out.println(tijdPaniek);
System.out.println(tijdPaniek80);
System.exit(0);
}
}
}
}
| MV57/Besmetting | src/botsingen/Animatiepaneel.java | 1,665 | //dan wordt q besmet door p | line_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package botsingen;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
public class Animatiepaneel extends JPanel {
private ArrayList<SimCirkel> lijst;
private javax.swing.Timer timer;
private int aantalPersonen = 50;
private int aantalBesmet = 0;
private int aantalImmuun =0;
private int tijdPaniek = 0;
private int tijdPaniek80 = 0;
public Animatiepaneel() {
double t;
int r;
int x, y, dx, dy;
setSize( 1180, 980 );
timer = new javax.swing.Timer( 10, new TimerHandler() );
lijst = new ArrayList<SimCirkel>();
for (int i=0; i<aantalPersonen; i++){
t=Math.random();
t*=1180;
x = (int)t;
t=Math.random();
t*=980;
y = (int)t;
t = Math.random();
t*=8;
r=(int)t;
switch(r){
case 0:
{
dx=0; dy=1; break;
}
case 1:
{
dx=1; dy=1; break;
}
case 2:
{
dx=1; dy=0; break;
}
case 3:
{
dx=1; dy=-1; break;
}
case 4:
{
dx=0; dy=-1; break;
}
case 5:
{
dx=-1; dy=-1; break;
}
case 6:
{
dx=-1; dy=0; break;
}
case 7:
{
dx=-1; dy=1; break;
}
default:
{
dx=0; dy=0;
System.out.println("geen geldig resultaat");
}
}
//dx = (int)t-1;
//t = Math.random();
//t*=3;
//dy = (int)t-1;
lijst.add(new SimCirkel(x,y,dx,dy,getBounds()));
//System.out.println(dx);
//System.out.println(dy);
}
lijst.add( new SimCirkel( 200, 120, 1, 1, getBounds(), true ));
timer.start();
}
public void paintComponent( Graphics g ) {
super.paintComponent( g );
setBackground( Color.WHITE );
for( SimCirkel p : lijst ) {
p.teken( g );
}
}
private void verplaatsAlles() {
for( SimCirkel p : lijst ) {
p.verplaats();
}
}
public int aantalBesmet(){
int n = 0;
for (SimCirkel p: lijst){
if (p.getBesmet()){
n+=1;
}
}
return n;
}
public int aantalImmuun(){
int n=0;
for (SimCirkel p: lijst){
if (p.getImmuun()){
n=n+1;
}
}
return n;
}
public int aantalResterend(){
int n = 0;
for (SimCirkel p: lijst){
if (!p.getImmuun()){
n+=1;
}
}
return n;
}
private void controleerBotsingen() {
int pos = 0;
for( SimCirkel p : lijst ) {
pos++;
java.util.List<SimCirkel> sublijst =
lijst.subList( pos, lijst.size() );
for( SimCirkel q : sublijst ) {
if( p.botstMet( q ) ) {
Point pRichting = p.getRichting();
p.setRichting( q.getRichting() );
q.setRichting( pRichting );
if (p.getBesmet()){//als p besmet is
if (!q.getBesmet()&&!q.getImmuun()){ //en q is niet besmet, en niet immuun
q.setBesmet(true); //dan wordt<SUF>
break;//
}
}
if (q.getBesmet()){//als q besmet is
if (!p.getBesmet()&&!p.getImmuun()){//en p is niet besmet, en niet immuun
p.setBesmet(true);//dan wordt p besmet door q
}
}
}
}
}
}
class TimerHandler implements ActionListener{
public void actionPerformed( ActionEvent e ) {
int d = (int)(aantalPersonen*0.8);
int f = (int)(aantalPersonen*0.1);
if (aantalBesmet()!=0){
verplaatsAlles();
controleerBotsingen();
if (aantalBesmet()>f){
if (aantalImmuun()>d){
tijdPaniek80+=1;
}
else {
tijdPaniek+=1;
}
}
repaint();
}
else
{
System.out.println(aantalResterend());
System.out.println(tijdPaniek);
System.out.println(tijdPaniek80);
System.exit(0);
}
}
}
}
|
143228_31 | /*
* 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.coyote;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.WriteListener;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.buf.B2CConverter;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.buf.MessageBytes;
import org.apache.tomcat.util.http.MimeHeaders;
import org.apache.tomcat.util.http.parser.MediaType;
import org.apache.tomcat.util.res.StringManager;
/**
* Response object.
*
* @author James Duncan Davidson [[email protected]]
* @author Jason Hunter [[email protected]]
* @author James Todd [[email protected]]
* @author Harish Prabandham
* @author Hans Bergsten [[email protected]]
* @author Remy Maucherat
*/
public final class Response {
private static final StringManager sm = StringManager.getManager(Response.class);
private static final Log log = LogFactory.getLog(Response.class);
// ----------------------------------------------------- Class Variables
/**
* Default locale as mandated by the spec.
*/
private static final Locale DEFAULT_LOCALE = Locale.getDefault();
// ----------------------------------------------------- Instance Variables
/**
* Status code.
*/
int status = 200;
/**
* Status message.
*/
String message = null;
/**
* Response headers.
*/
final MimeHeaders headers = new MimeHeaders();
/**
* Associated output buffer.
*/
OutputBuffer outputBuffer;
/**
* Notes.
*/
final Object notes[] = new Object[Constants.MAX_NOTES];
/**
* Committed flag.
*/
volatile boolean committed = false;
/**
* Action hook.
*/
volatile ActionHook hook;
/**
* HTTP specific fields.
*/
String contentType = null;
String contentLanguage = null;
Charset charset = null;
// Retain the original name used to set the charset so exactly that name is
// used in the ContentType header. Some (arguably non-specification
// compliant) user agents are very particular
String characterEncoding = null;
long contentLength = -1;
private Locale locale = DEFAULT_LOCALE;
// General informations
private long contentWritten = 0;
private long commitTime = -1;
/**
* Holds request error exception.
*/
Exception errorException = null;
/**
* With the introduction of async processing and the possibility of
* non-container threads calling sendError() tracking the current error
* state and ensuring that the correct error page is called becomes more
* complicated. This state attribute helps by tracking the current error
* state and informing callers that attempt to change state if the change
* was successful or if another thread got there first.
*
* <pre>
* The state machine is very simple:
*
* 0 - NONE
* 1 - NOT_REPORTED
* 2 - REPORTED
*
*
* -->---->-- >NONE
* | | |
* | | | setError()
* ^ ^ |
* | | \|/
* | |-<-NOT_REPORTED
* | |
* ^ | report()
* | |
* | \|/
* |----<----REPORTED
* </pre>
*/
private final AtomicInteger errorState = new AtomicInteger(0);
Request req;
// ------------------------------------------------------------- Properties
public Request getRequest() {
return req;
}
public void setRequest(Request req) {
this.req = req;
}
public void setOutputBuffer(OutputBuffer outputBuffer) {
this.outputBuffer = outputBuffer;
}
public MimeHeaders getMimeHeaders() {
return headers;
}
protected void setHook(ActionHook hook) {
this.hook = hook;
}
// -------------------- Per-Response "notes" --------------------
public final void setNote(int pos, Object value) {
notes[pos] = value;
}
public final Object getNote(int pos) {
return notes[pos];
}
// -------------------- Actions --------------------
public void action(ActionCode actionCode, Object param) {
if (hook != null) {
if (param == null) {
hook.action(actionCode, this);
} else {
hook.action(actionCode, param);
}
}
}
// -------------------- State --------------------
public int getStatus() {
return status;
}
/**
* Set the response status.
*
* @param status The status value to set
*/
public void setStatus(int status) {
this.status = status;
}
/**
* Get the status message.
*
* @return The message associated with the current status
*/
public String getMessage() {
return message;
}
/**
* Set the status message.
*
* @param message The status message to set
*/
public void setMessage(String message) {
this.message = message;
}
public boolean isCommitted() {
return committed;
}
public void setCommitted(boolean v) {
if (v && !this.committed) {
this.commitTime = System.currentTimeMillis();
}
this.committed = v;
}
/**
* Return the time the response was committed (based on System.currentTimeMillis).
*
* @return the time the response was committed
*/
public long getCommitTime() {
return commitTime;
}
// -----------------Error State --------------------
/**
* Set the error Exception that occurred during request processing.
*
* @param ex The exception that occurred
*/
public void setErrorException(Exception ex) {
errorException = ex;
}
/**
* Get the Exception that occurred during request processing.
*
* @return The exception that occurred
*/
public Exception getErrorException() {
return errorException;
}
public boolean isExceptionPresent() {
return (errorException != null);
}
/**
* Set the error flag.
*
* @return <code>false</code> if the error flag was already set
*/
public boolean setError() {
return errorState.compareAndSet(0, 1);
}
/**
* Error flag accessor.
*
* @return <code>true</code> if the response has encountered an error
*/
public boolean isError() {
return errorState.get() > 0;
}
public boolean isErrorReportRequired() {
return errorState.get() == 1;
}
public boolean setErrorReported() {
return errorState.compareAndSet(1, 2);
}
// -------------------- Methods --------------------
public void reset() throws IllegalStateException {
if (committed) {
throw new IllegalStateException();
}
recycle();
}
// -------------------- Headers --------------------
/**
* Does the response contain the given header.
* <br>
* Warning: This method always returns <code>false</code> for Content-Type
* and Content-Length.
*
* @param name The name of the header of interest
* @return {@code true} if the response contains the header.
*/
public boolean containsHeader(String name) {
return headers.getHeader(name) != null;
}
public void setHeader(String name, String value) {
char cc = name.charAt(0);
if (cc == 'C' || cc == 'c') {
if (checkSpecialHeader(name, value))
return;
}
headers.setValue(name).setString(value);
}
public void addHeader(String name, String value) {
addHeader(name, value, null);
}
public void addHeader(String name, String value, Charset charset) {
char cc = name.charAt(0);
if (cc == 'C' || cc == 'c') {
if (checkSpecialHeader(name, value))
return;
}
MessageBytes mb = headers.addValue(name);
if (charset != null) {
mb.setCharset(charset);
}
mb.setString(value);
}
/**
* Set internal fields for special header names.
* Called from set/addHeader.
* Return true if the header is special, no need to set the header.
*/
private boolean checkSpecialHeader(String name, String value) {
// XXX Eliminate redundant fields !!!
// ( both header and in special fields )
if (name.equalsIgnoreCase("Content-Type")) {
setContentType(value);
return true;
}
if (name.equalsIgnoreCase("Content-Length")) {
try {
long cL = Long.parseLong(value);
setContentLength(cL);
return true;
} catch (NumberFormatException ex) {
// Do nothing - the spec doesn't have any "throws"
// and the user might know what he's doing
return false;
}
}
return false;
}
/**
* Signal that we're done with the headers, and body will follow.
* Any implementation needs to notify ContextManager, to allow
* interceptors to fix headers.
*/
public void sendHeaders() {
action(ActionCode.COMMIT, this);
setCommitted(true);
}
// -------------------- I18N --------------------
public Locale getLocale() {
return locale;
}
/**
* Called explicitly by user to set the Content-Language and the default
* encoding.
*
* @param locale The locale to use for this response
*/
public void setLocale(Locale locale) {
if (locale == null) {
return; // throw an exception?
}
// Save the locale for use by getLocale()
this.locale = locale;
// Set the contentLanguage for header output
contentLanguage = locale.toLanguageTag();
}
/**
* Return the content language.
*
* @return The language code for the language currently associated with this
* response
*/
public String getContentLanguage() {
return contentLanguage;
}
/**
* Overrides the character encoding used in the body of the response. This
* method must be called prior to writing output using getWriter().
*
* @param characterEncoding The name of character encoding.
*/
public void setCharacterEncoding(String characterEncoding) {
if (isCommitted()) {
return;
}
if (characterEncoding == null) {
return;
}
try {
this.charset = B2CConverter.getCharset(characterEncoding);
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException(e);
}
this.characterEncoding = characterEncoding;
}
/**
* @return The name of the current encoding
*/
public String getCharacterEncoding() {
return characterEncoding;
}
public Charset getCharset() {
return charset;
}
/**
* Sets the content type.
* <p>
* This method must preserve any response charset that may already have
* been set via a call to response.setContentType(), response.setLocale(),
* or response.setCharacterEncoding().
*
* @param type the content type
*/
public void setContentType(String type) {
if (type == null) {
this.contentType = null;
return;
}
MediaType m = null;
try {
m = MediaType.parseMediaType(new StringReader(type));
} catch (IOException e) {
// Ignore - null test below handles this
}
if (m == null) {
// Invalid - Assume no charset and just pass through whatever
// the user provided.
this.contentType = type;
return;
}
this.contentType = m.toStringNoCharset();
String charsetValue = m.getCharset();
if (charsetValue != null) {
charsetValue = charsetValue.trim();
if (charsetValue.length() > 0) {
try {
charset = B2CConverter.getCharset(charsetValue);
} catch (UnsupportedEncodingException e) {
log.warn(sm.getString("response.encoding.invalid", charsetValue), e);
}
}
}
}
public void setContentTypeNoCharset(String type) {
this.contentType = type;
}
public String getContentType() {
String ret = contentType;
if (ret != null && charset != null) {
ret = ret + ";charset=" + characterEncoding;
}
return ret;
}
public void setContentLength(long contentLength) {
this.contentLength = contentLength;
}
public int getContentLength() {
long length = getContentLengthLong();
if (length < Integer.MAX_VALUE) {
return (int) length;
}
return -1;
}
public long getContentLengthLong() {
return contentLength;
}
/**
* Write a chunk of bytes.
*
* @param chunk The bytes to write
* @throws IOException If an I/O error occurs during the write
* @deprecated Unused. Will be removed in Tomcat 9. Use
* {@link #doWrite(ByteBuffer)}
*/
@Deprecated
public void doWrite(ByteChunk chunk) throws IOException {
outputBuffer.doWrite(chunk);
contentWritten += chunk.getLength();
}
/**
* Write a chunk of bytes.
*
* @param chunk The ByteBuffer to write
* @throws IOException If an I/O error occurs during the write
*/
public void doWrite(ByteBuffer chunk) throws IOException {
int len = chunk.remaining();
outputBuffer.doWrite(chunk);
contentWritten += len - chunk.remaining();
}
// --------------------
public void recycle() {
contentType = null;
contentLanguage = null;
locale = DEFAULT_LOCALE;
charset = null;
characterEncoding = null;
contentLength = -1;
status = 200;
message = null;
committed = false;
commitTime = -1;
errorException = null;
errorState.set(0);
headers.clear();
// Servlet 3.1 non-blocking write listener
listener = null;
fireListener = false;
registeredForWrite = false;
// update counters
contentWritten = 0;
}
/**
* Bytes written by application - i.e. before compression, chunking, etc.
*
* @return The total number of bytes written to the response by the
* application. This will not be the number of bytes written to the
* network which may be more or less than this value.
*/
public long getContentWritten() {
return contentWritten;
}
/**
* Bytes written to socket - i.e. after compression, chunking, etc.
*
* @param flush Should any remaining bytes be flushed before returning the
* total? If {@code false} bytes remaining in the buffer will
* not be included in the returned value
* @return The total number of bytes written to the socket for this response
*/
public long getBytesWritten(boolean flush) {
if (flush) {
action(ActionCode.CLIENT_FLUSH, this);
}
return outputBuffer.getBytesWritten();
}
/*
* State for non-blocking output is maintained here as it is the one point
* easily reachable from the CoyoteOutputStream and the Processor which both
* need access to state.
*/
volatile WriteListener listener;
private boolean fireListener = false;
private boolean registeredForWrite = false;
private final Object nonBlockingStateLock = new Object();
public WriteListener getWriteListener() {
return listener;
}
public void setWriteListener(WriteListener listener) {
if (listener == null) {
throw new NullPointerException(
sm.getString("response.nullWriteListener"));
}
if (getWriteListener() != null) {
throw new IllegalStateException(
sm.getString("response.writeListenerSet"));
}
// Note: This class is not used for HTTP upgrade so only need to test
// for async
AtomicBoolean result = new AtomicBoolean(false);
action(ActionCode.ASYNC_IS_ASYNC, result);
if (!result.get()) {
throw new IllegalStateException(
sm.getString("response.notAsync"));
}
this.listener = listener;
// The container is responsible for the first call to
// listener.onWritePossible(). If isReady() returns true, the container
// needs to call listener.onWritePossible() from a new thread. If
// isReady() returns false, the socket will be registered for write and
// the container will call listener.onWritePossible() once data can be
// written.
if (isReady()) {
synchronized (nonBlockingStateLock) {
// Ensure we don't get multiple write registrations if
// ServletOutputStream.isReady() returns false during a call to
// onDataAvailable()
registeredForWrite = true;
// Need to set the fireListener flag otherwise when the
// container tries to trigger onWritePossible, nothing will
// happen
fireListener = true;
}
action(ActionCode.DISPATCH_WRITE, null);
if (!ContainerThreadMarker.isContainerThread()) {
// Not on a container thread so need to execute the dispatch
action(ActionCode.DISPATCH_EXECUTE, null);
}
}
}
public boolean isReady() {
if (listener == null) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("response.notNonBlocking"));
}
return false;
}
// Assume write is not possible
boolean ready = false;
synchronized (nonBlockingStateLock) {
if (registeredForWrite) {
fireListener = true;
return false;
}
ready = checkRegisterForWrite();
fireListener = !ready;
}
return ready;
}
public boolean checkRegisterForWrite() {
AtomicBoolean ready = new AtomicBoolean(false);
synchronized (nonBlockingStateLock) {
if (!registeredForWrite) {
action(ActionCode.NB_WRITE_INTEREST, ready);
registeredForWrite = !ready.get();
}
}
return ready.get();
}
public void onWritePossible() throws IOException {
// Any buffered data left over from a previous non-blocking write is
// written in the Processor so if this point is reached the app is able
// to write data.
boolean fire = false;
synchronized (nonBlockingStateLock) {
registeredForWrite = false;
if (fireListener) {
fireListener = false;
fire = true;
}
}
if (fire) {
listener.onWritePossible();
}
}
}
| MaShantao/tomcat_original | apache-tomcat-8.5.61-src/java/org/apache/coyote/Response.java | 5,423 | // -------------------- Headers -------------------- | 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.coyote;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.WriteListener;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.buf.B2CConverter;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.buf.MessageBytes;
import org.apache.tomcat.util.http.MimeHeaders;
import org.apache.tomcat.util.http.parser.MediaType;
import org.apache.tomcat.util.res.StringManager;
/**
* Response object.
*
* @author James Duncan Davidson [[email protected]]
* @author Jason Hunter [[email protected]]
* @author James Todd [[email protected]]
* @author Harish Prabandham
* @author Hans Bergsten [[email protected]]
* @author Remy Maucherat
*/
public final class Response {
private static final StringManager sm = StringManager.getManager(Response.class);
private static final Log log = LogFactory.getLog(Response.class);
// ----------------------------------------------------- Class Variables
/**
* Default locale as mandated by the spec.
*/
private static final Locale DEFAULT_LOCALE = Locale.getDefault();
// ----------------------------------------------------- Instance Variables
/**
* Status code.
*/
int status = 200;
/**
* Status message.
*/
String message = null;
/**
* Response headers.
*/
final MimeHeaders headers = new MimeHeaders();
/**
* Associated output buffer.
*/
OutputBuffer outputBuffer;
/**
* Notes.
*/
final Object notes[] = new Object[Constants.MAX_NOTES];
/**
* Committed flag.
*/
volatile boolean committed = false;
/**
* Action hook.
*/
volatile ActionHook hook;
/**
* HTTP specific fields.
*/
String contentType = null;
String contentLanguage = null;
Charset charset = null;
// Retain the original name used to set the charset so exactly that name is
// used in the ContentType header. Some (arguably non-specification
// compliant) user agents are very particular
String characterEncoding = null;
long contentLength = -1;
private Locale locale = DEFAULT_LOCALE;
// General informations
private long contentWritten = 0;
private long commitTime = -1;
/**
* Holds request error exception.
*/
Exception errorException = null;
/**
* With the introduction of async processing and the possibility of
* non-container threads calling sendError() tracking the current error
* state and ensuring that the correct error page is called becomes more
* complicated. This state attribute helps by tracking the current error
* state and informing callers that attempt to change state if the change
* was successful or if another thread got there first.
*
* <pre>
* The state machine is very simple:
*
* 0 - NONE
* 1 - NOT_REPORTED
* 2 - REPORTED
*
*
* -->---->-- >NONE
* | | |
* | | | setError()
* ^ ^ |
* | | \|/
* | |-<-NOT_REPORTED
* | |
* ^ | report()
* | |
* | \|/
* |----<----REPORTED
* </pre>
*/
private final AtomicInteger errorState = new AtomicInteger(0);
Request req;
// ------------------------------------------------------------- Properties
public Request getRequest() {
return req;
}
public void setRequest(Request req) {
this.req = req;
}
public void setOutputBuffer(OutputBuffer outputBuffer) {
this.outputBuffer = outputBuffer;
}
public MimeHeaders getMimeHeaders() {
return headers;
}
protected void setHook(ActionHook hook) {
this.hook = hook;
}
// -------------------- Per-Response "notes" --------------------
public final void setNote(int pos, Object value) {
notes[pos] = value;
}
public final Object getNote(int pos) {
return notes[pos];
}
// -------------------- Actions --------------------
public void action(ActionCode actionCode, Object param) {
if (hook != null) {
if (param == null) {
hook.action(actionCode, this);
} else {
hook.action(actionCode, param);
}
}
}
// -------------------- State --------------------
public int getStatus() {
return status;
}
/**
* Set the response status.
*
* @param status The status value to set
*/
public void setStatus(int status) {
this.status = status;
}
/**
* Get the status message.
*
* @return The message associated with the current status
*/
public String getMessage() {
return message;
}
/**
* Set the status message.
*
* @param message The status message to set
*/
public void setMessage(String message) {
this.message = message;
}
public boolean isCommitted() {
return committed;
}
public void setCommitted(boolean v) {
if (v && !this.committed) {
this.commitTime = System.currentTimeMillis();
}
this.committed = v;
}
/**
* Return the time the response was committed (based on System.currentTimeMillis).
*
* @return the time the response was committed
*/
public long getCommitTime() {
return commitTime;
}
// -----------------Error State --------------------
/**
* Set the error Exception that occurred during request processing.
*
* @param ex The exception that occurred
*/
public void setErrorException(Exception ex) {
errorException = ex;
}
/**
* Get the Exception that occurred during request processing.
*
* @return The exception that occurred
*/
public Exception getErrorException() {
return errorException;
}
public boolean isExceptionPresent() {
return (errorException != null);
}
/**
* Set the error flag.
*
* @return <code>false</code> if the error flag was already set
*/
public boolean setError() {
return errorState.compareAndSet(0, 1);
}
/**
* Error flag accessor.
*
* @return <code>true</code> if the response has encountered an error
*/
public boolean isError() {
return errorState.get() > 0;
}
public boolean isErrorReportRequired() {
return errorState.get() == 1;
}
public boolean setErrorReported() {
return errorState.compareAndSet(1, 2);
}
// -------------------- Methods --------------------
public void reset() throws IllegalStateException {
if (committed) {
throw new IllegalStateException();
}
recycle();
}
// -------------------- Headers<SUF>
/**
* Does the response contain the given header.
* <br>
* Warning: This method always returns <code>false</code> for Content-Type
* and Content-Length.
*
* @param name The name of the header of interest
* @return {@code true} if the response contains the header.
*/
public boolean containsHeader(String name) {
return headers.getHeader(name) != null;
}
public void setHeader(String name, String value) {
char cc = name.charAt(0);
if (cc == 'C' || cc == 'c') {
if (checkSpecialHeader(name, value))
return;
}
headers.setValue(name).setString(value);
}
public void addHeader(String name, String value) {
addHeader(name, value, null);
}
public void addHeader(String name, String value, Charset charset) {
char cc = name.charAt(0);
if (cc == 'C' || cc == 'c') {
if (checkSpecialHeader(name, value))
return;
}
MessageBytes mb = headers.addValue(name);
if (charset != null) {
mb.setCharset(charset);
}
mb.setString(value);
}
/**
* Set internal fields for special header names.
* Called from set/addHeader.
* Return true if the header is special, no need to set the header.
*/
private boolean checkSpecialHeader(String name, String value) {
// XXX Eliminate redundant fields !!!
// ( both header and in special fields )
if (name.equalsIgnoreCase("Content-Type")) {
setContentType(value);
return true;
}
if (name.equalsIgnoreCase("Content-Length")) {
try {
long cL = Long.parseLong(value);
setContentLength(cL);
return true;
} catch (NumberFormatException ex) {
// Do nothing - the spec doesn't have any "throws"
// and the user might know what he's doing
return false;
}
}
return false;
}
/**
* Signal that we're done with the headers, and body will follow.
* Any implementation needs to notify ContextManager, to allow
* interceptors to fix headers.
*/
public void sendHeaders() {
action(ActionCode.COMMIT, this);
setCommitted(true);
}
// -------------------- I18N --------------------
public Locale getLocale() {
return locale;
}
/**
* Called explicitly by user to set the Content-Language and the default
* encoding.
*
* @param locale The locale to use for this response
*/
public void setLocale(Locale locale) {
if (locale == null) {
return; // throw an exception?
}
// Save the locale for use by getLocale()
this.locale = locale;
// Set the contentLanguage for header output
contentLanguage = locale.toLanguageTag();
}
/**
* Return the content language.
*
* @return The language code for the language currently associated with this
* response
*/
public String getContentLanguage() {
return contentLanguage;
}
/**
* Overrides the character encoding used in the body of the response. This
* method must be called prior to writing output using getWriter().
*
* @param characterEncoding The name of character encoding.
*/
public void setCharacterEncoding(String characterEncoding) {
if (isCommitted()) {
return;
}
if (characterEncoding == null) {
return;
}
try {
this.charset = B2CConverter.getCharset(characterEncoding);
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException(e);
}
this.characterEncoding = characterEncoding;
}
/**
* @return The name of the current encoding
*/
public String getCharacterEncoding() {
return characterEncoding;
}
public Charset getCharset() {
return charset;
}
/**
* Sets the content type.
* <p>
* This method must preserve any response charset that may already have
* been set via a call to response.setContentType(), response.setLocale(),
* or response.setCharacterEncoding().
*
* @param type the content type
*/
public void setContentType(String type) {
if (type == null) {
this.contentType = null;
return;
}
MediaType m = null;
try {
m = MediaType.parseMediaType(new StringReader(type));
} catch (IOException e) {
// Ignore - null test below handles this
}
if (m == null) {
// Invalid - Assume no charset and just pass through whatever
// the user provided.
this.contentType = type;
return;
}
this.contentType = m.toStringNoCharset();
String charsetValue = m.getCharset();
if (charsetValue != null) {
charsetValue = charsetValue.trim();
if (charsetValue.length() > 0) {
try {
charset = B2CConverter.getCharset(charsetValue);
} catch (UnsupportedEncodingException e) {
log.warn(sm.getString("response.encoding.invalid", charsetValue), e);
}
}
}
}
public void setContentTypeNoCharset(String type) {
this.contentType = type;
}
public String getContentType() {
String ret = contentType;
if (ret != null && charset != null) {
ret = ret + ";charset=" + characterEncoding;
}
return ret;
}
public void setContentLength(long contentLength) {
this.contentLength = contentLength;
}
public int getContentLength() {
long length = getContentLengthLong();
if (length < Integer.MAX_VALUE) {
return (int) length;
}
return -1;
}
public long getContentLengthLong() {
return contentLength;
}
/**
* Write a chunk of bytes.
*
* @param chunk The bytes to write
* @throws IOException If an I/O error occurs during the write
* @deprecated Unused. Will be removed in Tomcat 9. Use
* {@link #doWrite(ByteBuffer)}
*/
@Deprecated
public void doWrite(ByteChunk chunk) throws IOException {
outputBuffer.doWrite(chunk);
contentWritten += chunk.getLength();
}
/**
* Write a chunk of bytes.
*
* @param chunk The ByteBuffer to write
* @throws IOException If an I/O error occurs during the write
*/
public void doWrite(ByteBuffer chunk) throws IOException {
int len = chunk.remaining();
outputBuffer.doWrite(chunk);
contentWritten += len - chunk.remaining();
}
// --------------------
public void recycle() {
contentType = null;
contentLanguage = null;
locale = DEFAULT_LOCALE;
charset = null;
characterEncoding = null;
contentLength = -1;
status = 200;
message = null;
committed = false;
commitTime = -1;
errorException = null;
errorState.set(0);
headers.clear();
// Servlet 3.1 non-blocking write listener
listener = null;
fireListener = false;
registeredForWrite = false;
// update counters
contentWritten = 0;
}
/**
* Bytes written by application - i.e. before compression, chunking, etc.
*
* @return The total number of bytes written to the response by the
* application. This will not be the number of bytes written to the
* network which may be more or less than this value.
*/
public long getContentWritten() {
return contentWritten;
}
/**
* Bytes written to socket - i.e. after compression, chunking, etc.
*
* @param flush Should any remaining bytes be flushed before returning the
* total? If {@code false} bytes remaining in the buffer will
* not be included in the returned value
* @return The total number of bytes written to the socket for this response
*/
public long getBytesWritten(boolean flush) {
if (flush) {
action(ActionCode.CLIENT_FLUSH, this);
}
return outputBuffer.getBytesWritten();
}
/*
* State for non-blocking output is maintained here as it is the one point
* easily reachable from the CoyoteOutputStream and the Processor which both
* need access to state.
*/
volatile WriteListener listener;
private boolean fireListener = false;
private boolean registeredForWrite = false;
private final Object nonBlockingStateLock = new Object();
public WriteListener getWriteListener() {
return listener;
}
public void setWriteListener(WriteListener listener) {
if (listener == null) {
throw new NullPointerException(
sm.getString("response.nullWriteListener"));
}
if (getWriteListener() != null) {
throw new IllegalStateException(
sm.getString("response.writeListenerSet"));
}
// Note: This class is not used for HTTP upgrade so only need to test
// for async
AtomicBoolean result = new AtomicBoolean(false);
action(ActionCode.ASYNC_IS_ASYNC, result);
if (!result.get()) {
throw new IllegalStateException(
sm.getString("response.notAsync"));
}
this.listener = listener;
// The container is responsible for the first call to
// listener.onWritePossible(). If isReady() returns true, the container
// needs to call listener.onWritePossible() from a new thread. If
// isReady() returns false, the socket will be registered for write and
// the container will call listener.onWritePossible() once data can be
// written.
if (isReady()) {
synchronized (nonBlockingStateLock) {
// Ensure we don't get multiple write registrations if
// ServletOutputStream.isReady() returns false during a call to
// onDataAvailable()
registeredForWrite = true;
// Need to set the fireListener flag otherwise when the
// container tries to trigger onWritePossible, nothing will
// happen
fireListener = true;
}
action(ActionCode.DISPATCH_WRITE, null);
if (!ContainerThreadMarker.isContainerThread()) {
// Not on a container thread so need to execute the dispatch
action(ActionCode.DISPATCH_EXECUTE, null);
}
}
}
public boolean isReady() {
if (listener == null) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("response.notNonBlocking"));
}
return false;
}
// Assume write is not possible
boolean ready = false;
synchronized (nonBlockingStateLock) {
if (registeredForWrite) {
fireListener = true;
return false;
}
ready = checkRegisterForWrite();
fireListener = !ready;
}
return ready;
}
public boolean checkRegisterForWrite() {
AtomicBoolean ready = new AtomicBoolean(false);
synchronized (nonBlockingStateLock) {
if (!registeredForWrite) {
action(ActionCode.NB_WRITE_INTEREST, ready);
registeredForWrite = !ready.get();
}
}
return ready.get();
}
public void onWritePossible() throws IOException {
// Any buffered data left over from a previous non-blocking write is
// written in the Processor so if this point is reached the app is able
// to write data.
boolean fire = false;
synchronized (nonBlockingStateLock) {
registeredForWrite = false;
if (fireListener) {
fireListener = false;
fire = true;
}
}
if (fire) {
listener.onWritePossible();
}
}
}
|
69555_5 | package be.domino;
import java.util.ArrayList;
import java.util.Optional;
/**
* @author Maarten Gielkens
* Ik heb ongeveer 12 uur gewerkt aan deze taak.
*/
public class Algoritme {
/**
* Methode die de ketting maakt en recursief kan worden opgeroepen.
* @param stenen De ArrayList van de stenen die meegegeven worden door de main
* @param geplaatsteStenen De stenen waarin de ketting wordt gelegd
* @param steenNummer De index die bijhoudt welke steen uit de originele lijst moeten geprobeerd toe te voegen
* @param aantalBacktracks Het aantal stenen die terug verwijderd zijn met backtracken
* @param volledigeBacktracks Het aantal keer dat het algoritme een nieuwe steen vooraan legt
* @return Recursief maakKetting opnieuw oproepen
*/
public Optional<ArrayList<Steen>> maakKetting(ArrayList<Steen> stenen, ArrayList<Steen> geplaatsteStenen, int steenNummer, int aantalBacktracks, int volledigeBacktracks) {
Steen huidigeSteen;
//controle die zorgt dat het algoritme stopt wanneer alle stenen op de eerste plaats hebben gelegen.
if (volledigeBacktracks > stenen.size() + geplaatsteStenen.size()) {
if(controleerSteen(geplaatsteStenen.get(geplaatsteStenen.size() - 1), geplaatsteStenen.get(0))) {
return Optional.of(geplaatsteStenen);
}
else {
return Optional.empty();
}
}
//Controle die zorgt dat het algoritme stopt wanneer alle te plaatsen stenen zijn opgebruikt
if (stenen.size() == 0) {
if(controleerSteen(geplaatsteStenen.get(geplaatsteStenen.size() - 1), geplaatsteStenen.get(0))) {
return Optional.of(geplaatsteStenen);
}
else {
return Optional.empty();
}
}
huidigeSteen = stenen.get(steenNummer);
//Vult de lege lijst met geplaatste stenen aan met het eerste element van de te plaatsen stenen.
if (geplaatsteStenen.isEmpty()) {
stenen.remove(huidigeSteen);
geplaatsteStenen.add(huidigeSteen);
return maakKetting(stenen, geplaatsteStenen, steenNummer, 0, volledigeBacktracks + 1);
}
Steen vorigeSteen = geplaatsteStenen.get(geplaatsteStenen.size()-1);
//Controleert als de volgende steen kan toegevoegd worden en doet dit ook indien mogelijk.
if (controleerSteen(vorigeSteen, huidigeSteen)) {
stenen.remove(steenNummer);
geplaatsteStenen.add(huidigeSteen);
steenNummer = 0;
return maakKetting(stenen, geplaatsteStenen, steenNummer, aantalBacktracks, volledigeBacktracks);
}
//Als er niet meer kan worden bijgeplaatst dan begint het volgende stuk met backtracken
else if (stenen.size() -1 - aantalBacktracks <= steenNummer){
if(controleerSteen(geplaatsteStenen.get(geplaatsteStenen.size() - 1), geplaatsteStenen.get(0))) {
return Optional.of(geplaatsteStenen);
}
controleerSteen(geplaatsteStenen.get(geplaatsteStenen.size() - 1), geplaatsteStenen.get(0));
geplaatsteStenen.remove(vorigeSteen);
stenen.add(vorigeSteen);
aantalBacktracks += 1;
return maakKetting(stenen, geplaatsteStenen, 0, aantalBacktracks, volledigeBacktracks);
}
else{
return maakKetting(stenen, geplaatsteStenen, steenNummer + 1, aantalBacktracks, volledigeBacktracks);
}
}
/**
* Methode die controleert als 2 stenen langs elkaar kunnen liggen, indien een steen geflipt moet worden dan doet deze methode dat ook.
* @param steen1 De eerste steen die gecontroleerd moet worden.
* @param steen2 De tweede steen die gecontroleerd moet worden
* @return Boolean om aan te geven als de stenen achter elkaar gelegd kunnen worden of niet.
*/
public boolean controleerSteen(Steen steen1, Steen steen2) {
if (steen1.getKleur() == steen2.getKleur()) {
return false;
}
if(steen1.getOgen2() != steen2.getOgen1()) {
if(steen1.getOgen2() == steen2.getOgen2()) {
steen2.flip();
return true;
}
else return false;
}
return true;
}
} | MaartenG18/TaakBacktracking | GielkensMaarten/src/main/java/be/domino/Algoritme.java | 1,424 | //Controleert als de volgende steen kan toegevoegd worden en doet dit ook indien mogelijk. | line_comment | nl | package be.domino;
import java.util.ArrayList;
import java.util.Optional;
/**
* @author Maarten Gielkens
* Ik heb ongeveer 12 uur gewerkt aan deze taak.
*/
public class Algoritme {
/**
* Methode die de ketting maakt en recursief kan worden opgeroepen.
* @param stenen De ArrayList van de stenen die meegegeven worden door de main
* @param geplaatsteStenen De stenen waarin de ketting wordt gelegd
* @param steenNummer De index die bijhoudt welke steen uit de originele lijst moeten geprobeerd toe te voegen
* @param aantalBacktracks Het aantal stenen die terug verwijderd zijn met backtracken
* @param volledigeBacktracks Het aantal keer dat het algoritme een nieuwe steen vooraan legt
* @return Recursief maakKetting opnieuw oproepen
*/
public Optional<ArrayList<Steen>> maakKetting(ArrayList<Steen> stenen, ArrayList<Steen> geplaatsteStenen, int steenNummer, int aantalBacktracks, int volledigeBacktracks) {
Steen huidigeSteen;
//controle die zorgt dat het algoritme stopt wanneer alle stenen op de eerste plaats hebben gelegen.
if (volledigeBacktracks > stenen.size() + geplaatsteStenen.size()) {
if(controleerSteen(geplaatsteStenen.get(geplaatsteStenen.size() - 1), geplaatsteStenen.get(0))) {
return Optional.of(geplaatsteStenen);
}
else {
return Optional.empty();
}
}
//Controle die zorgt dat het algoritme stopt wanneer alle te plaatsen stenen zijn opgebruikt
if (stenen.size() == 0) {
if(controleerSteen(geplaatsteStenen.get(geplaatsteStenen.size() - 1), geplaatsteStenen.get(0))) {
return Optional.of(geplaatsteStenen);
}
else {
return Optional.empty();
}
}
huidigeSteen = stenen.get(steenNummer);
//Vult de lege lijst met geplaatste stenen aan met het eerste element van de te plaatsen stenen.
if (geplaatsteStenen.isEmpty()) {
stenen.remove(huidigeSteen);
geplaatsteStenen.add(huidigeSteen);
return maakKetting(stenen, geplaatsteStenen, steenNummer, 0, volledigeBacktracks + 1);
}
Steen vorigeSteen = geplaatsteStenen.get(geplaatsteStenen.size()-1);
//Controleert als<SUF>
if (controleerSteen(vorigeSteen, huidigeSteen)) {
stenen.remove(steenNummer);
geplaatsteStenen.add(huidigeSteen);
steenNummer = 0;
return maakKetting(stenen, geplaatsteStenen, steenNummer, aantalBacktracks, volledigeBacktracks);
}
//Als er niet meer kan worden bijgeplaatst dan begint het volgende stuk met backtracken
else if (stenen.size() -1 - aantalBacktracks <= steenNummer){
if(controleerSteen(geplaatsteStenen.get(geplaatsteStenen.size() - 1), geplaatsteStenen.get(0))) {
return Optional.of(geplaatsteStenen);
}
controleerSteen(geplaatsteStenen.get(geplaatsteStenen.size() - 1), geplaatsteStenen.get(0));
geplaatsteStenen.remove(vorigeSteen);
stenen.add(vorigeSteen);
aantalBacktracks += 1;
return maakKetting(stenen, geplaatsteStenen, 0, aantalBacktracks, volledigeBacktracks);
}
else{
return maakKetting(stenen, geplaatsteStenen, steenNummer + 1, aantalBacktracks, volledigeBacktracks);
}
}
/**
* Methode die controleert als 2 stenen langs elkaar kunnen liggen, indien een steen geflipt moet worden dan doet deze methode dat ook.
* @param steen1 De eerste steen die gecontroleerd moet worden.
* @param steen2 De tweede steen die gecontroleerd moet worden
* @return Boolean om aan te geven als de stenen achter elkaar gelegd kunnen worden of niet.
*/
public boolean controleerSteen(Steen steen1, Steen steen2) {
if (steen1.getKleur() == steen2.getKleur()) {
return false;
}
if(steen1.getOgen2() != steen2.getOgen1()) {
if(steen1.getOgen2() == steen2.getOgen2()) {
steen2.flip();
return true;
}
else return false;
}
return true;
}
} |
73373_0 | package be.kuleuven.vrolijkezweters;
import be.kuleuven.vrolijkezweters.controller.LoginController;
import be.kuleuven.vrolijkezweters.database.*;
import be.kuleuven.vrolijkezweters.model.*;
import be.kuleuven.vrolijkezweters.view.LoginView;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.stage.Stage;
import javax.swing.border.EtchedBorder;
import java.time.LocalDate;
/**
* DB Taak 2022-2023: De Vrolijke Zweters
* Zie https://kuleuven-diepenbeek.github.io/db-course/extra/project/ voor opgave details
*
* Deze code is slechts een quick-start om je op weg te helpen met de integratie van JavaFX tabellen en data!
* Zie README.md voor meer informatie.
*/
public class ProjectMain extends Application {
private static Stage rootStage;
public static Stage getRootStage() {
return rootStage;
}
@Override
public void start(Stage stage) throws Exception {
//maakDummyData();
Login model = new Login();
LoginView view = new LoginView(stage, model);
LoginController controller = new LoginController(model, view);
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getClassLoader().getResource("login.fxml"));
fxmlLoader.setController(controller);
Parent root = fxmlLoader.load();
view.setRoot(root);
view.start();
}
public static void main(String[] args) {
launch();
}
private void maakDummyData() {
PersoonDao persoonDao = new PersoonDao();
LoperDao loperDao = new LoperDao();
VrijwilligerDao vrijwilligerDao = new VrijwilligerDao();
WedstrijdDao wedstrijdDao = new WedstrijdDao();
EtappeDao etappeDao = new EtappeDao();
EtappeResultaatDao etappeResultaatDao = new EtappeResultaatDao();
Persoon admin = new Persoon();
admin.setNaam("Gielkens");
admin.setVoornaam("Maarten");
admin.setGeboorteDatum(LocalDate.of(2020, 1, 8));
admin.setGender("M");
admin.setEmail("[email protected]");
admin.setWachtwoord("Admin");
admin.setAdmin(true);
persoonDao.createPersoon(admin);
Wedstrijd wedstrijd = new Wedstrijd();
wedstrijd.setDatum(LocalDate.of(2022, 2, 20));
wedstrijd.setNaam("Rondje Genk-Hasselt");
wedstrijd.setStartLocatie("Genk");
wedstrijd.setEindLocatie("Hasselt");
wedstrijd.setInschrijvingsgeld(10);
wedstrijdDao.createWedstrijd(wedstrijd);
Loper loper = new Loper();
loper.setGewicht(95);
loper.setFitheid(70);
loper.setPersoon(admin);
loperDao.createLoper(loper);
Loper loper1 = new Loper();
loper1.setGewicht(105);
loper1.setFitheid(50);
loper1.setPersoon(admin);
loperDao.createLoper(loper1);
Persoon persoon1 = new Persoon();
persoon1.setNaam("Groeneveld");
persoon1.setVoornaam("Wouter");
persoon1.setGeboorteDatum(LocalDate.of(2020, 1, 8));
persoon1.setGender("M");
persoon1.setEmail("[email protected]");
persoon1.setWachtwoord("Admin");
persoon1.setAdmin(false);
persoonDao.createPersoon(persoon1);
Loper loper2 = new Loper();
loper2.setGewicht(70);
loper2.setFitheid(85);
loper2.setPersoon(persoon1);
loperDao.createLoper(loper2);
Persoon persoon2 = new Persoon();
persoon2.setNaam("Aerts");
persoon2.setVoornaam("Kris");
persoon2.setGeboorteDatum(LocalDate.of(2020, 1, 8));
persoon2.setGender("M");
persoon2.setEmail("[email protected]");
persoon2.setWachtwoord("Admin");
persoon2.setAdmin(false);
persoonDao.createPersoon(persoon2);
Vrijwilliger vrijwilliger = new Vrijwilliger();
vrijwilliger.setTaak("Startschot geven");
vrijwilliger.setPersoon(persoon2);
vrijwilliger.voegWedstrijdToe(wedstrijd);
wedstrijd.voegVrijwilligerToe(vrijwilliger);
vrijwilligerDao.createVrijwilliger(vrijwilliger);
wedstrijdDao.updateWedstrijd(wedstrijd);
Etappe etappe1 = new Etappe();
etappe1.setLengte(2);
etappe1.setLocatie("Genk");
etappe1.setWedstrijd(wedstrijd);
Etappe etappe2 = new Etappe();
etappe2.setLengte(2);
etappe2.setLocatie("Genk");
etappe2.setWedstrijd(wedstrijd);
Etappe etappe3 = new Etappe();
etappe3.setLengte(2);
etappe3.setLocatie("Hasselt");
etappe3.setWedstrijd(wedstrijd);
Etappe etappe4 = new Etappe();
etappe4.setLengte(2);
etappe4.setLocatie("Hasselt");
etappe4.setWedstrijd(wedstrijd);
etappeDao.createEtappe(etappe1);
etappeDao.createEtappe(etappe2);
etappeDao.createEtappe(etappe3);
etappeDao.createEtappe(etappe4);
wedstrijd.voegEtappeToe(etappe1);
wedstrijd.voegEtappeToe(etappe2);
wedstrijd.voegEtappeToe(etappe3);
wedstrijd.voegEtappeToe(etappe4);
wedstrijdDao.updateWedstrijd(wedstrijd);
EtappeResultaat etappeResultaat1 = new EtappeResultaat();
etappeResultaat1.setTijd(600);
EtappeResultaat etappeResultaat2 = new EtappeResultaat();
etappeResultaat2.setTijd(600);
EtappeResultaat etappeResultaat3 = new EtappeResultaat();
etappeResultaat3.setTijd(600);
etappe1.voegEtappeResultaatToe(etappeResultaat1);
loper.voegEtappeResultaatToe(etappeResultaat1);
etappe2.voegEtappeResultaatToe(etappeResultaat2);
loper.voegEtappeResultaatToe(etappeResultaat2);
etappe3.voegEtappeResultaatToe(etappeResultaat3);
loper.voegEtappeResultaatToe(etappeResultaat3);
etappeResultaatDao.createEtappeResultaat(etappeResultaat1);
etappeResultaatDao.createEtappeResultaat(etappeResultaat2);
etappeResultaatDao.createEtappeResultaat(etappeResultaat3);
}
}
| MaartenG18/TaakDatabases | vrolijke_zweters/src/main/java/be/kuleuven/vrolijkezweters/ProjectMain.java | 2,139 | /**
* DB Taak 2022-2023: De Vrolijke Zweters
* Zie https://kuleuven-diepenbeek.github.io/db-course/extra/project/ voor opgave details
*
* Deze code is slechts een quick-start om je op weg te helpen met de integratie van JavaFX tabellen en data!
* Zie README.md voor meer informatie.
*/ | block_comment | nl | package be.kuleuven.vrolijkezweters;
import be.kuleuven.vrolijkezweters.controller.LoginController;
import be.kuleuven.vrolijkezweters.database.*;
import be.kuleuven.vrolijkezweters.model.*;
import be.kuleuven.vrolijkezweters.view.LoginView;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.stage.Stage;
import javax.swing.border.EtchedBorder;
import java.time.LocalDate;
/**
* DB Taak 2022-2023:<SUF>*/
public class ProjectMain extends Application {
private static Stage rootStage;
public static Stage getRootStage() {
return rootStage;
}
@Override
public void start(Stage stage) throws Exception {
//maakDummyData();
Login model = new Login();
LoginView view = new LoginView(stage, model);
LoginController controller = new LoginController(model, view);
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getClassLoader().getResource("login.fxml"));
fxmlLoader.setController(controller);
Parent root = fxmlLoader.load();
view.setRoot(root);
view.start();
}
public static void main(String[] args) {
launch();
}
private void maakDummyData() {
PersoonDao persoonDao = new PersoonDao();
LoperDao loperDao = new LoperDao();
VrijwilligerDao vrijwilligerDao = new VrijwilligerDao();
WedstrijdDao wedstrijdDao = new WedstrijdDao();
EtappeDao etappeDao = new EtappeDao();
EtappeResultaatDao etappeResultaatDao = new EtappeResultaatDao();
Persoon admin = new Persoon();
admin.setNaam("Gielkens");
admin.setVoornaam("Maarten");
admin.setGeboorteDatum(LocalDate.of(2020, 1, 8));
admin.setGender("M");
admin.setEmail("[email protected]");
admin.setWachtwoord("Admin");
admin.setAdmin(true);
persoonDao.createPersoon(admin);
Wedstrijd wedstrijd = new Wedstrijd();
wedstrijd.setDatum(LocalDate.of(2022, 2, 20));
wedstrijd.setNaam("Rondje Genk-Hasselt");
wedstrijd.setStartLocatie("Genk");
wedstrijd.setEindLocatie("Hasselt");
wedstrijd.setInschrijvingsgeld(10);
wedstrijdDao.createWedstrijd(wedstrijd);
Loper loper = new Loper();
loper.setGewicht(95);
loper.setFitheid(70);
loper.setPersoon(admin);
loperDao.createLoper(loper);
Loper loper1 = new Loper();
loper1.setGewicht(105);
loper1.setFitheid(50);
loper1.setPersoon(admin);
loperDao.createLoper(loper1);
Persoon persoon1 = new Persoon();
persoon1.setNaam("Groeneveld");
persoon1.setVoornaam("Wouter");
persoon1.setGeboorteDatum(LocalDate.of(2020, 1, 8));
persoon1.setGender("M");
persoon1.setEmail("[email protected]");
persoon1.setWachtwoord("Admin");
persoon1.setAdmin(false);
persoonDao.createPersoon(persoon1);
Loper loper2 = new Loper();
loper2.setGewicht(70);
loper2.setFitheid(85);
loper2.setPersoon(persoon1);
loperDao.createLoper(loper2);
Persoon persoon2 = new Persoon();
persoon2.setNaam("Aerts");
persoon2.setVoornaam("Kris");
persoon2.setGeboorteDatum(LocalDate.of(2020, 1, 8));
persoon2.setGender("M");
persoon2.setEmail("[email protected]");
persoon2.setWachtwoord("Admin");
persoon2.setAdmin(false);
persoonDao.createPersoon(persoon2);
Vrijwilliger vrijwilliger = new Vrijwilliger();
vrijwilliger.setTaak("Startschot geven");
vrijwilliger.setPersoon(persoon2);
vrijwilliger.voegWedstrijdToe(wedstrijd);
wedstrijd.voegVrijwilligerToe(vrijwilliger);
vrijwilligerDao.createVrijwilliger(vrijwilliger);
wedstrijdDao.updateWedstrijd(wedstrijd);
Etappe etappe1 = new Etappe();
etappe1.setLengte(2);
etappe1.setLocatie("Genk");
etappe1.setWedstrijd(wedstrijd);
Etappe etappe2 = new Etappe();
etappe2.setLengte(2);
etappe2.setLocatie("Genk");
etappe2.setWedstrijd(wedstrijd);
Etappe etappe3 = new Etappe();
etappe3.setLengte(2);
etappe3.setLocatie("Hasselt");
etappe3.setWedstrijd(wedstrijd);
Etappe etappe4 = new Etappe();
etappe4.setLengte(2);
etappe4.setLocatie("Hasselt");
etappe4.setWedstrijd(wedstrijd);
etappeDao.createEtappe(etappe1);
etappeDao.createEtappe(etappe2);
etappeDao.createEtappe(etappe3);
etappeDao.createEtappe(etappe4);
wedstrijd.voegEtappeToe(etappe1);
wedstrijd.voegEtappeToe(etappe2);
wedstrijd.voegEtappeToe(etappe3);
wedstrijd.voegEtappeToe(etappe4);
wedstrijdDao.updateWedstrijd(wedstrijd);
EtappeResultaat etappeResultaat1 = new EtappeResultaat();
etappeResultaat1.setTijd(600);
EtappeResultaat etappeResultaat2 = new EtappeResultaat();
etappeResultaat2.setTijd(600);
EtappeResultaat etappeResultaat3 = new EtappeResultaat();
etappeResultaat3.setTijd(600);
etappe1.voegEtappeResultaatToe(etappeResultaat1);
loper.voegEtappeResultaatToe(etappeResultaat1);
etappe2.voegEtappeResultaatToe(etappeResultaat2);
loper.voegEtappeResultaatToe(etappeResultaat2);
etappe3.voegEtappeResultaatToe(etappeResultaat3);
loper.voegEtappeResultaatToe(etappeResultaat3);
etappeResultaatDao.createEtappeResultaat(etappeResultaat1);
etappeResultaatDao.createEtappeResultaat(etappeResultaat2);
etappeResultaatDao.createEtappeResultaat(etappeResultaat3);
}
}
|
42928_1 | public class Game {
public void playGame() {
// Beide spelers hebben een stok
Stok deckP1 = new Stok();
Stok deckP2 = new Stok();
// Beide spelers hebben puntentelling
int scoreP1 = 0;
int scoreP2 = 0;
while (deckP1.getLength() != 0) {
// Spelers pakken kaart
Kaart cardP1 = deckP1.drawCard();
Kaart cardP2 = deckP2.drawCard();
if (cardP1.getScore() > cardP2.getScore()) {
scoreP1 += 1;
System.out.println("Player 1 won this round");
System.out.println(String.format("Score player1, player2: %d:%d", scoreP1, scoreP2));
continue;
}
if (cardP1.getScore() < cardP2.getScore()) {
scoreP2 += 1;
System.out.println("Player 2 won this round");
System.out.println(String.format("Score player1, player2: %d:%d", scoreP1, scoreP2));
continue;
}
}
if (scoreP1 == scoreP2) {
System.out.println("The game ended in a draw");
return;
}
if (scoreP1 > scoreP2) {
System.out.println("Winner of the cardgame is PLAYER 1!");
return;
}
System.out.println("Winner of the cardgame is PLAYER 2!");
}
}
| MaartjeGubb/simple-card-game | Game.java | 421 | // Beide spelers hebben puntentelling | line_comment | nl | public class Game {
public void playGame() {
// Beide spelers hebben een stok
Stok deckP1 = new Stok();
Stok deckP2 = new Stok();
// Beide spelers<SUF>
int scoreP1 = 0;
int scoreP2 = 0;
while (deckP1.getLength() != 0) {
// Spelers pakken kaart
Kaart cardP1 = deckP1.drawCard();
Kaart cardP2 = deckP2.drawCard();
if (cardP1.getScore() > cardP2.getScore()) {
scoreP1 += 1;
System.out.println("Player 1 won this round");
System.out.println(String.format("Score player1, player2: %d:%d", scoreP1, scoreP2));
continue;
}
if (cardP1.getScore() < cardP2.getScore()) {
scoreP2 += 1;
System.out.println("Player 2 won this round");
System.out.println(String.format("Score player1, player2: %d:%d", scoreP1, scoreP2));
continue;
}
}
if (scoreP1 == scoreP2) {
System.out.println("The game ended in a draw");
return;
}
if (scoreP1 > scoreP2) {
System.out.println("Winner of the cardgame is PLAYER 1!");
return;
}
System.out.println("Winner of the cardgame is PLAYER 2!");
}
}
|
73712_12 | /**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2010 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package org.appcelerator.titanium.view;
import java.lang.ref.WeakReference;
import java.util.Comparator;
import java.util.TreeSet;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.kroll.common.TiConfig;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.TiDimension;
import org.appcelerator.titanium.proxy.TiViewProxy;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.OnHierarchyChangeListener;
/**
* Base layout class for all Titanium views.
*/
public class TiCompositeLayout extends ViewGroup
implements OnHierarchyChangeListener
{
/**
* Supported layout arrangements
* @module.api
*/
public enum LayoutArrangement {
/**
* The default Titanium layout arrangement.
*/
DEFAULT,
/**
* The layout arrangement for Views and Windows that set layout: "vertical".
*/
VERTICAL,
/**
* The layout arrangement for Views and Windows that set layout: "horizontal".
*/
HORIZONTAL
}
protected static final String TAG = "TiCompositeLayout";
protected static final boolean DBG = TiConfig.LOGD && false;
public static final int NOT_SET = Integer.MIN_VALUE;
private TreeSet<View> viewSorter;
private boolean needsSort;
protected LayoutArrangement arrangement;
// Used by horizonal arrangement calculations
private int horizontalLayoutTopBuffer = 0;
private int horizontalLayoutCurrentLeft = 0;
private int horizontalLayoutLineHeight = 0;
private boolean disableHorizontalWrap = false;
private WeakReference<TiViewProxy> proxy;
// We need these two constructors for backwards compatibility with modules
/**
* Constructs a new TiCompositeLayout object.
* @param context the associated context.
* @module.api
*/
public TiCompositeLayout(Context context)
{
this(context, LayoutArrangement.DEFAULT, null);
}
/**
* Contructs a new TiCompositeLayout object.
* @param context the associated context.
* @param arrangement the associated LayoutArrangement
* @module.api
*/
public TiCompositeLayout(Context context, LayoutArrangement arrangement)
{
this(context, LayoutArrangement.DEFAULT, null);
}
/**
* Constructs a new TiCompositeLayout object.
* @param context the associated context.
* @param proxy the associated proxy.
*/
public TiCompositeLayout(Context context, TiViewProxy proxy)
{
this(context, LayoutArrangement.DEFAULT, proxy);
}
/**
* Contructs a new TiCompositeLayout object.
* @param context the associated context.
* @param arrangement the associated LayoutArrangement
* @param proxy the associated proxy.
*/
public TiCompositeLayout(Context context, LayoutArrangement arrangement, TiViewProxy proxy)
{
super(context);
this.arrangement = arrangement;
this.viewSorter = new TreeSet<View>(new Comparator<View>()
{
public int compare(View o1, View o2)
{
TiCompositeLayout.LayoutParams p1 = (TiCompositeLayout.LayoutParams) o1.getLayoutParams();
TiCompositeLayout.LayoutParams p2 = (TiCompositeLayout.LayoutParams) o2.getLayoutParams();
int result = 0;
if (p1.optionZIndex != NOT_SET && p2.optionZIndex != NOT_SET) {
if (p1.optionZIndex < p2.optionZIndex) {
result = -1;
} else if (p1.optionZIndex > p2.optionZIndex) {
result = 1;
}
} else if (p1.optionZIndex != NOT_SET) {
if (p1.optionZIndex < 0) {
result = -1;
}
if (p1.optionZIndex > 0) {
result = 1;
}
} else if (p2.optionZIndex != NOT_SET) {
if (p2.optionZIndex < 0) {
result = 1;
}
if (p2.optionZIndex > 0) {
result = -1;
}
}
if (result == 0) {
if (p1.index < p2.index) {
result = -1;
} else if (p1.index > p2.index) {
result = 1;
} else {
throw new IllegalStateException("Ambiguous Z-Order");
}
}
return result;
}
});
needsSort = true;
setOnHierarchyChangeListener(this);
this.proxy = new WeakReference<TiViewProxy>(proxy);
}
private String viewToString(View view) {
return view.getClass().getSimpleName() + "@" + Integer.toHexString(view.hashCode());
}
public void resort()
{
needsSort = true;
requestLayout();
invalidate();
}
public void onChildViewAdded(View parent, View child) {
needsSort = true;
if (DBG && parent != null && child != null) {
Log.d(TAG, "Attaching: " + viewToString(child) + " to " + viewToString(parent));
}
}
public void onChildViewRemoved(View parent, View child) {
needsSort = true;
if (DBG) {
Log.d(TAG, "Removing: " + viewToString(child) + " from " + viewToString(parent));
}
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof TiCompositeLayout.LayoutParams;
}
@Override
protected LayoutParams generateDefaultLayoutParams()
{
// Default is fill view
LayoutParams params = new LayoutParams();
params.optionLeft = null;
params.optionRight = null;
params.optionTop = null;
params.optionBottom = null;
params.optionZIndex = NOT_SET;
params.autoHeight = true;
params.autoWidth = true;
return params;
}
protected int getViewWidthPadding(View child, int parentWidth)
{
LayoutParams p = (LayoutParams) child.getLayoutParams();
int padding = 0;
if (p.optionLeft != null) {
if (p.optionLeft.isUnitPercent()) {
padding += (int) ((p.optionLeft.getValue() / 100.0) * parentWidth);
} else {
padding += p.optionLeft.getAsPixels(this);
}
}
if (p.optionRight != null) {
if (p.optionRight.isUnitPercent()) {
padding += (int) ((p.optionRight.getValue() / 100.0) * parentWidth);
} else {
padding += p.optionRight.getAsPixels(this);
}
}
return padding;
}
protected int getViewHeightPadding(View child, int parentHeight)
{
LayoutParams p = (LayoutParams) child.getLayoutParams();
int padding = 0;
if (p.optionTop != null) {
if (p.optionTop.isUnitPercent()) {
padding += (int) ((p.optionTop.getValue() / 100.0) * parentHeight);
} else {
padding += p.optionTop.getAsPixels(this);
}
}
if (p.optionBottom != null) {
if (p.optionBottom.isUnitPercent()) {
padding += (int) ((p.optionBottom.getValue() / 100.0) * parentHeight);
} else {
padding += p.optionBottom.getAsPixels(this);
}
}
return padding;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int childCount = getChildCount();
int wFromSpec = MeasureSpec.getSize(widthMeasureSpec);
int hFromSpec = MeasureSpec.getSize(heightMeasureSpec);
int wSuggested = getSuggestedMinimumWidth();
int hSuggested = getSuggestedMinimumHeight();
int w = Math.max(wFromSpec, wSuggested);
int wMode = MeasureSpec.getMode(widthMeasureSpec);
int h = Math.max(hFromSpec, hSuggested);
int hMode = MeasureSpec.getMode(heightMeasureSpec);
int maxWidth = 0;
int maxHeight = 0;
for(int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if (child.getVisibility() != View.GONE) {
constrainChild(child, w, wMode, h, hMode);
}
int childWidth = child.getMeasuredWidth();
int childHeight = child.getMeasuredHeight();
if (child.getVisibility() != View.GONE) {
childWidth += getViewWidthPadding(child, w);
childHeight += getViewHeightPadding(child, h);
}
if (isHorizontalArrangement()) {
maxWidth += childWidth;
} else {
maxWidth = Math.max(maxWidth, childWidth);
}
if (isVerticalArrangement()) {
maxHeight += childHeight;
} else {
maxHeight = Math.max(maxHeight, childHeight);
}
}
// account for padding
maxWidth += getPaddingLeft() + getPaddingRight();
maxHeight += getPaddingTop() + getPaddingBottom();
// Account for border
//int padding = Math.round(borderHelper.calculatePadding());
//maxWidth += padding;
//maxHeight += padding;
// check minimums
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
int measuredWidth = getMeasuredWidth(maxWidth, widthMeasureSpec);
int measuredHeight = getMeasuredHeight(maxHeight,heightMeasureSpec);
setMeasuredDimension(measuredWidth, measuredHeight);
}
protected void constrainChild(View child, int width, int wMode, int height, int hMode)
{
LayoutParams p = (LayoutParams) child.getLayoutParams();
int childDimension = LayoutParams.WRAP_CONTENT;
if (p.optionWidth != null) {
if (p.optionWidth.isUnitPercent() && width > 0) {
childDimension = (int) ((p.optionWidth.getValue() / 100.0) * width);
} else {
childDimension = p.optionWidth.getAsPixels(this);
}
} else {
if (p.autoFillsWidth && !isHorizontalArrangement()) {
childDimension = LayoutParams.FILL_PARENT;
}
}
int widthPadding = getViewWidthPadding(child, width);
int widthSpec = ViewGroup.getChildMeasureSpec(MeasureSpec.makeMeasureSpec(width, wMode), widthPadding,
childDimension);
childDimension = LayoutParams.WRAP_CONTENT;
if (p.optionHeight != null) {
if (p.optionHeight.isUnitPercent() && height > 0) {
childDimension = (int) ((p.optionHeight.getValue() / 100.0) * height);
} else {
childDimension = p.optionHeight.getAsPixels(this);
}
} else {
if (p.autoFillsHeight && !isVerticalArrangement()) {
childDimension = LayoutParams.FILL_PARENT;
}
}
int heightPadding = getViewHeightPadding(child, height);
int heightSpec = ViewGroup.getChildMeasureSpec(MeasureSpec.makeMeasureSpec(height, hMode), heightPadding,
childDimension);
child.measure(widthSpec, heightSpec);
// Useful for debugging.
// int childWidth = child.getMeasuredWidth();
// int childHeight = child.getMeasuredHeight();
}
private int getUndefinedWidth(LayoutParams params, int parentLeft, int parentRight, int parentWidth)
{
int width = -1;
if (params.optionWidth != null || params.autoWidth) {
return width;
}
TiDimension left = params.optionLeft;
TiDimension centerX = params.optionCenterX;
TiDimension right = params.optionRight;
if (left != null) {
if (centerX != null) {
width = (centerX.getAsPixels(this) - left.getAsPixels(this) - parentLeft) * 2;
} else if (right != null) {
width = parentWidth - right.getAsPixels(this) - left.getAsPixels(this);
}
} else if (centerX != null && right != null) {
width = (parentRight - right.getAsPixels(this) - centerX.getAsPixels(this)) * 2;
}
return width;
}
private int getUndefinedHeight(LayoutParams params, int parentTop, int parentBottom, int parentHeight)
{
int height = -1;
// Return if we don't need undefined behavior
if (params.optionHeight != null || params.autoHeight) {
return height;
}
TiDimension top = params.optionTop;
TiDimension centerY = params.optionCenterY;
TiDimension bottom = params.optionBottom;
if (top != null) {
if (centerY != null) {
height = (centerY.getAsPixels(this) - parentTop - top.getAsPixels(this)) * 2;
} else if (bottom != null) {
height = parentBottom - top.getAsPixels(this) - bottom.getAsPixels(this);
}
} else if (centerY != null && bottom != null) {
height = (parentBottom - bottom.getAsPixels(this) - centerY.getAsPixels(this)) * 2;
}
return height;
}
protected int getMeasuredWidth(int maxWidth, int widthSpec)
{
return resolveSize(maxWidth, widthSpec);
}
protected int getMeasuredHeight(int maxHeight, int heightSpec)
{
return resolveSize(maxHeight, heightSpec);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
int count = getChildCount();
int left = 0;
int top = 0;
int right = r - l;
int bottom = b - t;
if (needsSort) {
viewSorter.clear();
if (count > 1) { // No need to sort one item.
for(int i = 0; i < count; i++) {
View child = getChildAt(i);
TiCompositeLayout.LayoutParams params =
(TiCompositeLayout.LayoutParams) child.getLayoutParams();
params.index = i;
viewSorter.add(child);
}
detachAllViewsFromParent();
int i = 0;
for (View child : viewSorter) {
attachViewToParent(child, i++, child.getLayoutParams());
}
}
needsSort = false;
}
// viewSorter is not needed after this. It's a source of
// memory leaks if it retains the views it's holding.
viewSorter.clear();
int[] horizontal = new int[2];
int[] vertical = new int[2];
int currentHeight = 0; // Used by vertical arrangement calcs
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
TiCompositeLayout.LayoutParams params =
(TiCompositeLayout.LayoutParams) child.getLayoutParams();
if (child.getVisibility() != View.GONE) {
// Dimension is required from Measure. Positioning is determined here.
// Try using undefined behavior first
int childMeasuredHeight = getUndefinedHeight(params, top, bottom, getHeight());
int childMeasuredWidth = getUndefinedWidth(params, left, right, getWidth());
if (childMeasuredWidth == -1) {
childMeasuredWidth = child.getMeasuredWidth();
}
if (childMeasuredHeight == -1) {
childMeasuredHeight = child.getMeasuredHeight();
}
if (isHorizontalArrangement()) {
if (i == 0) {
horizontalLayoutCurrentLeft = left;
horizontalLayoutLineHeight = 0;
horizontalLayoutTopBuffer = 0;
}
computeHorizontalLayoutPosition(params, childMeasuredWidth, childMeasuredHeight, right, top, bottom, horizontal, vertical);
} else {
computePosition(this, params.optionLeft, params.optionCenterX, params.optionRight, childMeasuredWidth, left, right, horizontal);
if (isVerticalArrangement()) {
computeVerticalLayoutPosition(currentHeight, params.optionTop, params.optionBottom, childMeasuredHeight, top, bottom, vertical, b);
} else {
computePosition(this, params.optionTop, params.optionCenterY, params.optionBottom, childMeasuredHeight, top, bottom, vertical);
}
}
if (DBG) {
Log.d(TAG, child.getClass().getName() + " {" + horizontal[0] + "," + vertical[0] + "," + horizontal[1] + "," + vertical[1] + "}");
}
int newWidth = horizontal[1] - horizontal[0];
int newHeight = vertical[1] - vertical[0];
if (newWidth != childMeasuredWidth
|| newHeight != childMeasuredHeight) {
int newWidthSpec = MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY);
int newHeightSpec = MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY);
child.measure(newWidthSpec, newHeightSpec);
}
child.layout(horizontal[0], vertical[0], horizontal[1], vertical[1]);
currentHeight += newHeight;
if (params.optionTop != null) {
currentHeight += params.optionTop.getAsPixels(this);
}
}
}
TiViewProxy viewProxy = proxy.get();
if (viewProxy != null && viewProxy.hasListeners(TiC.EVENT_POST_LAYOUT)) {
viewProxy.fireEvent(TiC.EVENT_POST_LAYOUT, null);
}
}
@Override
protected void onAnimationEnd()
{
super.onAnimationEnd();
invalidate();
}
// option0 is left/top, option1 is right/bottom
public static void computePosition(View parent, TiDimension leftOrTop, TiDimension optionCenter, TiDimension rightOrBottom,
int measuredSize, int layoutPosition0, int layoutPosition1, int[] pos)
{
int dist = layoutPosition1 - layoutPosition0;
if (leftOrTop != null) {
// peg left/top
int leftOrTopPixels = leftOrTop.getAsPixels(parent);
pos[0] = layoutPosition0 + leftOrTopPixels;
pos[1] = layoutPosition0 + leftOrTopPixels + measuredSize;
} else if (optionCenter != null && optionCenter.getValue() != 0.0) {
// Don't calculate position based on center dimension if it's 0.0
int halfSize = measuredSize / 2;
pos[0] = layoutPosition0 + optionCenter.getAsPixels(parent) - halfSize;
pos[1] = pos[0] + measuredSize;
} else if (rightOrBottom != null) {
// peg right/bottom
int rightOrBottomPixels = rightOrBottom.getAsPixels(parent);
pos[0] = dist - rightOrBottomPixels - measuredSize;
pos[1] = dist - rightOrBottomPixels;
} else {
// Center
int offset = (dist - measuredSize) / 2;
pos[0] = layoutPosition0 + offset;
pos[1] = pos[0] + measuredSize;
}
}
private void computeVerticalLayoutPosition(int currentHeight,
TiDimension optionTop, TiDimension optionBottom, int measuredHeight, int layoutTop, int layoutBottom, int[] pos, int maxBottom)
{
int top = layoutTop + currentHeight;
if (optionTop != null) {
top += optionTop.getAsPixels(this);
}
//cap the bottom to make sure views don't go off-screen when user supplies a height value that is >= screen height and this view is
//below another view in vertical layout.
int bottom = Math.min(top + measuredHeight, maxBottom);
pos[0] = top;
pos[1] = bottom;
}
private void computeHorizontalLayoutPosition(TiCompositeLayout.LayoutParams params, int measuredWidth, int measuredHeight, int layoutRight, int layoutTop, int layoutBottom, int[] hpos, int[] vpos)
{
TiDimension optionLeft = params.optionLeft;
int left = horizontalLayoutCurrentLeft;
if (optionLeft != null) {
left += optionLeft.getAsPixels(this);
}
int right = left + measuredWidth;
if (right > layoutRight && !disableHorizontalWrap) {
// Too long for the current "line" that it's on. Need to move it down.
left = 0;
right = measuredWidth;
horizontalLayoutTopBuffer = horizontalLayoutTopBuffer + horizontalLayoutLineHeight;
horizontalLayoutLineHeight = 0;
}
hpos[0] = left;
hpos[1] = right;
horizontalLayoutCurrentLeft = right;
// Get vertical position into vpos
computePosition(this, params.optionTop, params.optionCenterY, params.optionBottom, measuredHeight, layoutTop, layoutBottom, vpos);
horizontalLayoutLineHeight = Math.max(horizontalLayoutLineHeight, vpos[1] - vpos[0]);
// account for moving the item "down" to later line(s) if there has been wrapping.
vpos[0] = vpos[0] + horizontalLayoutTopBuffer;
vpos[1] = vpos[1] + horizontalLayoutTopBuffer;
}
protected int getWidthMeasureSpec(View child) {
return MeasureSpec.EXACTLY;
}
protected int getHeightMeasureSpec(View child) {
return MeasureSpec.EXACTLY;
}
/**
* A TiCompositeLayout specific version of {@link android.view.ViewGroup.LayoutParams}
*/
public static class LayoutParams extends ViewGroup.LayoutParams {
protected int index;
public int optionZIndex = NOT_SET;
public TiDimension optionLeft = null;
public TiDimension optionTop = null;
public TiDimension optionCenterX = null;
public TiDimension optionCenterY = null;
public TiDimension optionRight = null;
public TiDimension optionBottom = null;
public TiDimension optionWidth = null;
public TiDimension optionHeight = null;
public Ti2DMatrix optionTransform = null;
public boolean autoHeight = true;
public boolean autoWidth = true;
/**
* If this is true, and {@link #autoWidth} is true, then the current view will fill available parent width.
* @module.api
*/
public boolean autoFillsWidth = false;
/**
* If this is true, and {@link #autoHeight} is true, then the current view will fill available parent height.
* @module.api
*/
public boolean autoFillsHeight = false;
public LayoutParams() {
super(WRAP_CONTENT, WRAP_CONTENT);
index = Integer.MIN_VALUE;
}
}
protected boolean isVerticalArrangement()
{
return (arrangement == LayoutArrangement.VERTICAL);
}
protected boolean isHorizontalArrangement()
{
return (arrangement == LayoutArrangement.HORIZONTAL);
}
protected boolean isDefaultArrangement()
{
return (arrangement == LayoutArrangement.DEFAULT);
}
public void setLayoutArrangement(String arrangementProperty)
{
if (arrangementProperty != null && arrangementProperty.equals(TiC.LAYOUT_HORIZONTAL)) {
arrangement = LayoutArrangement.HORIZONTAL;
} else if (arrangementProperty != null && arrangementProperty.equals(TiC.LAYOUT_VERTICAL)) {
arrangement = LayoutArrangement.VERTICAL;
} else {
arrangement = LayoutArrangement.DEFAULT;
}
}
public void setDisableHorizontalWrap(boolean disable)
{
disableHorizontalWrap = disable;
}
public void setProxy(TiViewProxy proxy)
{
this.proxy = new WeakReference<TiViewProxy>(proxy);
}
}
| Macadamian/titanium_mobile | android/titanium/src/java/org/appcelerator/titanium/view/TiCompositeLayout.java | 6,666 | // Default is fill view | line_comment | nl | /**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2010 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package org.appcelerator.titanium.view;
import java.lang.ref.WeakReference;
import java.util.Comparator;
import java.util.TreeSet;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.kroll.common.TiConfig;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.TiDimension;
import org.appcelerator.titanium.proxy.TiViewProxy;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.OnHierarchyChangeListener;
/**
* Base layout class for all Titanium views.
*/
public class TiCompositeLayout extends ViewGroup
implements OnHierarchyChangeListener
{
/**
* Supported layout arrangements
* @module.api
*/
public enum LayoutArrangement {
/**
* The default Titanium layout arrangement.
*/
DEFAULT,
/**
* The layout arrangement for Views and Windows that set layout: "vertical".
*/
VERTICAL,
/**
* The layout arrangement for Views and Windows that set layout: "horizontal".
*/
HORIZONTAL
}
protected static final String TAG = "TiCompositeLayout";
protected static final boolean DBG = TiConfig.LOGD && false;
public static final int NOT_SET = Integer.MIN_VALUE;
private TreeSet<View> viewSorter;
private boolean needsSort;
protected LayoutArrangement arrangement;
// Used by horizonal arrangement calculations
private int horizontalLayoutTopBuffer = 0;
private int horizontalLayoutCurrentLeft = 0;
private int horizontalLayoutLineHeight = 0;
private boolean disableHorizontalWrap = false;
private WeakReference<TiViewProxy> proxy;
// We need these two constructors for backwards compatibility with modules
/**
* Constructs a new TiCompositeLayout object.
* @param context the associated context.
* @module.api
*/
public TiCompositeLayout(Context context)
{
this(context, LayoutArrangement.DEFAULT, null);
}
/**
* Contructs a new TiCompositeLayout object.
* @param context the associated context.
* @param arrangement the associated LayoutArrangement
* @module.api
*/
public TiCompositeLayout(Context context, LayoutArrangement arrangement)
{
this(context, LayoutArrangement.DEFAULT, null);
}
/**
* Constructs a new TiCompositeLayout object.
* @param context the associated context.
* @param proxy the associated proxy.
*/
public TiCompositeLayout(Context context, TiViewProxy proxy)
{
this(context, LayoutArrangement.DEFAULT, proxy);
}
/**
* Contructs a new TiCompositeLayout object.
* @param context the associated context.
* @param arrangement the associated LayoutArrangement
* @param proxy the associated proxy.
*/
public TiCompositeLayout(Context context, LayoutArrangement arrangement, TiViewProxy proxy)
{
super(context);
this.arrangement = arrangement;
this.viewSorter = new TreeSet<View>(new Comparator<View>()
{
public int compare(View o1, View o2)
{
TiCompositeLayout.LayoutParams p1 = (TiCompositeLayout.LayoutParams) o1.getLayoutParams();
TiCompositeLayout.LayoutParams p2 = (TiCompositeLayout.LayoutParams) o2.getLayoutParams();
int result = 0;
if (p1.optionZIndex != NOT_SET && p2.optionZIndex != NOT_SET) {
if (p1.optionZIndex < p2.optionZIndex) {
result = -1;
} else if (p1.optionZIndex > p2.optionZIndex) {
result = 1;
}
} else if (p1.optionZIndex != NOT_SET) {
if (p1.optionZIndex < 0) {
result = -1;
}
if (p1.optionZIndex > 0) {
result = 1;
}
} else if (p2.optionZIndex != NOT_SET) {
if (p2.optionZIndex < 0) {
result = 1;
}
if (p2.optionZIndex > 0) {
result = -1;
}
}
if (result == 0) {
if (p1.index < p2.index) {
result = -1;
} else if (p1.index > p2.index) {
result = 1;
} else {
throw new IllegalStateException("Ambiguous Z-Order");
}
}
return result;
}
});
needsSort = true;
setOnHierarchyChangeListener(this);
this.proxy = new WeakReference<TiViewProxy>(proxy);
}
private String viewToString(View view) {
return view.getClass().getSimpleName() + "@" + Integer.toHexString(view.hashCode());
}
public void resort()
{
needsSort = true;
requestLayout();
invalidate();
}
public void onChildViewAdded(View parent, View child) {
needsSort = true;
if (DBG && parent != null && child != null) {
Log.d(TAG, "Attaching: " + viewToString(child) + " to " + viewToString(parent));
}
}
public void onChildViewRemoved(View parent, View child) {
needsSort = true;
if (DBG) {
Log.d(TAG, "Removing: " + viewToString(child) + " from " + viewToString(parent));
}
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof TiCompositeLayout.LayoutParams;
}
@Override
protected LayoutParams generateDefaultLayoutParams()
{
// Default is<SUF>
LayoutParams params = new LayoutParams();
params.optionLeft = null;
params.optionRight = null;
params.optionTop = null;
params.optionBottom = null;
params.optionZIndex = NOT_SET;
params.autoHeight = true;
params.autoWidth = true;
return params;
}
protected int getViewWidthPadding(View child, int parentWidth)
{
LayoutParams p = (LayoutParams) child.getLayoutParams();
int padding = 0;
if (p.optionLeft != null) {
if (p.optionLeft.isUnitPercent()) {
padding += (int) ((p.optionLeft.getValue() / 100.0) * parentWidth);
} else {
padding += p.optionLeft.getAsPixels(this);
}
}
if (p.optionRight != null) {
if (p.optionRight.isUnitPercent()) {
padding += (int) ((p.optionRight.getValue() / 100.0) * parentWidth);
} else {
padding += p.optionRight.getAsPixels(this);
}
}
return padding;
}
protected int getViewHeightPadding(View child, int parentHeight)
{
LayoutParams p = (LayoutParams) child.getLayoutParams();
int padding = 0;
if (p.optionTop != null) {
if (p.optionTop.isUnitPercent()) {
padding += (int) ((p.optionTop.getValue() / 100.0) * parentHeight);
} else {
padding += p.optionTop.getAsPixels(this);
}
}
if (p.optionBottom != null) {
if (p.optionBottom.isUnitPercent()) {
padding += (int) ((p.optionBottom.getValue() / 100.0) * parentHeight);
} else {
padding += p.optionBottom.getAsPixels(this);
}
}
return padding;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int childCount = getChildCount();
int wFromSpec = MeasureSpec.getSize(widthMeasureSpec);
int hFromSpec = MeasureSpec.getSize(heightMeasureSpec);
int wSuggested = getSuggestedMinimumWidth();
int hSuggested = getSuggestedMinimumHeight();
int w = Math.max(wFromSpec, wSuggested);
int wMode = MeasureSpec.getMode(widthMeasureSpec);
int h = Math.max(hFromSpec, hSuggested);
int hMode = MeasureSpec.getMode(heightMeasureSpec);
int maxWidth = 0;
int maxHeight = 0;
for(int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if (child.getVisibility() != View.GONE) {
constrainChild(child, w, wMode, h, hMode);
}
int childWidth = child.getMeasuredWidth();
int childHeight = child.getMeasuredHeight();
if (child.getVisibility() != View.GONE) {
childWidth += getViewWidthPadding(child, w);
childHeight += getViewHeightPadding(child, h);
}
if (isHorizontalArrangement()) {
maxWidth += childWidth;
} else {
maxWidth = Math.max(maxWidth, childWidth);
}
if (isVerticalArrangement()) {
maxHeight += childHeight;
} else {
maxHeight = Math.max(maxHeight, childHeight);
}
}
// account for padding
maxWidth += getPaddingLeft() + getPaddingRight();
maxHeight += getPaddingTop() + getPaddingBottom();
// Account for border
//int padding = Math.round(borderHelper.calculatePadding());
//maxWidth += padding;
//maxHeight += padding;
// check minimums
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
int measuredWidth = getMeasuredWidth(maxWidth, widthMeasureSpec);
int measuredHeight = getMeasuredHeight(maxHeight,heightMeasureSpec);
setMeasuredDimension(measuredWidth, measuredHeight);
}
protected void constrainChild(View child, int width, int wMode, int height, int hMode)
{
LayoutParams p = (LayoutParams) child.getLayoutParams();
int childDimension = LayoutParams.WRAP_CONTENT;
if (p.optionWidth != null) {
if (p.optionWidth.isUnitPercent() && width > 0) {
childDimension = (int) ((p.optionWidth.getValue() / 100.0) * width);
} else {
childDimension = p.optionWidth.getAsPixels(this);
}
} else {
if (p.autoFillsWidth && !isHorizontalArrangement()) {
childDimension = LayoutParams.FILL_PARENT;
}
}
int widthPadding = getViewWidthPadding(child, width);
int widthSpec = ViewGroup.getChildMeasureSpec(MeasureSpec.makeMeasureSpec(width, wMode), widthPadding,
childDimension);
childDimension = LayoutParams.WRAP_CONTENT;
if (p.optionHeight != null) {
if (p.optionHeight.isUnitPercent() && height > 0) {
childDimension = (int) ((p.optionHeight.getValue() / 100.0) * height);
} else {
childDimension = p.optionHeight.getAsPixels(this);
}
} else {
if (p.autoFillsHeight && !isVerticalArrangement()) {
childDimension = LayoutParams.FILL_PARENT;
}
}
int heightPadding = getViewHeightPadding(child, height);
int heightSpec = ViewGroup.getChildMeasureSpec(MeasureSpec.makeMeasureSpec(height, hMode), heightPadding,
childDimension);
child.measure(widthSpec, heightSpec);
// Useful for debugging.
// int childWidth = child.getMeasuredWidth();
// int childHeight = child.getMeasuredHeight();
}
private int getUndefinedWidth(LayoutParams params, int parentLeft, int parentRight, int parentWidth)
{
int width = -1;
if (params.optionWidth != null || params.autoWidth) {
return width;
}
TiDimension left = params.optionLeft;
TiDimension centerX = params.optionCenterX;
TiDimension right = params.optionRight;
if (left != null) {
if (centerX != null) {
width = (centerX.getAsPixels(this) - left.getAsPixels(this) - parentLeft) * 2;
} else if (right != null) {
width = parentWidth - right.getAsPixels(this) - left.getAsPixels(this);
}
} else if (centerX != null && right != null) {
width = (parentRight - right.getAsPixels(this) - centerX.getAsPixels(this)) * 2;
}
return width;
}
private int getUndefinedHeight(LayoutParams params, int parentTop, int parentBottom, int parentHeight)
{
int height = -1;
// Return if we don't need undefined behavior
if (params.optionHeight != null || params.autoHeight) {
return height;
}
TiDimension top = params.optionTop;
TiDimension centerY = params.optionCenterY;
TiDimension bottom = params.optionBottom;
if (top != null) {
if (centerY != null) {
height = (centerY.getAsPixels(this) - parentTop - top.getAsPixels(this)) * 2;
} else if (bottom != null) {
height = parentBottom - top.getAsPixels(this) - bottom.getAsPixels(this);
}
} else if (centerY != null && bottom != null) {
height = (parentBottom - bottom.getAsPixels(this) - centerY.getAsPixels(this)) * 2;
}
return height;
}
protected int getMeasuredWidth(int maxWidth, int widthSpec)
{
return resolveSize(maxWidth, widthSpec);
}
protected int getMeasuredHeight(int maxHeight, int heightSpec)
{
return resolveSize(maxHeight, heightSpec);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
int count = getChildCount();
int left = 0;
int top = 0;
int right = r - l;
int bottom = b - t;
if (needsSort) {
viewSorter.clear();
if (count > 1) { // No need to sort one item.
for(int i = 0; i < count; i++) {
View child = getChildAt(i);
TiCompositeLayout.LayoutParams params =
(TiCompositeLayout.LayoutParams) child.getLayoutParams();
params.index = i;
viewSorter.add(child);
}
detachAllViewsFromParent();
int i = 0;
for (View child : viewSorter) {
attachViewToParent(child, i++, child.getLayoutParams());
}
}
needsSort = false;
}
// viewSorter is not needed after this. It's a source of
// memory leaks if it retains the views it's holding.
viewSorter.clear();
int[] horizontal = new int[2];
int[] vertical = new int[2];
int currentHeight = 0; // Used by vertical arrangement calcs
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
TiCompositeLayout.LayoutParams params =
(TiCompositeLayout.LayoutParams) child.getLayoutParams();
if (child.getVisibility() != View.GONE) {
// Dimension is required from Measure. Positioning is determined here.
// Try using undefined behavior first
int childMeasuredHeight = getUndefinedHeight(params, top, bottom, getHeight());
int childMeasuredWidth = getUndefinedWidth(params, left, right, getWidth());
if (childMeasuredWidth == -1) {
childMeasuredWidth = child.getMeasuredWidth();
}
if (childMeasuredHeight == -1) {
childMeasuredHeight = child.getMeasuredHeight();
}
if (isHorizontalArrangement()) {
if (i == 0) {
horizontalLayoutCurrentLeft = left;
horizontalLayoutLineHeight = 0;
horizontalLayoutTopBuffer = 0;
}
computeHorizontalLayoutPosition(params, childMeasuredWidth, childMeasuredHeight, right, top, bottom, horizontal, vertical);
} else {
computePosition(this, params.optionLeft, params.optionCenterX, params.optionRight, childMeasuredWidth, left, right, horizontal);
if (isVerticalArrangement()) {
computeVerticalLayoutPosition(currentHeight, params.optionTop, params.optionBottom, childMeasuredHeight, top, bottom, vertical, b);
} else {
computePosition(this, params.optionTop, params.optionCenterY, params.optionBottom, childMeasuredHeight, top, bottom, vertical);
}
}
if (DBG) {
Log.d(TAG, child.getClass().getName() + " {" + horizontal[0] + "," + vertical[0] + "," + horizontal[1] + "," + vertical[1] + "}");
}
int newWidth = horizontal[1] - horizontal[0];
int newHeight = vertical[1] - vertical[0];
if (newWidth != childMeasuredWidth
|| newHeight != childMeasuredHeight) {
int newWidthSpec = MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY);
int newHeightSpec = MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY);
child.measure(newWidthSpec, newHeightSpec);
}
child.layout(horizontal[0], vertical[0], horizontal[1], vertical[1]);
currentHeight += newHeight;
if (params.optionTop != null) {
currentHeight += params.optionTop.getAsPixels(this);
}
}
}
TiViewProxy viewProxy = proxy.get();
if (viewProxy != null && viewProxy.hasListeners(TiC.EVENT_POST_LAYOUT)) {
viewProxy.fireEvent(TiC.EVENT_POST_LAYOUT, null);
}
}
@Override
protected void onAnimationEnd()
{
super.onAnimationEnd();
invalidate();
}
// option0 is left/top, option1 is right/bottom
public static void computePosition(View parent, TiDimension leftOrTop, TiDimension optionCenter, TiDimension rightOrBottom,
int measuredSize, int layoutPosition0, int layoutPosition1, int[] pos)
{
int dist = layoutPosition1 - layoutPosition0;
if (leftOrTop != null) {
// peg left/top
int leftOrTopPixels = leftOrTop.getAsPixels(parent);
pos[0] = layoutPosition0 + leftOrTopPixels;
pos[1] = layoutPosition0 + leftOrTopPixels + measuredSize;
} else if (optionCenter != null && optionCenter.getValue() != 0.0) {
// Don't calculate position based on center dimension if it's 0.0
int halfSize = measuredSize / 2;
pos[0] = layoutPosition0 + optionCenter.getAsPixels(parent) - halfSize;
pos[1] = pos[0] + measuredSize;
} else if (rightOrBottom != null) {
// peg right/bottom
int rightOrBottomPixels = rightOrBottom.getAsPixels(parent);
pos[0] = dist - rightOrBottomPixels - measuredSize;
pos[1] = dist - rightOrBottomPixels;
} else {
// Center
int offset = (dist - measuredSize) / 2;
pos[0] = layoutPosition0 + offset;
pos[1] = pos[0] + measuredSize;
}
}
private void computeVerticalLayoutPosition(int currentHeight,
TiDimension optionTop, TiDimension optionBottom, int measuredHeight, int layoutTop, int layoutBottom, int[] pos, int maxBottom)
{
int top = layoutTop + currentHeight;
if (optionTop != null) {
top += optionTop.getAsPixels(this);
}
//cap the bottom to make sure views don't go off-screen when user supplies a height value that is >= screen height and this view is
//below another view in vertical layout.
int bottom = Math.min(top + measuredHeight, maxBottom);
pos[0] = top;
pos[1] = bottom;
}
private void computeHorizontalLayoutPosition(TiCompositeLayout.LayoutParams params, int measuredWidth, int measuredHeight, int layoutRight, int layoutTop, int layoutBottom, int[] hpos, int[] vpos)
{
TiDimension optionLeft = params.optionLeft;
int left = horizontalLayoutCurrentLeft;
if (optionLeft != null) {
left += optionLeft.getAsPixels(this);
}
int right = left + measuredWidth;
if (right > layoutRight && !disableHorizontalWrap) {
// Too long for the current "line" that it's on. Need to move it down.
left = 0;
right = measuredWidth;
horizontalLayoutTopBuffer = horizontalLayoutTopBuffer + horizontalLayoutLineHeight;
horizontalLayoutLineHeight = 0;
}
hpos[0] = left;
hpos[1] = right;
horizontalLayoutCurrentLeft = right;
// Get vertical position into vpos
computePosition(this, params.optionTop, params.optionCenterY, params.optionBottom, measuredHeight, layoutTop, layoutBottom, vpos);
horizontalLayoutLineHeight = Math.max(horizontalLayoutLineHeight, vpos[1] - vpos[0]);
// account for moving the item "down" to later line(s) if there has been wrapping.
vpos[0] = vpos[0] + horizontalLayoutTopBuffer;
vpos[1] = vpos[1] + horizontalLayoutTopBuffer;
}
protected int getWidthMeasureSpec(View child) {
return MeasureSpec.EXACTLY;
}
protected int getHeightMeasureSpec(View child) {
return MeasureSpec.EXACTLY;
}
/**
* A TiCompositeLayout specific version of {@link android.view.ViewGroup.LayoutParams}
*/
public static class LayoutParams extends ViewGroup.LayoutParams {
protected int index;
public int optionZIndex = NOT_SET;
public TiDimension optionLeft = null;
public TiDimension optionTop = null;
public TiDimension optionCenterX = null;
public TiDimension optionCenterY = null;
public TiDimension optionRight = null;
public TiDimension optionBottom = null;
public TiDimension optionWidth = null;
public TiDimension optionHeight = null;
public Ti2DMatrix optionTransform = null;
public boolean autoHeight = true;
public boolean autoWidth = true;
/**
* If this is true, and {@link #autoWidth} is true, then the current view will fill available parent width.
* @module.api
*/
public boolean autoFillsWidth = false;
/**
* If this is true, and {@link #autoHeight} is true, then the current view will fill available parent height.
* @module.api
*/
public boolean autoFillsHeight = false;
public LayoutParams() {
super(WRAP_CONTENT, WRAP_CONTENT);
index = Integer.MIN_VALUE;
}
}
protected boolean isVerticalArrangement()
{
return (arrangement == LayoutArrangement.VERTICAL);
}
protected boolean isHorizontalArrangement()
{
return (arrangement == LayoutArrangement.HORIZONTAL);
}
protected boolean isDefaultArrangement()
{
return (arrangement == LayoutArrangement.DEFAULT);
}
public void setLayoutArrangement(String arrangementProperty)
{
if (arrangementProperty != null && arrangementProperty.equals(TiC.LAYOUT_HORIZONTAL)) {
arrangement = LayoutArrangement.HORIZONTAL;
} else if (arrangementProperty != null && arrangementProperty.equals(TiC.LAYOUT_VERTICAL)) {
arrangement = LayoutArrangement.VERTICAL;
} else {
arrangement = LayoutArrangement.DEFAULT;
}
}
public void setDisableHorizontalWrap(boolean disable)
{
disableHorizontalWrap = disable;
}
public void setProxy(TiViewProxy proxy)
{
this.proxy = new WeakReference<TiViewProxy>(proxy);
}
}
|
60366_16 | ////////////////////////////////////////////////////////////////////////
//
// This file Lamp.java is part of SURFEX.
//
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
//
// SURFEX version 0.90.00
// =================
//
// Saarland University at Saarbruecken, Germany
// Department of Mathematics and Computer Science
//
// SURFEX on the web: www.surfex.AlgebraicSurface.net
//
// Authors: Oliver Labs (2001-2008), Stephan Holzer (2004-2005)
//
// Copyright (C) 2001-2008
//
//
// *NOTICE*
// ========
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation ( version 3 or later of the License ).
//
// See LICENCE.TXT for details.
//
/////////////////////////////////////////////////////////////////////////
import java.awt.BorderLayout;
import java.awt.*;//Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintWriter;
import java.text.NumberFormat;
import javax.swing.*;//JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.util.*;
import jv.vecmath.*;
//////////////////////////////////////////////////////////////
//
// class Lamp
//
//////////////////////////////////////////////////////////////
public class Lamp extends JPanel {
// Anfang Variablen
// JButton deleteLampButton = new JButton("del");
JButton colorButton;
String lastX = "0";
String lastY = "0";
String lastZ = "0";
String lastXj = "0";
String lastYj = "0";
String lastZj = "0";
//Lichtstaerke lichtstaerke;
//////////////////////////////
Project project;
public int lampNo = 0;
public JCheckBox cbox = new JCheckBox("", true);
public int oldFrom = 0;
public int oldTo = 1;
public int newFrom = 0;
public int newTo = 1;
// zum rechnen
// pcalc polyCalc = new pcalc();
public JLabel intenseLabel = new JLabel("50");
public JTextField from = new JTextField("0");
public JTextField to = new JTextField("100");
JLabel toLabel = new JLabel("to:");
JLabel fromLabel = new JLabel("from:");
JSlider intenseSlider = new JSlider(0, 100);//intenseSlider = null;
// GUI
public JLabel nameLabel = null;
public JTextField xPos = new JTextField("0.000");
public JTextField yPos = new JTextField("1.000");
public JTextField zPos = new JTextField("0.000");
//public JLabel parLabel = new JLabel("0.50000");
JLabel xLabel = new JLabel(" x: ");
JLabel zLabel = new JLabel(" z: ");
JLabel yLabel = new JLabel(" y: ");
JLabel PreviewPic;
Lamp previewLamp;
JButton setPos = new JButton("set Pos");;
JButton intensity = new JButton("Intensity");
LampAdmin lampAdmin;
// Ende Variablen
// Konstruktor
Lamp(Project pro, LampAdmin lampAdmin,JPanel[] lampPanel) {
project = pro;
this.lampAdmin = lampAdmin;
nameLabel = new JLabel(" " + lampNo+" ");
lampPanel[0].add(nameLabel);
// polyCalc.doPrint = false;
// lichtstaerke = new Lichtstaerke(" intensity of " + nameLabel.getText()+" ");
//panel.add(KoordsPanel);
//panel.add(flowPanel);
// flowPanel.add(cbox);
PreviewPic = new JLabel();
lampPanel[1].add(setPos);
// lampPanel[2].add(xLabel);
//xPos.setBounds(200, 40, 250, 100);//.setSize(200,50);
lampPanel[2].add(xPos);
// lampPanel[4].add(yLabel);
lampPanel[3].add(yPos);
// lampPanel[6].add(zLabel);
lampPanel[4].add(zPos);
setPos.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
updateLampAdmin();
// PreviewFenser anpassen
//lichtstaerke.setVisible(true);
}
});
// lampPanel[8].add(setPos);
//lampPanel[9].add(deleteLampButton);
// deleteLampButton.setEnabled(false);
//flowPanel.add(new JLabel(" "));
/* intensity.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
lichtstaerke.setVisible(true);
}
});
*/
intenseSlider.setValue(50);
intenseSlider.setMinorTickSpacing(1);
intenseSlider.setMajorTickSpacing(10);
intenseSlider.setPaintTicks(true);
intenseSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent evt) {
updateintenseSliderLabel();
}
});
lampPanel[5].add(intenseSlider);
colorButton = new JButton();
// colorButton.setBorderPainted(true);
// colorButton.setBorder(BorderFactory.createBevelBorder(5,new Color(100,100,100),new Color(200,200,200)));//.createEtchedBorder());
//colorButton.setText("");
colorButton.setBackground(new Color(0, 180, 240));
colorButton.setToolTipText("Select the \"light\" color");
colorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setColor(JColorChooser.showDialog(null,
"Change light color", colorButton.getBackground()));
}
});
// lampPanel[10].add(new JLabel(" color: "));
lampPanel[6].add(colorButton);
// lampPanel[2].add(new JLabel(" shines: "));
lampPanel[7].add(cbox);
}
public synchronized void updateLampAdmin(){
lampAdmin.setSelectedLamp(lampNo-1);
}
// Konstruktor ohne GUI:
Lamp(Project pro, LampAdmin lampAdmin) {
project = pro;
this.lampAdmin = lampAdmin;
// polyCalc.doPrint = false;
intenseSlider.setValue(50);
colorButton = new JButton();
colorButton.setBackground(new Color(0, 180, 240));
}
public Lamp previewLamp(double x, double y, double z){
previewLamp=getNewLamp(x,y,z,colorButton.getBackground(),getVol(),isShining());
return previewLamp;
}
public Lamp getNewLamp(double x, double y, double z,
Color c,
int i,
boolean shines){
Lamp lamp=new Lamp(project,lampAdmin);//(Lamp)lampList.lastElement();
lamp.setKoords(x,y,z);
lamp.setIntensity( i);
lamp.setColor(c);
lamp.setIsShining(shines);
//SwingUtilities.updateComponentTreeUI(lamp);
return lamp;
}
public void setColor(Color c){
colorButton.setBackground(c);
if(previewLamp!=null){
previewLamp.setColor(c);
}
}
public int getIntensity(){
return intenseSlider.getValue();
}
public void setIntensity(int i){
intenseSlider.setValue(i);
updateintenseSliderLabel();
if(previewLamp!=null){
previewLamp.setIntensity(i);
}
}
public synchronized void updateintenseSliderLabel() {
intenseLabel.setText(""+intenseSlider.getValue());
//SwingUtilities.updateComponentTreeUI(this);
}
public void setKoords(double x, double y, double z) {
//grosses Pronlem :: NumberFormat arbeitet buggy.
// d.h. er gibt manchmal nen leeren String zurueck,
// was ihn spaeter z.b. in getXpos() abschiesst
// bloss nicht die previewLamp updaten ;-)
NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
nf.setMaximumFractionDigits(3);//.setsetMinimumIntegerDigits(5); //
// ggf. mit fuehrenden Nullen ausgeben
nf.setMinimumFractionDigits(3);//.setsetMinimumIntegerDigits(5); //
// ggf. mit fuehrenden Nullen ausgeben
String newx = nf.format(x);
int i = 0;
while (newx.compareTo("") != 0 && ++i < 10) {
newx = nf.format(x);
}
xPos.setText(newx);
i = 0;
String newy = nf.format(y);
while (newy.compareTo("") != 0 && ++i < 10) {
newy = nf.format(y);
}
yPos.setText(newy);
i = 0;
String newz = nf.format(z);
while (newz.compareTo("") != 0 && ++i < 10) {
newz = nf.format(z);
}
zPos.setText(newz);
// System.out.println("new coords:"+xPos.getText()+","+yPos.getText()+","+zPos.getText()+".");
}
public void setColor(int r, int g, int b) {
colorButton.setBackground(new Color(r, g, b));
if(previewLamp!=null){
previewLamp.setColor(r,g,b);
}
}
public boolean isSelected() {
return (cbox.isSelected());
}
public void setIsShining(boolean b) {
cbox.setSelected(b);
//if(previewLamp!=nul)
if(previewLamp!=null){
previewLamp.setIsShining(b);
}
}
/* public synchronized void updateKoords_InvokedByUpdateFrameImmediatlyThread_LampAdmin(
jv4surfex jv4sx) {
// bloss nicht die previewLamp updaten ;-)
double[] ang = new double[3];
ang[0] = jv4sx.getCamPos()[0];//-jv4sx.getCamPos()[0];
ang[1] = jv4sx.getCamPos()[1];//.getCameraRotationYXZ()[1];//-jv4sx.getCamPos()[1];
ang[2] = jv4sx.getCamPos()[2];//getCameraRotationYXZ()[2];//)-jv4sx.getCamPos()[2];
// System.out.println("r" + vec2Str(jv4sx.getCamPos()));
if (!((lastX.compareTo(getXpos_str()) == 0)
&& (lastY.compareTo(getYpos_str()) == 0) && (lastZ
.compareTo(getZpos_str()) == 0))) {
// der Benutzer hat die Koordinaten schriftlich geaendert
// -> jv4sx anpassen!!
try{
PdVector v = getPos();
v.multScalar(1.0);
jv4sx.disp.getCamera().setPosition(v);
jv4sx.setParameterWarning(false);
//jv4sx.updateScaleSliderValue();
// System.out.println(10/getVecLength()+" - "+jv4sx.disp.getCamera().getScale());
jv4sx.updateDisp();
}catch(Exception e){
//er hat wahrschinlich nen parameter im Textfeld stehehn und kann deswegen nicht nach double konvertieren
jv4sx.setParameterWarning(true);
}
// geaenderte Daten speichern
// damit man merkt, falls er sie wieder aendert
//lastXj=Double.valueOf(ang[0]).toString();
//lastYj=Double.valueOf(ang[1]).toString();
//lastZj=Double.valueOf(ang[2]).toString();
lastX = getXpos_str();
lastY = getYpos_str();
lastZ = getZpos_str();
}
if (!((lastXj.compareTo(Double.valueOf(ang[0]).toString()) == 0)
&& (lastYj.compareTo(Double.valueOf(ang[1]).toString()) == 0) && (lastZj
.compareTo(Double.valueOf(ang[2]).toString()) == 0))) {
// d.h der Benutzer hat die Koordinaten nicht schriftlich geaendert
// aber moeglicherweise im jv4sx-previefenster:
//
// d.h. Benutzer hat jvview gedreht
setKoords(ang[0], ang[1], ang[2]);
// geaenderte Daten speichern
// dami man merkt, falls er sie wieder aendert
lastXj = Double.valueOf(ang[0]).toString();
lastYj = Double.valueOf(ang[1]).toString();
lastZj = Double.valueOf(ang[2]).toString();
lastX = getXpos_str();
lastY = getYpos_str();
lastZ = getZpos_str();
}
}*/
public String vec2Str(double[] v) {
return ("<" + v[0] + "," + v[1] + "," + v[2] + ">");
}
public PdVector getPos() {
return new PdVector(getXpos(), getYpos(), getZpos());
}
public double getVecLength(){
// System.out.println(Math.sqrt(2));
return Math.sqrt(Math.pow(this.getXpos(),2)+Math.pow(this.getYpos(),2)+Math.pow(this.getZpos(),2));
}
public boolean isShining() {
//System.out.println("sel");
return cbox.isSelected();
}
public void setSelected(boolean b) {
if(previewLamp!=null){
previewLamp.setSelected(b);
}
if (b) {
setPos.setBackground(new Color(0, 255, 0));
} else {
// System.out.println("set false -----------------------------------------");
setPos.setBackground(null);//new Color(100, 100, 100));
}
setPos.repaint();
}
public synchronized String getXpos_str() {
String str = "";
while (str.compareTo("") == 0) {
str = xPos.getText();
// Achtung, liefert manchmal den leeren String statt den richtigen
}
// System.out.println("xPos:"+str+".");
return str;
}
public synchronized String getYpos_str() {
String str = "";
while (str.compareTo("") == 0) {
str = yPos.getText();
// Achtung, liefert manchmal den leeren String statt den richtigen
}
return str;
}
public synchronized String getZpos_str() {
String str = "";
while (str.compareTo("") == 0) {
str = zPos.getText();
// Achtung, liefert manchmal den leeren String statt den richtigen
}
return str;
}
public synchronized double getXpos() {
String str = "";
while (str.compareTo("") == 0) {
str = xPos.getText();
// Achtung, liefert manchmal den leeren String statt den richtigen
}
// System.out.println("xPos:"+str+".");
return Double.valueOf(str).doubleValue();
}
public synchronized double getYpos() {
String str = "";
while (str.compareTo("") == 0) {
str = yPos.getText();
// Achtung, liefert manchmal den leeren String statt den richtigen
}
return Double.valueOf(str).doubleValue();
}
public synchronized double getZpos() {
String str = "";
while (str.compareTo("") == 0) {
str = zPos.getText();
// Achtung, liefert manchmal den leeren String statt den richtigen
}
return Double.valueOf(str).doubleValue();
}
public int getVol() {
return getIntensity();
}
public int getRed() {
return colorButton.getBackground().getRed();
}
public int getGreen() {
return colorButton.getBackground().getGreen();
}
public int getBlue() {
return colorButton.getBackground().getBlue();
}
public void setLampNo(int no) {
if(previewLamp!=null){
previewLamp.setLampNo(no);
}
lampNo = no;
nameLabel.setText(" " + lampNo);
//lichtstaerke.setTitle("l" + lampNo);
//SwingUtilities.updateComponentTreeUI(lichtstaerke);
}
public void updateActionCommands(int internalCunr) {
}
public String getSurfCode(int lampNo, String[] runningParams,
double[] runningParamsValue) {
String str="";
str+="light"+lampNo+"_x ="+evalWithPar(getXpos_str(),runningParams,runningParamsValue)+";\n";
str+="light"+lampNo+"_y ="+evalWithPar(getYpos_str(),runningParams,runningParamsValue)+";\n";
str+="light"+lampNo+"_z ="+evalWithPar(getZpos_str(),runningParams,runningParamsValue)+";\n";
str+="light"+lampNo+"_vol ="+getVol()+";\n";
str+="light"+lampNo+"_red ="+getRed()+";\n";
str+="light"+lampNo+"_green ="+getGreen()+";\n";
str+="light"+lampNo+"_blue ="+getBlue()+";\n";
return str;
}
public double evalWithPar(String s,String[] runningParams,
double[] runningParamsValue){
int i=0;
// System.out.println(s);
if(runningParams!=null){
for(int j=0;j<runningParams.length;j++){
// System.out.println("rv:"+runningParamsValue[j]);
s=s.replaceAll(runningParams[j],(new Double(runningParamsValue[j])).toString());
}
}
s=s.replaceAll(" ","");
s=s.replaceAll("\\*"," ");
/*
System.out.println("s1:"+s);
s= polyCalc.showAsPovrayCode(s);
System.out.println("s2:"+s);
if(s.length()>4){
s=s.substring(4,s.length()-1);
} //Double.valueOf(s).doubleValue()*genauigkeit;
// damit es waehrend der Eingabe keine Probleme gibt:
s=s.replaceAll("\\+","");
if(s.charAt(0)=='-'){
s=s.replaceAll("-","");
s="-"+s;
}else{
s=s.replaceAll("-","");
}
s=s.replaceAll("\\*","");
s=s.replaceAll("/","");
s=s.replaceAll("^","");
System.out.println("s3:"+s);
*/
try{
return Double.valueOf(s).doubleValue();
}catch(Exception e){
// System.out.println("ERROR: erst parameter auswaehlen ("+s+")");
}
return 0.0;
}
public void saveYourself(PrintWriter pw) {
String str = "";
pw.println("////////////////// Parameter: /////////////////////////"
+ "\n");
pw.println("" + lampNo + "\n");
pw.println("" + newFrom + "\n");
pw.println("" + newTo + "\n");
pw.println("" + intenseSlider.getValue() + "\n");
// pw.println(parLabel.getText()+"\n");
// pw.println(cbox.isSelected()+"\n");
//optionButtonPane.saveYourself(pw);
}
public String saveYourself() {
String str = "";
str += "////////////////// Parameter: /////////////////////////\n";
str += ("" + lampNo + "\n");
str += ("" + newFrom + "\n");
str += ("" + newTo + "\n");
str += ("" + intenseSlider.getValue() + "\n");
// str += (parLabel.getText()+"\n");
// str += (cbox.isSelected()+"\n");
return (str);
}
} // end of class OneParameter
| Macaulay2/Singular | Singular/LIB/surfex/Lamp.java | 5,935 | // lichtstaerke = new Lichtstaerke(" intensity of " + nameLabel.getText()+" "); | line_comment | nl | ////////////////////////////////////////////////////////////////////////
//
// This file Lamp.java is part of SURFEX.
//
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
//
// SURFEX version 0.90.00
// =================
//
// Saarland University at Saarbruecken, Germany
// Department of Mathematics and Computer Science
//
// SURFEX on the web: www.surfex.AlgebraicSurface.net
//
// Authors: Oliver Labs (2001-2008), Stephan Holzer (2004-2005)
//
// Copyright (C) 2001-2008
//
//
// *NOTICE*
// ========
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation ( version 3 or later of the License ).
//
// See LICENCE.TXT for details.
//
/////////////////////////////////////////////////////////////////////////
import java.awt.BorderLayout;
import java.awt.*;//Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintWriter;
import java.text.NumberFormat;
import javax.swing.*;//JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.util.*;
import jv.vecmath.*;
//////////////////////////////////////////////////////////////
//
// class Lamp
//
//////////////////////////////////////////////////////////////
public class Lamp extends JPanel {
// Anfang Variablen
// JButton deleteLampButton = new JButton("del");
JButton colorButton;
String lastX = "0";
String lastY = "0";
String lastZ = "0";
String lastXj = "0";
String lastYj = "0";
String lastZj = "0";
//Lichtstaerke lichtstaerke;
//////////////////////////////
Project project;
public int lampNo = 0;
public JCheckBox cbox = new JCheckBox("", true);
public int oldFrom = 0;
public int oldTo = 1;
public int newFrom = 0;
public int newTo = 1;
// zum rechnen
// pcalc polyCalc = new pcalc();
public JLabel intenseLabel = new JLabel("50");
public JTextField from = new JTextField("0");
public JTextField to = new JTextField("100");
JLabel toLabel = new JLabel("to:");
JLabel fromLabel = new JLabel("from:");
JSlider intenseSlider = new JSlider(0, 100);//intenseSlider = null;
// GUI
public JLabel nameLabel = null;
public JTextField xPos = new JTextField("0.000");
public JTextField yPos = new JTextField("1.000");
public JTextField zPos = new JTextField("0.000");
//public JLabel parLabel = new JLabel("0.50000");
JLabel xLabel = new JLabel(" x: ");
JLabel zLabel = new JLabel(" z: ");
JLabel yLabel = new JLabel(" y: ");
JLabel PreviewPic;
Lamp previewLamp;
JButton setPos = new JButton("set Pos");;
JButton intensity = new JButton("Intensity");
LampAdmin lampAdmin;
// Ende Variablen
// Konstruktor
Lamp(Project pro, LampAdmin lampAdmin,JPanel[] lampPanel) {
project = pro;
this.lampAdmin = lampAdmin;
nameLabel = new JLabel(" " + lampNo+" ");
lampPanel[0].add(nameLabel);
// polyCalc.doPrint = false;
// lichtstaerke =<SUF>
//panel.add(KoordsPanel);
//panel.add(flowPanel);
// flowPanel.add(cbox);
PreviewPic = new JLabel();
lampPanel[1].add(setPos);
// lampPanel[2].add(xLabel);
//xPos.setBounds(200, 40, 250, 100);//.setSize(200,50);
lampPanel[2].add(xPos);
// lampPanel[4].add(yLabel);
lampPanel[3].add(yPos);
// lampPanel[6].add(zLabel);
lampPanel[4].add(zPos);
setPos.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
updateLampAdmin();
// PreviewFenser anpassen
//lichtstaerke.setVisible(true);
}
});
// lampPanel[8].add(setPos);
//lampPanel[9].add(deleteLampButton);
// deleteLampButton.setEnabled(false);
//flowPanel.add(new JLabel(" "));
/* intensity.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
lichtstaerke.setVisible(true);
}
});
*/
intenseSlider.setValue(50);
intenseSlider.setMinorTickSpacing(1);
intenseSlider.setMajorTickSpacing(10);
intenseSlider.setPaintTicks(true);
intenseSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent evt) {
updateintenseSliderLabel();
}
});
lampPanel[5].add(intenseSlider);
colorButton = new JButton();
// colorButton.setBorderPainted(true);
// colorButton.setBorder(BorderFactory.createBevelBorder(5,new Color(100,100,100),new Color(200,200,200)));//.createEtchedBorder());
//colorButton.setText("");
colorButton.setBackground(new Color(0, 180, 240));
colorButton.setToolTipText("Select the \"light\" color");
colorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setColor(JColorChooser.showDialog(null,
"Change light color", colorButton.getBackground()));
}
});
// lampPanel[10].add(new JLabel(" color: "));
lampPanel[6].add(colorButton);
// lampPanel[2].add(new JLabel(" shines: "));
lampPanel[7].add(cbox);
}
public synchronized void updateLampAdmin(){
lampAdmin.setSelectedLamp(lampNo-1);
}
// Konstruktor ohne GUI:
Lamp(Project pro, LampAdmin lampAdmin) {
project = pro;
this.lampAdmin = lampAdmin;
// polyCalc.doPrint = false;
intenseSlider.setValue(50);
colorButton = new JButton();
colorButton.setBackground(new Color(0, 180, 240));
}
public Lamp previewLamp(double x, double y, double z){
previewLamp=getNewLamp(x,y,z,colorButton.getBackground(),getVol(),isShining());
return previewLamp;
}
public Lamp getNewLamp(double x, double y, double z,
Color c,
int i,
boolean shines){
Lamp lamp=new Lamp(project,lampAdmin);//(Lamp)lampList.lastElement();
lamp.setKoords(x,y,z);
lamp.setIntensity( i);
lamp.setColor(c);
lamp.setIsShining(shines);
//SwingUtilities.updateComponentTreeUI(lamp);
return lamp;
}
public void setColor(Color c){
colorButton.setBackground(c);
if(previewLamp!=null){
previewLamp.setColor(c);
}
}
public int getIntensity(){
return intenseSlider.getValue();
}
public void setIntensity(int i){
intenseSlider.setValue(i);
updateintenseSliderLabel();
if(previewLamp!=null){
previewLamp.setIntensity(i);
}
}
public synchronized void updateintenseSliderLabel() {
intenseLabel.setText(""+intenseSlider.getValue());
//SwingUtilities.updateComponentTreeUI(this);
}
public void setKoords(double x, double y, double z) {
//grosses Pronlem :: NumberFormat arbeitet buggy.
// d.h. er gibt manchmal nen leeren String zurueck,
// was ihn spaeter z.b. in getXpos() abschiesst
// bloss nicht die previewLamp updaten ;-)
NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
nf.setMaximumFractionDigits(3);//.setsetMinimumIntegerDigits(5); //
// ggf. mit fuehrenden Nullen ausgeben
nf.setMinimumFractionDigits(3);//.setsetMinimumIntegerDigits(5); //
// ggf. mit fuehrenden Nullen ausgeben
String newx = nf.format(x);
int i = 0;
while (newx.compareTo("") != 0 && ++i < 10) {
newx = nf.format(x);
}
xPos.setText(newx);
i = 0;
String newy = nf.format(y);
while (newy.compareTo("") != 0 && ++i < 10) {
newy = nf.format(y);
}
yPos.setText(newy);
i = 0;
String newz = nf.format(z);
while (newz.compareTo("") != 0 && ++i < 10) {
newz = nf.format(z);
}
zPos.setText(newz);
// System.out.println("new coords:"+xPos.getText()+","+yPos.getText()+","+zPos.getText()+".");
}
public void setColor(int r, int g, int b) {
colorButton.setBackground(new Color(r, g, b));
if(previewLamp!=null){
previewLamp.setColor(r,g,b);
}
}
public boolean isSelected() {
return (cbox.isSelected());
}
public void setIsShining(boolean b) {
cbox.setSelected(b);
//if(previewLamp!=nul)
if(previewLamp!=null){
previewLamp.setIsShining(b);
}
}
/* public synchronized void updateKoords_InvokedByUpdateFrameImmediatlyThread_LampAdmin(
jv4surfex jv4sx) {
// bloss nicht die previewLamp updaten ;-)
double[] ang = new double[3];
ang[0] = jv4sx.getCamPos()[0];//-jv4sx.getCamPos()[0];
ang[1] = jv4sx.getCamPos()[1];//.getCameraRotationYXZ()[1];//-jv4sx.getCamPos()[1];
ang[2] = jv4sx.getCamPos()[2];//getCameraRotationYXZ()[2];//)-jv4sx.getCamPos()[2];
// System.out.println("r" + vec2Str(jv4sx.getCamPos()));
if (!((lastX.compareTo(getXpos_str()) == 0)
&& (lastY.compareTo(getYpos_str()) == 0) && (lastZ
.compareTo(getZpos_str()) == 0))) {
// der Benutzer hat die Koordinaten schriftlich geaendert
// -> jv4sx anpassen!!
try{
PdVector v = getPos();
v.multScalar(1.0);
jv4sx.disp.getCamera().setPosition(v);
jv4sx.setParameterWarning(false);
//jv4sx.updateScaleSliderValue();
// System.out.println(10/getVecLength()+" - "+jv4sx.disp.getCamera().getScale());
jv4sx.updateDisp();
}catch(Exception e){
//er hat wahrschinlich nen parameter im Textfeld stehehn und kann deswegen nicht nach double konvertieren
jv4sx.setParameterWarning(true);
}
// geaenderte Daten speichern
// damit man merkt, falls er sie wieder aendert
//lastXj=Double.valueOf(ang[0]).toString();
//lastYj=Double.valueOf(ang[1]).toString();
//lastZj=Double.valueOf(ang[2]).toString();
lastX = getXpos_str();
lastY = getYpos_str();
lastZ = getZpos_str();
}
if (!((lastXj.compareTo(Double.valueOf(ang[0]).toString()) == 0)
&& (lastYj.compareTo(Double.valueOf(ang[1]).toString()) == 0) && (lastZj
.compareTo(Double.valueOf(ang[2]).toString()) == 0))) {
// d.h der Benutzer hat die Koordinaten nicht schriftlich geaendert
// aber moeglicherweise im jv4sx-previefenster:
//
// d.h. Benutzer hat jvview gedreht
setKoords(ang[0], ang[1], ang[2]);
// geaenderte Daten speichern
// dami man merkt, falls er sie wieder aendert
lastXj = Double.valueOf(ang[0]).toString();
lastYj = Double.valueOf(ang[1]).toString();
lastZj = Double.valueOf(ang[2]).toString();
lastX = getXpos_str();
lastY = getYpos_str();
lastZ = getZpos_str();
}
}*/
public String vec2Str(double[] v) {
return ("<" + v[0] + "," + v[1] + "," + v[2] + ">");
}
public PdVector getPos() {
return new PdVector(getXpos(), getYpos(), getZpos());
}
public double getVecLength(){
// System.out.println(Math.sqrt(2));
return Math.sqrt(Math.pow(this.getXpos(),2)+Math.pow(this.getYpos(),2)+Math.pow(this.getZpos(),2));
}
public boolean isShining() {
//System.out.println("sel");
return cbox.isSelected();
}
public void setSelected(boolean b) {
if(previewLamp!=null){
previewLamp.setSelected(b);
}
if (b) {
setPos.setBackground(new Color(0, 255, 0));
} else {
// System.out.println("set false -----------------------------------------");
setPos.setBackground(null);//new Color(100, 100, 100));
}
setPos.repaint();
}
public synchronized String getXpos_str() {
String str = "";
while (str.compareTo("") == 0) {
str = xPos.getText();
// Achtung, liefert manchmal den leeren String statt den richtigen
}
// System.out.println("xPos:"+str+".");
return str;
}
public synchronized String getYpos_str() {
String str = "";
while (str.compareTo("") == 0) {
str = yPos.getText();
// Achtung, liefert manchmal den leeren String statt den richtigen
}
return str;
}
public synchronized String getZpos_str() {
String str = "";
while (str.compareTo("") == 0) {
str = zPos.getText();
// Achtung, liefert manchmal den leeren String statt den richtigen
}
return str;
}
public synchronized double getXpos() {
String str = "";
while (str.compareTo("") == 0) {
str = xPos.getText();
// Achtung, liefert manchmal den leeren String statt den richtigen
}
// System.out.println("xPos:"+str+".");
return Double.valueOf(str).doubleValue();
}
public synchronized double getYpos() {
String str = "";
while (str.compareTo("") == 0) {
str = yPos.getText();
// Achtung, liefert manchmal den leeren String statt den richtigen
}
return Double.valueOf(str).doubleValue();
}
public synchronized double getZpos() {
String str = "";
while (str.compareTo("") == 0) {
str = zPos.getText();
// Achtung, liefert manchmal den leeren String statt den richtigen
}
return Double.valueOf(str).doubleValue();
}
public int getVol() {
return getIntensity();
}
public int getRed() {
return colorButton.getBackground().getRed();
}
public int getGreen() {
return colorButton.getBackground().getGreen();
}
public int getBlue() {
return colorButton.getBackground().getBlue();
}
public void setLampNo(int no) {
if(previewLamp!=null){
previewLamp.setLampNo(no);
}
lampNo = no;
nameLabel.setText(" " + lampNo);
//lichtstaerke.setTitle("l" + lampNo);
//SwingUtilities.updateComponentTreeUI(lichtstaerke);
}
public void updateActionCommands(int internalCunr) {
}
public String getSurfCode(int lampNo, String[] runningParams,
double[] runningParamsValue) {
String str="";
str+="light"+lampNo+"_x ="+evalWithPar(getXpos_str(),runningParams,runningParamsValue)+";\n";
str+="light"+lampNo+"_y ="+evalWithPar(getYpos_str(),runningParams,runningParamsValue)+";\n";
str+="light"+lampNo+"_z ="+evalWithPar(getZpos_str(),runningParams,runningParamsValue)+";\n";
str+="light"+lampNo+"_vol ="+getVol()+";\n";
str+="light"+lampNo+"_red ="+getRed()+";\n";
str+="light"+lampNo+"_green ="+getGreen()+";\n";
str+="light"+lampNo+"_blue ="+getBlue()+";\n";
return str;
}
public double evalWithPar(String s,String[] runningParams,
double[] runningParamsValue){
int i=0;
// System.out.println(s);
if(runningParams!=null){
for(int j=0;j<runningParams.length;j++){
// System.out.println("rv:"+runningParamsValue[j]);
s=s.replaceAll(runningParams[j],(new Double(runningParamsValue[j])).toString());
}
}
s=s.replaceAll(" ","");
s=s.replaceAll("\\*"," ");
/*
System.out.println("s1:"+s);
s= polyCalc.showAsPovrayCode(s);
System.out.println("s2:"+s);
if(s.length()>4){
s=s.substring(4,s.length()-1);
} //Double.valueOf(s).doubleValue()*genauigkeit;
// damit es waehrend der Eingabe keine Probleme gibt:
s=s.replaceAll("\\+","");
if(s.charAt(0)=='-'){
s=s.replaceAll("-","");
s="-"+s;
}else{
s=s.replaceAll("-","");
}
s=s.replaceAll("\\*","");
s=s.replaceAll("/","");
s=s.replaceAll("^","");
System.out.println("s3:"+s);
*/
try{
return Double.valueOf(s).doubleValue();
}catch(Exception e){
// System.out.println("ERROR: erst parameter auswaehlen ("+s+")");
}
return 0.0;
}
public void saveYourself(PrintWriter pw) {
String str = "";
pw.println("////////////////// Parameter: /////////////////////////"
+ "\n");
pw.println("" + lampNo + "\n");
pw.println("" + newFrom + "\n");
pw.println("" + newTo + "\n");
pw.println("" + intenseSlider.getValue() + "\n");
// pw.println(parLabel.getText()+"\n");
// pw.println(cbox.isSelected()+"\n");
//optionButtonPane.saveYourself(pw);
}
public String saveYourself() {
String str = "";
str += "////////////////// Parameter: /////////////////////////\n";
str += ("" + lampNo + "\n");
str += ("" + newFrom + "\n");
str += ("" + newTo + "\n");
str += ("" + intenseSlider.getValue() + "\n");
// str += (parLabel.getText()+"\n");
// str += (cbox.isSelected()+"\n");
return (str);
}
} // end of class OneParameter
|
206531_0 | package com.eringa.Reversi.service;
import com.eringa.Reversi.domain.ERole;
import com.eringa.Reversi.domain.Role;
import com.eringa.Reversi.domain.Score;
import com.eringa.Reversi.domain.User;
import com.eringa.Reversi.payload.request.LoginRequest;
import com.eringa.Reversi.payload.request.SignupRequest;
import com.eringa.Reversi.payload.response.JwtResponse;
import com.eringa.Reversi.payload.response.MessageResponse;
import com.eringa.Reversi.persistence.RoleRepository;
import com.eringa.Reversi.persistence.UserRepository;
import com.eringa.Reversi.persistence.ScoreRepository;
import com.eringa.Reversi.service.Security.jwt.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Service
@Validated
public class AuthorizationService {
private static final String ROLE_NOT_FOUND_ERROR = "Error: Role is not found.";
private UserRepository userRepository;
private PasswordEncoder encoder;
private RoleRepository roleRepository;
private ScoreRepository scoreRepository;
private AuthenticationManager authenticationManager;
private JwtUtils jwtUtils;
@Autowired
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Autowired
public void setEncoder(PasswordEncoder passwordEncoder) {
this.encoder = passwordEncoder;
}
@Autowired
public void setRoleRepository(RoleRepository roleRepository) {
this.roleRepository = roleRepository;
}
@Autowired
public void setScoreRepository(ScoreRepository scoreRepository) {
this.scoreRepository = scoreRepository;
}
@Autowired
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Autowired
public void setJwtUtils(JwtUtils jwtUtils) {
this.jwtUtils = jwtUtils;
}
/**
*
* Deze methode verwerkt de gebruiker die wil registreren. De username en e-mail worden gecheckt. Eventuele rollen
* worden toegevoegd en de gebruiker wordt opgeslagen in de database.
*
* @param signUpRequest de payload signup-request met gebruikersnaam en wachtwoord.
* @return een HTTP response met daarin een succesbericht.
*/
public ResponseEntity<MessageResponse> registerUser(@Valid SignupRequest signUpRequest) {
if (Boolean.TRUE.equals(userRepository.existsByUsername(signUpRequest.getUsername()))) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("This username is already taken! Please choose another."));
}
if (Boolean.TRUE.equals(userRepository.existsByEmail(signUpRequest.getEmail()))) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("This emailaddress is already in use! Please use it to login."));
}
// Create new user's account
User user = new User(signUpRequest.getUsername(),
signUpRequest.getEmail(),
encoder.encode(signUpRequest.getPassword()));
Set<String> strRoles = signUpRequest.getRole();
Set<Role> roles = new HashSet<>();
if (strRoles == null) {
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
.orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR));
roles.add(adminRole);
break;
case "mod":
Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
.orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR));
roles.add(modRole);
break;
default:
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR));
roles.add(userRole);
}
});
}
//create the initial scores in the score table.
Score initialscore = new Score();
initialscore.setGamesPlayed(0);
initialscore.setGamesWon(0);
initialscore.setStoneswon(0);
user.setRoles(roles);
userRepository.save(user);
scoreRepository.save(initialscore);
return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
}
/**
* Deze methode controleert de ontvangen username en wachtwoord. Het gebruikt hiervoor de
* AuthenticationManager. I.a.w. Spring security doet dit allemaal voor ons.
*
* Wanneer de gebruikersnaam/wachtwoord combinatie niet klopt, wordt er een Runtime exception gegooid:
* 401 Unauthorized. Deze wordt gegooid door
* {@link com.eringa.Reversi.service.Security.jwt.AuthEntryPointJwt}
*
*
* @param loginRequest De payload met username en password.
* @return een HTTP-response met daarin de JWT-token.
*/
public ResponseEntity<JwtResponse> authenticateUser(@Valid LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(),
loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
List<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toList());
return ResponseEntity.ok(new JwtResponse(jwt,
userDetails.getId(),
userDetails.getUsername(),
userDetails.getEmail(),
roles));
}
}
| Made-by-DJ/reversi4 | src/main/java/com/eringa/Reversi/service/AuthorizationService.java | 1,837 | /**
*
* Deze methode verwerkt de gebruiker die wil registreren. De username en e-mail worden gecheckt. Eventuele rollen
* worden toegevoegd en de gebruiker wordt opgeslagen in de database.
*
* @param signUpRequest de payload signup-request met gebruikersnaam en wachtwoord.
* @return een HTTP response met daarin een succesbericht.
*/ | block_comment | nl | package com.eringa.Reversi.service;
import com.eringa.Reversi.domain.ERole;
import com.eringa.Reversi.domain.Role;
import com.eringa.Reversi.domain.Score;
import com.eringa.Reversi.domain.User;
import com.eringa.Reversi.payload.request.LoginRequest;
import com.eringa.Reversi.payload.request.SignupRequest;
import com.eringa.Reversi.payload.response.JwtResponse;
import com.eringa.Reversi.payload.response.MessageResponse;
import com.eringa.Reversi.persistence.RoleRepository;
import com.eringa.Reversi.persistence.UserRepository;
import com.eringa.Reversi.persistence.ScoreRepository;
import com.eringa.Reversi.service.Security.jwt.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Service
@Validated
public class AuthorizationService {
private static final String ROLE_NOT_FOUND_ERROR = "Error: Role is not found.";
private UserRepository userRepository;
private PasswordEncoder encoder;
private RoleRepository roleRepository;
private ScoreRepository scoreRepository;
private AuthenticationManager authenticationManager;
private JwtUtils jwtUtils;
@Autowired
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Autowired
public void setEncoder(PasswordEncoder passwordEncoder) {
this.encoder = passwordEncoder;
}
@Autowired
public void setRoleRepository(RoleRepository roleRepository) {
this.roleRepository = roleRepository;
}
@Autowired
public void setScoreRepository(ScoreRepository scoreRepository) {
this.scoreRepository = scoreRepository;
}
@Autowired
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Autowired
public void setJwtUtils(JwtUtils jwtUtils) {
this.jwtUtils = jwtUtils;
}
/**
*
* Deze methode verwerkt<SUF>*/
public ResponseEntity<MessageResponse> registerUser(@Valid SignupRequest signUpRequest) {
if (Boolean.TRUE.equals(userRepository.existsByUsername(signUpRequest.getUsername()))) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("This username is already taken! Please choose another."));
}
if (Boolean.TRUE.equals(userRepository.existsByEmail(signUpRequest.getEmail()))) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("This emailaddress is already in use! Please use it to login."));
}
// Create new user's account
User user = new User(signUpRequest.getUsername(),
signUpRequest.getEmail(),
encoder.encode(signUpRequest.getPassword()));
Set<String> strRoles = signUpRequest.getRole();
Set<Role> roles = new HashSet<>();
if (strRoles == null) {
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
.orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR));
roles.add(adminRole);
break;
case "mod":
Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
.orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR));
roles.add(modRole);
break;
default:
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR));
roles.add(userRole);
}
});
}
//create the initial scores in the score table.
Score initialscore = new Score();
initialscore.setGamesPlayed(0);
initialscore.setGamesWon(0);
initialscore.setStoneswon(0);
user.setRoles(roles);
userRepository.save(user);
scoreRepository.save(initialscore);
return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
}
/**
* Deze methode controleert de ontvangen username en wachtwoord. Het gebruikt hiervoor de
* AuthenticationManager. I.a.w. Spring security doet dit allemaal voor ons.
*
* Wanneer de gebruikersnaam/wachtwoord combinatie niet klopt, wordt er een Runtime exception gegooid:
* 401 Unauthorized. Deze wordt gegooid door
* {@link com.eringa.Reversi.service.Security.jwt.AuthEntryPointJwt}
*
*
* @param loginRequest De payload met username en password.
* @return een HTTP-response met daarin de JWT-token.
*/
public ResponseEntity<JwtResponse> authenticateUser(@Valid LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(),
loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
List<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toList());
return ResponseEntity.ok(new JwtResponse(jwt,
userDetails.getId(),
userDetails.getUsername(),
userDetails.getEmail(),
roles));
}
}
|
140752_19 | /* _____ _
* |_ _| |_ _ _ ___ ___ _ __ __ _
* | | | ' \| '_/ -_) -_) ' \/ _` |_
* |_| |_||_|_| \___\___|_|_|_\__,_(_)
*
* Threema for Android
* Copyright (c) 2018-2024 Threema GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package ch.threema.app.emojis;
import android.graphics.Typeface;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.CharacterStyle;
import android.text.style.ForegroundColorSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EmptyStackException;
import java.util.HashMap;
import java.util.Stack;
import java.util.regex.Pattern;
import androidx.annotation.ColorInt;
import ch.threema.base.utils.LoggingUtil;
public class MarkupParser {
private static final Logger logger = LoggingUtil.getThreemaLogger("MarkupParser");
private static final String BOUNDARY_PATTERN = "[\\s.,!?¡¿‽⸮;:&(){}\\[\\]⟨⟩‹›«»'\"‘’“”*~\\-_…⋯᠁]";
private static final String URL_BOUNDARY_PATTERN = "[a-zA-Z0-9\\-._~:/?#\\[\\]@!$&'()*+,;=%]";
private static final String URL_START_PATTERN = "^[a-zA-Z]+://.*";
private static final char MARKUP_CHAR_BOLD = '*';
private static final char MARKUP_CHAR_ITALIC = '_';
private static final char MARKUP_CHAR_STRIKETHRU = '~';
public static final String MARKUP_CHAR_PATTERN = ".*[\\*_~].*";
private final Pattern boundaryPattern, urlBoundaryPattern, urlStartPattern;
// Singleton stuff
private static MarkupParser sInstance = null;
public static synchronized MarkupParser getInstance() {
if (sInstance == null) {
sInstance = new MarkupParser();
}
return sInstance;
}
private MarkupParser() {
this.boundaryPattern = Pattern.compile(BOUNDARY_PATTERN);
this.urlBoundaryPattern = Pattern.compile(URL_BOUNDARY_PATTERN);
this.urlStartPattern = Pattern.compile(URL_START_PATTERN);
}
private enum TokenType {
TEXT,
NEWLINE,
ASTERISK,
UNDERSCORE,
TILDE
}
private class Token {
TokenType kind;
int start;
int end;
private Token(TokenType kind, int start, int end) {
this.kind = kind;
this.start = start;
this.end = end;
}
}
private static class SpanItem {
TokenType kind;
int textStart;
int textEnd;
int markerStart;
int markerEnd;
SpanItem(TokenType kind, int textStart, int textEnd, int markerStart, int markerEnd) {
this.kind = kind;
this.textStart = textStart;
this.textEnd = textEnd;
this.markerStart = markerStart;
this.markerEnd = markerEnd;
}
}
// Booleans to avoid searching the stack.
// This is used for optimization.
public static class TokenPresenceMap extends HashMap<TokenType, Boolean> {
TokenPresenceMap() {
init();
}
public void init() {
this.put(TokenType.ASTERISK, false);
this.put(TokenType.UNDERSCORE, false);
this.put(TokenType.TILDE, false);
}
}
private HashMap<TokenType, Character> markupChars = new HashMap<>();
{
markupChars.put(TokenType.ASTERISK, MARKUP_CHAR_BOLD);
markupChars.put(TokenType.UNDERSCORE, MARKUP_CHAR_ITALIC);
markupChars.put(TokenType.TILDE, MARKUP_CHAR_STRIKETHRU);
}
/**
* Return whether the specified token type is a markup token.
*/
private boolean isMarkupToken(TokenType tokenType) {
return markupChars.containsKey(tokenType);
}
/**
* Return whether the character at the specified position in the string is a boundary character.
* When `character` is out of range, the function will return true.
*/
private boolean isBoundary(CharSequence text, int position) {
if (position < 0 || position >= text.length()) {
return true;
}
return boundaryPattern.matcher(TextUtils.substring(text, position, position + 1)).matches();
}
/**
* Return whether the specified character is a URL boundary character.
* When `character` is undefined, the function will return true.
*
* Characters that may be in an URL according to RFC 3986:
* ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=%
*/
private boolean isUrlBoundary(CharSequence text, int position) {
if (position < 0 || position >= text.length()) {
return true;
}
return !urlBoundaryPattern.matcher(TextUtils.substring(text, position, position + 1)).matches();
}
/**
* Return whether the specified string starts an URL.
*/
private boolean isUrlStart(CharSequence text, int position) {
if (position < 0 || position >= text.length()) {
return false;
}
return urlStartPattern.matcher(TextUtils.substring(text, position, text.length())).matches();
}
private int pushTextBufToken(int tokenLength, int i, ArrayList<Token> tokens) {
if (tokenLength > 0) {
tokens.add(new Token(TokenType.TEXT, i - tokenLength, i));
tokenLength = 0;
}
return tokenLength;
}
/**
* This function accepts a string and returns a list of tokens.
*/
private ArrayList<Token> tokenize(CharSequence text) {
int tokenLength = 0;
boolean matchingUrl = false;
ArrayList<Token> tokens = new ArrayList<>();
for (int i = 0; i < text.length(); i++) {
char currentChar = text.charAt(i);
// Detect URLs
if (!matchingUrl) {
matchingUrl = isUrlStart(text, i);
}
// URLs have a limited set of boundary characters, therefore we need to
// treat them separately.
if (matchingUrl) {
final boolean nextIsUrlBoundary = isUrlBoundary(text, i + 1);
if (nextIsUrlBoundary) {
tokenLength = pushTextBufToken(tokenLength, i, tokens);
matchingUrl = false;
}
tokenLength++;
} else {
final boolean prevIsBoundary = isBoundary(text, i - 1);
final boolean nextIsBoundary = isBoundary(text, i + 1);
if (currentChar == MARKUP_CHAR_BOLD && (prevIsBoundary || nextIsBoundary)) {
tokenLength = pushTextBufToken(tokenLength, i, tokens);
tokens.add(new Token(TokenType.ASTERISK, i, i + 1));
} else if (currentChar == MARKUP_CHAR_ITALIC && (prevIsBoundary || nextIsBoundary)) {
tokenLength = pushTextBufToken(tokenLength, i, tokens);
tokens.add(new Token(TokenType.UNDERSCORE, i, i + 1));
} else if (currentChar == MARKUP_CHAR_STRIKETHRU && (prevIsBoundary || nextIsBoundary)) {
tokenLength = pushTextBufToken(tokenLength, i, tokens);
tokens.add(new Token(TokenType.TILDE, i, i + 1));
} else if (currentChar == '\n') {
tokenLength = pushTextBufToken(tokenLength, i, tokens);
tokens.add(new Token(TokenType.NEWLINE, i, i + 1));
} else {
tokenLength++;
}
}
}
pushTextBufToken(tokenLength - 1, text.length() - 1, tokens);
return tokens;
}
private void applySpans(SpannableStringBuilder s, Stack<SpanItem> spanStack) {
ArrayList<Integer> deletables = new ArrayList<>();
while(!spanStack.isEmpty()) {
SpanItem span = spanStack.pop();
if (span.textStart > span.textEnd) {
logger.debug("range problem. ignore");
} else {
if (span.textStart > 0 && span.textEnd < s.length()) {
if (span.textStart != span.textEnd) {
s.setSpan(getCharacterStyle(span.kind), span.textStart, span.textEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
deletables.add(span.markerStart);
deletables.add(span.markerEnd);
}
}
}
}
if (deletables.size() > 0) {
Collections.sort(deletables, Collections.reverseOrder());
for (int deletable : deletables) {
s.delete(deletable, deletable + 1);
}
}
}
private void applySpans(Editable s, @ColorInt int markerColor, Stack<SpanItem> spanStack) {
while(!spanStack.isEmpty()) {
SpanItem span = spanStack.pop();
if (span.textStart > span.textEnd) {
logger.debug("range problem. ignore");
} else {
if (span.textStart > 0 && span.textEnd < s.length()) {
if (span.textStart != span.textEnd) {
s.setSpan(getCharacterStyle(span.kind), span.textStart, span.textEnd, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
s.setSpan(new ForegroundColorSpan(markerColor), span.markerStart, span.markerStart + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
s.setSpan(new ForegroundColorSpan(markerColor), span.markerEnd, span.markerEnd + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
}
}
// Helper: Pop the stack, throw an exception if it's empty
private Token popStack(Stack<Token> stack) throws MarkupParserException {
try {
return stack.pop();
} catch (EmptyStackException e) {
throw new MarkupParserException("Stack is empty");
}
}
private static CharacterStyle getCharacterStyle(TokenType tokenType) {
switch (tokenType) {
case UNDERSCORE:
return new StyleSpan(Typeface.ITALIC);
case ASTERISK:
return new StyleSpan(Typeface.BOLD);
case TILDE:
default:
return new StrikethroughSpan();
}
}
private void parse(ArrayList<Token> tokens, SpannableStringBuilder builder, Editable editable, @ColorInt int markerColor) throws MarkupParserException {
// Process the tokens. Add them to a stack. When a token pair is complete
// (e.g. the second asterisk is found), pop the stack until you find the
// matching token and convert everything in between to formatted text.
Stack<Token> stack = new Stack<>();
Stack<SpanItem> spanStack = new Stack<>();
TokenPresenceMap tokenPresenceMap = new TokenPresenceMap();
for (Token token : tokens) {
switch (token.kind) {
// Keep text as-is
case TEXT:
stack.push(token);
break;
// If a markup token is found, try to find a matching token.
case ASTERISK:
case UNDERSCORE:
case TILDE:
// Optimization: Only search the stack if a token with this token type exists
if (tokenPresenceMap.get(token.kind)) {
// Pop tokens from the stack. If a matching token was found, apply
// markup to the text parts in between those two tokens.
Stack<Token> textParts = new Stack<>();
while (true) {
Token stackTop = popStack(stack);
if (stackTop.kind == TokenType.TEXT) {
textParts.push(stackTop);
} else if (stackTop.kind == token.kind) {
int start, end;
if (textParts.size() == 0) {
// no text in between two markups
start = end = stackTop.end;
} else {
start = textParts.get(textParts.size() - 1).start;
end = textParts.get(0).end;
}
spanStack.push(new SpanItem(token.kind, start, end, stackTop.start, token.start));
stack.push(new Token(TokenType.TEXT, start, end));
tokenPresenceMap.put(token.kind, false);
break;
} else if (isMarkupToken(stackTop.kind)) {
textParts.push(new Token(TokenType.TEXT, stackTop.start, stackTop.end));
} else {
throw new MarkupParserException("Unknown token on stack: " + token.kind);
}
tokenPresenceMap.put(stackTop.kind, false);
}
} else {
stack.push(token);
tokenPresenceMap.put(token.kind, true);
}
break;
// Don't apply formatting across newlines
case NEWLINE:
tokenPresenceMap.init();
break;
default:
throw new MarkupParserException("Invalid token kind: " + token.kind);
}
}
// Concatenate processed tokens
if (builder != null) {
applySpans(builder, spanStack);
} else {
if (spanStack.size() > 0) {
applySpans(editable, markerColor, spanStack);
}
}
}
/**
* Add text markup to given SpannableStringBuilder
* @param builder
*/
public void markify(SpannableStringBuilder builder) {
try {
parse(tokenize(builder), builder, null, 0);
} catch (Exception e) {
//
}
}
/**
* Add text markup to text in given editable.
* @param editable Editable to be markified
* @param markerColor Desired color of markup markers
*/
public void markify(Editable editable, @ColorInt int markerColor) {
try {
parse(tokenize(editable), null, editable, markerColor);
} catch (Exception e) {
//
}
}
public class MarkupParserException extends Exception {
MarkupParserException(String e) {
super(e);
}
}
}
| MagicAndre1981/threema-android | app/src/main/java/ch/threema/app/emojis/MarkupParser.java | 4,257 | // no text in between two markups | line_comment | nl | /* _____ _
* |_ _| |_ _ _ ___ ___ _ __ __ _
* | | | ' \| '_/ -_) -_) ' \/ _` |_
* |_| |_||_|_| \___\___|_|_|_\__,_(_)
*
* Threema for Android
* Copyright (c) 2018-2024 Threema GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package ch.threema.app.emojis;
import android.graphics.Typeface;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.CharacterStyle;
import android.text.style.ForegroundColorSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EmptyStackException;
import java.util.HashMap;
import java.util.Stack;
import java.util.regex.Pattern;
import androidx.annotation.ColorInt;
import ch.threema.base.utils.LoggingUtil;
public class MarkupParser {
private static final Logger logger = LoggingUtil.getThreemaLogger("MarkupParser");
private static final String BOUNDARY_PATTERN = "[\\s.,!?¡¿‽⸮;:&(){}\\[\\]⟨⟩‹›«»'\"‘’“”*~\\-_…⋯᠁]";
private static final String URL_BOUNDARY_PATTERN = "[a-zA-Z0-9\\-._~:/?#\\[\\]@!$&'()*+,;=%]";
private static final String URL_START_PATTERN = "^[a-zA-Z]+://.*";
private static final char MARKUP_CHAR_BOLD = '*';
private static final char MARKUP_CHAR_ITALIC = '_';
private static final char MARKUP_CHAR_STRIKETHRU = '~';
public static final String MARKUP_CHAR_PATTERN = ".*[\\*_~].*";
private final Pattern boundaryPattern, urlBoundaryPattern, urlStartPattern;
// Singleton stuff
private static MarkupParser sInstance = null;
public static synchronized MarkupParser getInstance() {
if (sInstance == null) {
sInstance = new MarkupParser();
}
return sInstance;
}
private MarkupParser() {
this.boundaryPattern = Pattern.compile(BOUNDARY_PATTERN);
this.urlBoundaryPattern = Pattern.compile(URL_BOUNDARY_PATTERN);
this.urlStartPattern = Pattern.compile(URL_START_PATTERN);
}
private enum TokenType {
TEXT,
NEWLINE,
ASTERISK,
UNDERSCORE,
TILDE
}
private class Token {
TokenType kind;
int start;
int end;
private Token(TokenType kind, int start, int end) {
this.kind = kind;
this.start = start;
this.end = end;
}
}
private static class SpanItem {
TokenType kind;
int textStart;
int textEnd;
int markerStart;
int markerEnd;
SpanItem(TokenType kind, int textStart, int textEnd, int markerStart, int markerEnd) {
this.kind = kind;
this.textStart = textStart;
this.textEnd = textEnd;
this.markerStart = markerStart;
this.markerEnd = markerEnd;
}
}
// Booleans to avoid searching the stack.
// This is used for optimization.
public static class TokenPresenceMap extends HashMap<TokenType, Boolean> {
TokenPresenceMap() {
init();
}
public void init() {
this.put(TokenType.ASTERISK, false);
this.put(TokenType.UNDERSCORE, false);
this.put(TokenType.TILDE, false);
}
}
private HashMap<TokenType, Character> markupChars = new HashMap<>();
{
markupChars.put(TokenType.ASTERISK, MARKUP_CHAR_BOLD);
markupChars.put(TokenType.UNDERSCORE, MARKUP_CHAR_ITALIC);
markupChars.put(TokenType.TILDE, MARKUP_CHAR_STRIKETHRU);
}
/**
* Return whether the specified token type is a markup token.
*/
private boolean isMarkupToken(TokenType tokenType) {
return markupChars.containsKey(tokenType);
}
/**
* Return whether the character at the specified position in the string is a boundary character.
* When `character` is out of range, the function will return true.
*/
private boolean isBoundary(CharSequence text, int position) {
if (position < 0 || position >= text.length()) {
return true;
}
return boundaryPattern.matcher(TextUtils.substring(text, position, position + 1)).matches();
}
/**
* Return whether the specified character is a URL boundary character.
* When `character` is undefined, the function will return true.
*
* Characters that may be in an URL according to RFC 3986:
* ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=%
*/
private boolean isUrlBoundary(CharSequence text, int position) {
if (position < 0 || position >= text.length()) {
return true;
}
return !urlBoundaryPattern.matcher(TextUtils.substring(text, position, position + 1)).matches();
}
/**
* Return whether the specified string starts an URL.
*/
private boolean isUrlStart(CharSequence text, int position) {
if (position < 0 || position >= text.length()) {
return false;
}
return urlStartPattern.matcher(TextUtils.substring(text, position, text.length())).matches();
}
private int pushTextBufToken(int tokenLength, int i, ArrayList<Token> tokens) {
if (tokenLength > 0) {
tokens.add(new Token(TokenType.TEXT, i - tokenLength, i));
tokenLength = 0;
}
return tokenLength;
}
/**
* This function accepts a string and returns a list of tokens.
*/
private ArrayList<Token> tokenize(CharSequence text) {
int tokenLength = 0;
boolean matchingUrl = false;
ArrayList<Token> tokens = new ArrayList<>();
for (int i = 0; i < text.length(); i++) {
char currentChar = text.charAt(i);
// Detect URLs
if (!matchingUrl) {
matchingUrl = isUrlStart(text, i);
}
// URLs have a limited set of boundary characters, therefore we need to
// treat them separately.
if (matchingUrl) {
final boolean nextIsUrlBoundary = isUrlBoundary(text, i + 1);
if (nextIsUrlBoundary) {
tokenLength = pushTextBufToken(tokenLength, i, tokens);
matchingUrl = false;
}
tokenLength++;
} else {
final boolean prevIsBoundary = isBoundary(text, i - 1);
final boolean nextIsBoundary = isBoundary(text, i + 1);
if (currentChar == MARKUP_CHAR_BOLD && (prevIsBoundary || nextIsBoundary)) {
tokenLength = pushTextBufToken(tokenLength, i, tokens);
tokens.add(new Token(TokenType.ASTERISK, i, i + 1));
} else if (currentChar == MARKUP_CHAR_ITALIC && (prevIsBoundary || nextIsBoundary)) {
tokenLength = pushTextBufToken(tokenLength, i, tokens);
tokens.add(new Token(TokenType.UNDERSCORE, i, i + 1));
} else if (currentChar == MARKUP_CHAR_STRIKETHRU && (prevIsBoundary || nextIsBoundary)) {
tokenLength = pushTextBufToken(tokenLength, i, tokens);
tokens.add(new Token(TokenType.TILDE, i, i + 1));
} else if (currentChar == '\n') {
tokenLength = pushTextBufToken(tokenLength, i, tokens);
tokens.add(new Token(TokenType.NEWLINE, i, i + 1));
} else {
tokenLength++;
}
}
}
pushTextBufToken(tokenLength - 1, text.length() - 1, tokens);
return tokens;
}
private void applySpans(SpannableStringBuilder s, Stack<SpanItem> spanStack) {
ArrayList<Integer> deletables = new ArrayList<>();
while(!spanStack.isEmpty()) {
SpanItem span = spanStack.pop();
if (span.textStart > span.textEnd) {
logger.debug("range problem. ignore");
} else {
if (span.textStart > 0 && span.textEnd < s.length()) {
if (span.textStart != span.textEnd) {
s.setSpan(getCharacterStyle(span.kind), span.textStart, span.textEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
deletables.add(span.markerStart);
deletables.add(span.markerEnd);
}
}
}
}
if (deletables.size() > 0) {
Collections.sort(deletables, Collections.reverseOrder());
for (int deletable : deletables) {
s.delete(deletable, deletable + 1);
}
}
}
private void applySpans(Editable s, @ColorInt int markerColor, Stack<SpanItem> spanStack) {
while(!spanStack.isEmpty()) {
SpanItem span = spanStack.pop();
if (span.textStart > span.textEnd) {
logger.debug("range problem. ignore");
} else {
if (span.textStart > 0 && span.textEnd < s.length()) {
if (span.textStart != span.textEnd) {
s.setSpan(getCharacterStyle(span.kind), span.textStart, span.textEnd, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
s.setSpan(new ForegroundColorSpan(markerColor), span.markerStart, span.markerStart + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
s.setSpan(new ForegroundColorSpan(markerColor), span.markerEnd, span.markerEnd + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
}
}
// Helper: Pop the stack, throw an exception if it's empty
private Token popStack(Stack<Token> stack) throws MarkupParserException {
try {
return stack.pop();
} catch (EmptyStackException e) {
throw new MarkupParserException("Stack is empty");
}
}
private static CharacterStyle getCharacterStyle(TokenType tokenType) {
switch (tokenType) {
case UNDERSCORE:
return new StyleSpan(Typeface.ITALIC);
case ASTERISK:
return new StyleSpan(Typeface.BOLD);
case TILDE:
default:
return new StrikethroughSpan();
}
}
private void parse(ArrayList<Token> tokens, SpannableStringBuilder builder, Editable editable, @ColorInt int markerColor) throws MarkupParserException {
// Process the tokens. Add them to a stack. When a token pair is complete
// (e.g. the second asterisk is found), pop the stack until you find the
// matching token and convert everything in between to formatted text.
Stack<Token> stack = new Stack<>();
Stack<SpanItem> spanStack = new Stack<>();
TokenPresenceMap tokenPresenceMap = new TokenPresenceMap();
for (Token token : tokens) {
switch (token.kind) {
// Keep text as-is
case TEXT:
stack.push(token);
break;
// If a markup token is found, try to find a matching token.
case ASTERISK:
case UNDERSCORE:
case TILDE:
// Optimization: Only search the stack if a token with this token type exists
if (tokenPresenceMap.get(token.kind)) {
// Pop tokens from the stack. If a matching token was found, apply
// markup to the text parts in between those two tokens.
Stack<Token> textParts = new Stack<>();
while (true) {
Token stackTop = popStack(stack);
if (stackTop.kind == TokenType.TEXT) {
textParts.push(stackTop);
} else if (stackTop.kind == token.kind) {
int start, end;
if (textParts.size() == 0) {
// no text<SUF>
start = end = stackTop.end;
} else {
start = textParts.get(textParts.size() - 1).start;
end = textParts.get(0).end;
}
spanStack.push(new SpanItem(token.kind, start, end, stackTop.start, token.start));
stack.push(new Token(TokenType.TEXT, start, end));
tokenPresenceMap.put(token.kind, false);
break;
} else if (isMarkupToken(stackTop.kind)) {
textParts.push(new Token(TokenType.TEXT, stackTop.start, stackTop.end));
} else {
throw new MarkupParserException("Unknown token on stack: " + token.kind);
}
tokenPresenceMap.put(stackTop.kind, false);
}
} else {
stack.push(token);
tokenPresenceMap.put(token.kind, true);
}
break;
// Don't apply formatting across newlines
case NEWLINE:
tokenPresenceMap.init();
break;
default:
throw new MarkupParserException("Invalid token kind: " + token.kind);
}
}
// Concatenate processed tokens
if (builder != null) {
applySpans(builder, spanStack);
} else {
if (spanStack.size() > 0) {
applySpans(editable, markerColor, spanStack);
}
}
}
/**
* Add text markup to given SpannableStringBuilder
* @param builder
*/
public void markify(SpannableStringBuilder builder) {
try {
parse(tokenize(builder), builder, null, 0);
} catch (Exception e) {
//
}
}
/**
* Add text markup to text in given editable.
* @param editable Editable to be markified
* @param markerColor Desired color of markup markers
*/
public void markify(Editable editable, @ColorInt int markerColor) {
try {
parse(tokenize(editable), null, editable, markerColor);
} catch (Exception e) {
//
}
}
public class MarkupParserException extends Exception {
MarkupParserException(String e) {
super(e);
}
}
}
|
10262_2 | package eu.magisterapp.magisterapp.Storage;
import android.content.Context;
import android.util.Log;
import org.joda.time.DateTime;
import java.io.IOException;
import java.util.ArrayList;
import eu.magisterapp.magisterapi.AfspraakList;
import eu.magisterapp.magisterapp.MagisterApp;
import eu.magisterapp.magisterapp.NoInternetException;
import eu.magisterapp.magisterapi.Afspraak;
import eu.magisterapp.magisterapi.Cijfer;
import eu.magisterapp.magisterapi.CijferList;
import eu.magisterapp.magisterapi.MagisterAPI;
import eu.magisterapp.magisterapi.Sessie;
import eu.magisterapp.magisterapi.Utils;
/**
* Created by max on 13-12-15.
*/
public class DataFixer {
private static final String TAG = "Storage.DataFixer";
private MagisterAPI api;
private MagisterDatabase db;
private MagisterApp app;
private Context context;
public static class ResultBundle
{
public AfspraakList afspraken;
public CijferList cijfers;
public CijferList recentCijfers;
public void setAfspraken(AfspraakList afspraken)
{
this.afspraken = afspraken;
}
public void setCijfers(CijferList cijfers)
{
this.cijfers = cijfers;
}
public void setRecentCijfers(CijferList cijfers) { this.recentCijfers = cijfers; }
}
public interface OnResultInterface
{
void onResult(ResultBundle result);
}
public DataFixer(MagisterAPI api, Context context)
{
this.api = api;
db = new MagisterDatabase(context);
this.context = context;
app = (MagisterApp) context.getApplicationContext();
}
public int getDaysInAdvance()
{
return context.getSharedPreferences(MagisterApp.PREFS_NAME, 0).getInt(MagisterApp.PREFS_DAYS_IN_ADVANCE, 21);
}
public AfspraakList getNextDay() throws IOException
{
if (app.hasInternet())
{
try
{
db.insertAfspraken(app.getOwner(), api.getAfspraken(Utils.now(), Utils.deltaDays(getDaysInAdvance())));
}
catch (IOException e)
{
// het is jammer.
}
}
return getNextDayFromCache();
}
public AfspraakList getNextDayFromCache() throws IOException
{
AfspraakList afspraken = db.queryAfspraken("WHERE Einde >= ? AND owner = ? ORDER BY Start ASC LIMIT ?", db.now(), app.getOwner(), "1");
Afspraak eerste;
if (afspraken.size() > 0) eerste = afspraken.get(0);
else return afspraken;
DateTime start = eerste.Start; // Begin van 1e afspraak
DateTime end = start.withTimeAtStartOfDay().plusDays(1); // begin van volgende dag.
return getAfsprakenFromCache(DateTime.now(), end);
}
public AfspraakList getAfspraken(DateTime van, DateTime tot) throws IOException
{
fetchOnlineAfspraken(van, tot);
return getAfsprakenFromCache(van, tot);
}
public void fetchOnlineAfspraken(DateTime van, DateTime tot) throws IOException
{
if (! app.hasInternet()) throw new NoInternetException();
AfspraakList afspraken = app.getApi().getAfspraken(van, tot);
AfspraakList wijzigingen = app.getApi().getMainSessie().getRoosterWijzigingen(van, tot);
for(Afspraak wijziging : wijzigingen) {
Log.i(TAG, "Er is een wijziging.");
// Uitval
if (wijziging.Id == -1)
{
DateTime start = wijziging.Start;
DateTime einde = wijziging.Einde;
for (Afspraak afspraak : afspraken)
{
if (afspraak.Start.isEqual(start) && afspraak.Einde.isEqual(einde))
{
afspraak.Status = Afspraak.StatusEnum.GEENSTATUS;
break;
}
}
break;
}
// Normale wijzigingen.
for (int i = 0; i < afspraken.size(); i++)
{
if (afspraken.get(i).Id == wijziging.Id)
{
wijziging.isLokaalGewijzigd = true;
afspraken.set(i, wijziging);
break; // elke wijziging hoort maar bij 1 afspraak
}
}
}
if (afspraken.size() > 0) db.cleanAfspraken(van, tot);
db.insertAfspraken(app.getOwner(), afspraken);
}
public AfspraakList getAfsprakenFromCache(DateTime van, DateTime tot) throws IOException
{
return db.queryAfspraken("WHERE ((Start < @now AND Einde > @end) " +
"OR (Start > @now AND Einde < @end) " +
"OR (@now BETWEEN Start AND Einde) " +
"OR (@end BETWEEN Start AND Einde)) " +
"AND owner = ? " +
"ORDER BY Start ASC", db.ms(van), db.ms(tot), app.getOwner());
}
public CijferList getCijfers() throws IOException
{
fetchOnlineCijfers();
return getCijfersFromCache();
}
public void fetchOnlineCijfers() throws IOException
{
if (! app.hasInternet()) throw new NoInternetException();
// TODO: meerdere accounts: stop sessie van huidige account hierin, ipv mainsessie.
Sessie sessie = app.getApi().getMainSessie();
CijferList cijfers = sessie.getCijfers();
ArrayList<Cijfer.CijferInfo> info = new ArrayList<>();
for (Cijfer cijfer : cijfers)
{
Cijfer.CijferInfo cijferInfo = getCijferInfo(cijfer, sessie);
info.add(cijferInfo);
cijfer.setInfo(cijferInfo);
}
db.insertCijfers(sessie.id, cijfers);
db.insertCijferInfo(info);
}
public CijferList getCijfersFromCache() throws IOException
{
CijferList cijfers = db.queryCijfers("WHERE owner = ?", app.getOwner());
for (Cijfer cijfer : cijfers)
{
// query in een loop.. kan vast wel beter.
cijfer.setInfo(getCijferInfo(cijfer, null));
}
return cijfers;
}
private Cijfer.CijferInfo getCijferInfo(Cijfer cijfer, Sessie sessie) throws IOException
{
Cijfer.CijferInfo dbInfo = db.getCijferInfo(cijfer);
if (dbInfo != null) return dbInfo;
// Geen sessie beschikbaar, en het staat niet in de database. Als het goed is
// komt dit nooit voor, want zonder sessie en zonder cache zijn er ook geen cijfers.
if (sessie == null) return null;
return sessie.getCijferInfo(cijfer);
}
public CijferList getRecentCijfers() throws IOException
{
fetchOnlineRecentCijfers();
return getRecentCijfersFromCache();
}
public void fetchOnlineRecentCijfers() throws IOException
{
// TODO: meerdere accounts: stop sessie van huidige account hierin, ipv mainsessie.
db.insertRecentCijfers(app.getOwner(), app.getApi().getRecentCijfers());
}
public CijferList getRecentCijfersFromCache() throws IOException
{
// TODO: misschien een "seen" flag erop tyfen, zodat je niet zo vaak naar je 1.3 op duits hoeft te kijken.
return db.queryRecentCijfers("WHERE owner = ?", app.getOwner());
}
public MagisterDatabase getDB()
{
return db;
}
}
| Magister-Android/Magister-Android | app/src/main/java/eu/magisterapp/magisterapp/Storage/DataFixer.java | 2,296 | // Begin van 1e afspraak | line_comment | nl | package eu.magisterapp.magisterapp.Storage;
import android.content.Context;
import android.util.Log;
import org.joda.time.DateTime;
import java.io.IOException;
import java.util.ArrayList;
import eu.magisterapp.magisterapi.AfspraakList;
import eu.magisterapp.magisterapp.MagisterApp;
import eu.magisterapp.magisterapp.NoInternetException;
import eu.magisterapp.magisterapi.Afspraak;
import eu.magisterapp.magisterapi.Cijfer;
import eu.magisterapp.magisterapi.CijferList;
import eu.magisterapp.magisterapi.MagisterAPI;
import eu.magisterapp.magisterapi.Sessie;
import eu.magisterapp.magisterapi.Utils;
/**
* Created by max on 13-12-15.
*/
public class DataFixer {
private static final String TAG = "Storage.DataFixer";
private MagisterAPI api;
private MagisterDatabase db;
private MagisterApp app;
private Context context;
public static class ResultBundle
{
public AfspraakList afspraken;
public CijferList cijfers;
public CijferList recentCijfers;
public void setAfspraken(AfspraakList afspraken)
{
this.afspraken = afspraken;
}
public void setCijfers(CijferList cijfers)
{
this.cijfers = cijfers;
}
public void setRecentCijfers(CijferList cijfers) { this.recentCijfers = cijfers; }
}
public interface OnResultInterface
{
void onResult(ResultBundle result);
}
public DataFixer(MagisterAPI api, Context context)
{
this.api = api;
db = new MagisterDatabase(context);
this.context = context;
app = (MagisterApp) context.getApplicationContext();
}
public int getDaysInAdvance()
{
return context.getSharedPreferences(MagisterApp.PREFS_NAME, 0).getInt(MagisterApp.PREFS_DAYS_IN_ADVANCE, 21);
}
public AfspraakList getNextDay() throws IOException
{
if (app.hasInternet())
{
try
{
db.insertAfspraken(app.getOwner(), api.getAfspraken(Utils.now(), Utils.deltaDays(getDaysInAdvance())));
}
catch (IOException e)
{
// het is jammer.
}
}
return getNextDayFromCache();
}
public AfspraakList getNextDayFromCache() throws IOException
{
AfspraakList afspraken = db.queryAfspraken("WHERE Einde >= ? AND owner = ? ORDER BY Start ASC LIMIT ?", db.now(), app.getOwner(), "1");
Afspraak eerste;
if (afspraken.size() > 0) eerste = afspraken.get(0);
else return afspraken;
DateTime start = eerste.Start; // Begin van<SUF>
DateTime end = start.withTimeAtStartOfDay().plusDays(1); // begin van volgende dag.
return getAfsprakenFromCache(DateTime.now(), end);
}
public AfspraakList getAfspraken(DateTime van, DateTime tot) throws IOException
{
fetchOnlineAfspraken(van, tot);
return getAfsprakenFromCache(van, tot);
}
public void fetchOnlineAfspraken(DateTime van, DateTime tot) throws IOException
{
if (! app.hasInternet()) throw new NoInternetException();
AfspraakList afspraken = app.getApi().getAfspraken(van, tot);
AfspraakList wijzigingen = app.getApi().getMainSessie().getRoosterWijzigingen(van, tot);
for(Afspraak wijziging : wijzigingen) {
Log.i(TAG, "Er is een wijziging.");
// Uitval
if (wijziging.Id == -1)
{
DateTime start = wijziging.Start;
DateTime einde = wijziging.Einde;
for (Afspraak afspraak : afspraken)
{
if (afspraak.Start.isEqual(start) && afspraak.Einde.isEqual(einde))
{
afspraak.Status = Afspraak.StatusEnum.GEENSTATUS;
break;
}
}
break;
}
// Normale wijzigingen.
for (int i = 0; i < afspraken.size(); i++)
{
if (afspraken.get(i).Id == wijziging.Id)
{
wijziging.isLokaalGewijzigd = true;
afspraken.set(i, wijziging);
break; // elke wijziging hoort maar bij 1 afspraak
}
}
}
if (afspraken.size() > 0) db.cleanAfspraken(van, tot);
db.insertAfspraken(app.getOwner(), afspraken);
}
public AfspraakList getAfsprakenFromCache(DateTime van, DateTime tot) throws IOException
{
return db.queryAfspraken("WHERE ((Start < @now AND Einde > @end) " +
"OR (Start > @now AND Einde < @end) " +
"OR (@now BETWEEN Start AND Einde) " +
"OR (@end BETWEEN Start AND Einde)) " +
"AND owner = ? " +
"ORDER BY Start ASC", db.ms(van), db.ms(tot), app.getOwner());
}
public CijferList getCijfers() throws IOException
{
fetchOnlineCijfers();
return getCijfersFromCache();
}
public void fetchOnlineCijfers() throws IOException
{
if (! app.hasInternet()) throw new NoInternetException();
// TODO: meerdere accounts: stop sessie van huidige account hierin, ipv mainsessie.
Sessie sessie = app.getApi().getMainSessie();
CijferList cijfers = sessie.getCijfers();
ArrayList<Cijfer.CijferInfo> info = new ArrayList<>();
for (Cijfer cijfer : cijfers)
{
Cijfer.CijferInfo cijferInfo = getCijferInfo(cijfer, sessie);
info.add(cijferInfo);
cijfer.setInfo(cijferInfo);
}
db.insertCijfers(sessie.id, cijfers);
db.insertCijferInfo(info);
}
public CijferList getCijfersFromCache() throws IOException
{
CijferList cijfers = db.queryCijfers("WHERE owner = ?", app.getOwner());
for (Cijfer cijfer : cijfers)
{
// query in een loop.. kan vast wel beter.
cijfer.setInfo(getCijferInfo(cijfer, null));
}
return cijfers;
}
private Cijfer.CijferInfo getCijferInfo(Cijfer cijfer, Sessie sessie) throws IOException
{
Cijfer.CijferInfo dbInfo = db.getCijferInfo(cijfer);
if (dbInfo != null) return dbInfo;
// Geen sessie beschikbaar, en het staat niet in de database. Als het goed is
// komt dit nooit voor, want zonder sessie en zonder cache zijn er ook geen cijfers.
if (sessie == null) return null;
return sessie.getCijferInfo(cijfer);
}
public CijferList getRecentCijfers() throws IOException
{
fetchOnlineRecentCijfers();
return getRecentCijfersFromCache();
}
public void fetchOnlineRecentCijfers() throws IOException
{
// TODO: meerdere accounts: stop sessie van huidige account hierin, ipv mainsessie.
db.insertRecentCijfers(app.getOwner(), app.getApi().getRecentCijfers());
}
public CijferList getRecentCijfersFromCache() throws IOException
{
// TODO: misschien een "seen" flag erop tyfen, zodat je niet zo vaak naar je 1.3 op duits hoeft te kijken.
return db.queryRecentCijfers("WHERE owner = ?", app.getOwner());
}
public MagisterDatabase getDB()
{
return db;
}
}
|
22119_4 | package eu.magisterapp.magisterapi;
import org.joda.time.DateTime;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.CookieManager;
import java.net.HttpCookie;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import eu.magisterapp.magisterapi.afwijkingen.ZernikeAfwijking;
/**
* Created by max on 7-12-15.
*/
public class Sessie {
public static final Integer SESSION_TIMEOUT = 60*20*1000; // 20 minuten in ms
public static final String ERROR_LOGIN = "Er is iets fout gegaan tijdens het inloggen.";
private Long loggedInAt = 0L;
private final String username;
private final String password;
private final String school;
private final Map<String, String> payload;
private String apiKeyHeader;
private String apiKey;
private MagisterConnection connection;
private final URLS urls;
private CookieManager cookies = new CookieManager();
private Account account;
private AanmeldingenList aanmeldingen;
public final String id;
public Sessie(String gebruikersnaam, String wachtwoord, String school, MagisterConnection connection)
{
this.username = gebruikersnaam;
this.password = wachtwoord;
this.school = school;
this.connection = connection;
urls = new URLS(school);
payload = new HashMap<String, String>() {{
put("Gebruikersnaam", username);
put("Wachtwoord", password);
}};
id = "un:" + gebruikersnaam + "sc:" + school;
}
public boolean loggedIn()
{
return ! isExpired() && cookies.getCookieStore().getCookies().size() > 0;
}
public synchronized void logOut()
{
cookies.getCookieStore().removeAll();
loggedInAt = 0L;
}
private boolean isExpired()
{
return loggedInAt + (SESSION_TIMEOUT - 1000) < System.currentTimeMillis();
}
public synchronized void login() throws IOException
{
cookies.getCookieStore().removeAll();
connection.delete(urls.session(), this);
Response response = connection.post(urls.login(), payload, this);
if (response.isError() && response.isJson())
{
try
{
JSONObject json;
if ((json = response.getJson()) != null)
{
throw new BadResponseException(json.getString("message"));
}
}
catch (JSONException e)
{
throw new BadResponseException(ERROR_LOGIN);
}
}
else if(! response.isJson())
{
// Als het response geen JSON is, kunnen we vrij
// weinig. Daarom boeken we 'm hier maar voordat
// we Nullpointers naar niet-bestaande json krijgen.
throw new BadResponseException(ERROR_LOGIN);
}
if (response.headers.get("Set-Cookie") != null && response.headers.get("Set-Cookie").size() > 0)
{
// Cookies worden op de sessie gezet door de connection.
loggedInAt = System.currentTimeMillis();
}
else
{
throw new BadResponseException(ERROR_LOGIN);
}
}
private synchronized void loginIfNotLoggedIn() throws IOException
{
if (! loggedIn()) login();
}
public String getCookies()
{
if (cookies.getCookieStore().getCookies().size() == 0)
{
return "";
}
StringBuilder builder = new StringBuilder();
for (HttpCookie cookie : cookies.getCookieStore().getCookies())
{
builder.append(cookie.toString()).append(';');
}
return builder.toString();
}
public String getApiKeyHeader() throws IOException
{
if (shouldRefresh()) refresh();
return apiKeyHeader;
}
public String getApiKey() throws IOException
{
if (shouldRefresh()) refresh();
return apiKey;
}
private boolean shouldRefresh()
{
return apiKeyHeader == null || "".equals(apiKeyHeader) || apiKey == null || "".equals(apiKey);
}
private void refresh() throws IOException
{
String body = MagisterConnection.anonymousGet(urls.base()).body;
Pattern headerPattern = Pattern.compile("apiKeyHeader: '([a-zA-Z0-9-]+)'");
Pattern keyPattern = Pattern.compile("apiKey: '([a-zA-Z0-9-]+)'");
Matcher headerMatcher = headerPattern.matcher(body);
Matcher keyMatcher = keyPattern.matcher(body);
if (headerMatcher.find()) apiKeyHeader = headerMatcher.group(1);
if (keyMatcher.find()) apiKey = keyMatcher.group(1);
}
public synchronized void storeCookies(String cookieString)
{
cookies.getCookieStore().add(null, HttpCookie.parse(cookieString).get(0));
}
public Account getAccount() throws IOException
{
if (account != null) return account;
loginIfNotLoggedIn();
try
{
return account = new Account(connection, urls.account(), this);
}
catch (ParseException | JSONException e)
{
e.printStackTrace();
throw new BadResponseException("Fout bij het ophalen van account gegevens.");
}
}
public AfspraakList getAfspraken(DateTime van, DateTime tot) throws IOException
{
return getAfspraken(van, tot, true);
}
public AfspraakList getAfspraken(DateTime van, DateTime tot, boolean geenUitval) throws IOException
{
loginIfNotLoggedIn();
String url = urls.afspraken(getAccount(), van, tot, geenUitval);
Response response = connection.get(url, this);
try
{
AfspraakList afspraken = AfspraakFactory.make(response, school, getAanmeldingen().getCurrentAanmelding());
afspraken.filterBullshitAfspraken();
return afspraken;
}
catch (ParseException e)
{
throw new BadResponseException("Fout bij het ophalen van afspraken");
}
}
public AanmeldingenList getAanmeldingen() throws IOException
{
if (aanmeldingen != null) return aanmeldingen;
loginIfNotLoggedIn();
String url = urls.aanmeldingen(getAccount());
Response response = connection.get(url, this);
try
{
return aanmeldingen = AanmeldingenList.fromResponse(response);
}
catch (ParseException | JSONException e)
{
e.printStackTrace();
throw new BadResponseException("Fout bij het ophalen van aanmeldingen");
}
}
public CijferPerioden getCijferPerioden(Aanmelding aanmelding) throws IOException
{
loginIfNotLoggedIn();
String url = urls.cijferPerioden(getAccount(), aanmelding);
Response response = connection.get(url, this);
try
{
return CijferPerioden.fromResponse(response);
}
catch (ParseException | JSONException e)
{
throw new BadResponseException("Fout bij het ophalen van de cijferperioden.");
}
}
public VakList getVakken(Aanmelding aanmelding) throws IOException
{
loginIfNotLoggedIn();
String url = urls.vakken(getAccount(), aanmelding);
Response response = connection.get(url, this);
try
{
return VakList.fromResponse(response);
}
catch (ParseException | JSONException e)
{
throw new BadResponseException("Fout bij het ophalen van de vakken");
}
}
public CijferList getCijfers(Aanmelding aanmelding, VakList vakken) throws IOException
{
loginIfNotLoggedIn();
String url = urls.cijfers(getAccount(), aanmelding);
Response response = connection.get(url, this);
try
{
return CijferList.fromResponse(response, vakken, aanmelding);
}
catch (ParseException | JSONException e)
{
e.printStackTrace();
throw new BadResponseException("Fout bij het ophalen van cijfers");
}
}
public CijferList getCijfers() throws IOException
{
Aanmelding aanmelding = getAanmeldingen().getCurrentAanmelding();
return getCijfers(aanmelding, getVakken(aanmelding));
}
public CijferList getRecentCijfers(Aanmelding aanmelding, VakList vakken) throws IOException
{
loginIfNotLoggedIn();
String url = urls.recentCijfers(getAccount(), aanmelding);
Response response = connection.get(url, this);
try
{
return CijferList.fromResponse(response, vakken, aanmelding);
}
catch (ParseException | JSONException e)
{
e.printStackTrace();
throw new BadResponseException("Fout bij het ophalen van recente cijfers.");
}
}
public Cijfer.CijferInfo getCijferInfo(Cijfer cijfer) throws IOException
{
Aanmelding aanmelding = cijfer.aanmelding;
loginIfNotLoggedIn();
String url = urls.cijferDetails(getAccount(), aanmelding, cijfer);
Response response = connection.get(url, this);
try
{
return cijfer.new CijferInfo(response);
}
catch (ParseException | JSONException e)
{
e.printStackTrace();
throw new BadResponseException("Fout bij het ophalen van cijfer gegevens");
}
}
public Cijfer attachCijferInfo(Cijfer cijfer) throws IOException
{
return attachCijferInfo(getCijferInfo(cijfer), cijfer);
}
public Cijfer attachCijferInfo(Cijfer.CijferInfo info, Cijfer cijfer)
{
cijfer.setInfo(info);
return cijfer;
}
public AfspraakList getRoosterWijzigingen(DateTime van, DateTime tot) throws IOException
{
loginIfNotLoggedIn();
String url = urls.roosterWijzigingen(getAccount(), van, tot);
Response response = connection.get(url, this);
try
{
return AfspraakFactory.make(response, school, getAanmeldingen().getCurrentAanmelding());
}
catch (ParseException | JSONException e)
{
e.printStackTrace();
throw new BadResponseException("Fout bij het ophalen van roosterwijzigingen");
}
}
}
| Magister-Android/magister-api | src/main/java/eu/magisterapp/magisterapi/Sessie.java | 2,981 | // we Nullpointers naar niet-bestaande json krijgen. | line_comment | nl | package eu.magisterapp.magisterapi;
import org.joda.time.DateTime;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.CookieManager;
import java.net.HttpCookie;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import eu.magisterapp.magisterapi.afwijkingen.ZernikeAfwijking;
/**
* Created by max on 7-12-15.
*/
public class Sessie {
public static final Integer SESSION_TIMEOUT = 60*20*1000; // 20 minuten in ms
public static final String ERROR_LOGIN = "Er is iets fout gegaan tijdens het inloggen.";
private Long loggedInAt = 0L;
private final String username;
private final String password;
private final String school;
private final Map<String, String> payload;
private String apiKeyHeader;
private String apiKey;
private MagisterConnection connection;
private final URLS urls;
private CookieManager cookies = new CookieManager();
private Account account;
private AanmeldingenList aanmeldingen;
public final String id;
public Sessie(String gebruikersnaam, String wachtwoord, String school, MagisterConnection connection)
{
this.username = gebruikersnaam;
this.password = wachtwoord;
this.school = school;
this.connection = connection;
urls = new URLS(school);
payload = new HashMap<String, String>() {{
put("Gebruikersnaam", username);
put("Wachtwoord", password);
}};
id = "un:" + gebruikersnaam + "sc:" + school;
}
public boolean loggedIn()
{
return ! isExpired() && cookies.getCookieStore().getCookies().size() > 0;
}
public synchronized void logOut()
{
cookies.getCookieStore().removeAll();
loggedInAt = 0L;
}
private boolean isExpired()
{
return loggedInAt + (SESSION_TIMEOUT - 1000) < System.currentTimeMillis();
}
public synchronized void login() throws IOException
{
cookies.getCookieStore().removeAll();
connection.delete(urls.session(), this);
Response response = connection.post(urls.login(), payload, this);
if (response.isError() && response.isJson())
{
try
{
JSONObject json;
if ((json = response.getJson()) != null)
{
throw new BadResponseException(json.getString("message"));
}
}
catch (JSONException e)
{
throw new BadResponseException(ERROR_LOGIN);
}
}
else if(! response.isJson())
{
// Als het response geen JSON is, kunnen we vrij
// weinig. Daarom boeken we 'm hier maar voordat
// we Nullpointers<SUF>
throw new BadResponseException(ERROR_LOGIN);
}
if (response.headers.get("Set-Cookie") != null && response.headers.get("Set-Cookie").size() > 0)
{
// Cookies worden op de sessie gezet door de connection.
loggedInAt = System.currentTimeMillis();
}
else
{
throw new BadResponseException(ERROR_LOGIN);
}
}
private synchronized void loginIfNotLoggedIn() throws IOException
{
if (! loggedIn()) login();
}
public String getCookies()
{
if (cookies.getCookieStore().getCookies().size() == 0)
{
return "";
}
StringBuilder builder = new StringBuilder();
for (HttpCookie cookie : cookies.getCookieStore().getCookies())
{
builder.append(cookie.toString()).append(';');
}
return builder.toString();
}
public String getApiKeyHeader() throws IOException
{
if (shouldRefresh()) refresh();
return apiKeyHeader;
}
public String getApiKey() throws IOException
{
if (shouldRefresh()) refresh();
return apiKey;
}
private boolean shouldRefresh()
{
return apiKeyHeader == null || "".equals(apiKeyHeader) || apiKey == null || "".equals(apiKey);
}
private void refresh() throws IOException
{
String body = MagisterConnection.anonymousGet(urls.base()).body;
Pattern headerPattern = Pattern.compile("apiKeyHeader: '([a-zA-Z0-9-]+)'");
Pattern keyPattern = Pattern.compile("apiKey: '([a-zA-Z0-9-]+)'");
Matcher headerMatcher = headerPattern.matcher(body);
Matcher keyMatcher = keyPattern.matcher(body);
if (headerMatcher.find()) apiKeyHeader = headerMatcher.group(1);
if (keyMatcher.find()) apiKey = keyMatcher.group(1);
}
public synchronized void storeCookies(String cookieString)
{
cookies.getCookieStore().add(null, HttpCookie.parse(cookieString).get(0));
}
public Account getAccount() throws IOException
{
if (account != null) return account;
loginIfNotLoggedIn();
try
{
return account = new Account(connection, urls.account(), this);
}
catch (ParseException | JSONException e)
{
e.printStackTrace();
throw new BadResponseException("Fout bij het ophalen van account gegevens.");
}
}
public AfspraakList getAfspraken(DateTime van, DateTime tot) throws IOException
{
return getAfspraken(van, tot, true);
}
public AfspraakList getAfspraken(DateTime van, DateTime tot, boolean geenUitval) throws IOException
{
loginIfNotLoggedIn();
String url = urls.afspraken(getAccount(), van, tot, geenUitval);
Response response = connection.get(url, this);
try
{
AfspraakList afspraken = AfspraakFactory.make(response, school, getAanmeldingen().getCurrentAanmelding());
afspraken.filterBullshitAfspraken();
return afspraken;
}
catch (ParseException e)
{
throw new BadResponseException("Fout bij het ophalen van afspraken");
}
}
public AanmeldingenList getAanmeldingen() throws IOException
{
if (aanmeldingen != null) return aanmeldingen;
loginIfNotLoggedIn();
String url = urls.aanmeldingen(getAccount());
Response response = connection.get(url, this);
try
{
return aanmeldingen = AanmeldingenList.fromResponse(response);
}
catch (ParseException | JSONException e)
{
e.printStackTrace();
throw new BadResponseException("Fout bij het ophalen van aanmeldingen");
}
}
public CijferPerioden getCijferPerioden(Aanmelding aanmelding) throws IOException
{
loginIfNotLoggedIn();
String url = urls.cijferPerioden(getAccount(), aanmelding);
Response response = connection.get(url, this);
try
{
return CijferPerioden.fromResponse(response);
}
catch (ParseException | JSONException e)
{
throw new BadResponseException("Fout bij het ophalen van de cijferperioden.");
}
}
public VakList getVakken(Aanmelding aanmelding) throws IOException
{
loginIfNotLoggedIn();
String url = urls.vakken(getAccount(), aanmelding);
Response response = connection.get(url, this);
try
{
return VakList.fromResponse(response);
}
catch (ParseException | JSONException e)
{
throw new BadResponseException("Fout bij het ophalen van de vakken");
}
}
public CijferList getCijfers(Aanmelding aanmelding, VakList vakken) throws IOException
{
loginIfNotLoggedIn();
String url = urls.cijfers(getAccount(), aanmelding);
Response response = connection.get(url, this);
try
{
return CijferList.fromResponse(response, vakken, aanmelding);
}
catch (ParseException | JSONException e)
{
e.printStackTrace();
throw new BadResponseException("Fout bij het ophalen van cijfers");
}
}
public CijferList getCijfers() throws IOException
{
Aanmelding aanmelding = getAanmeldingen().getCurrentAanmelding();
return getCijfers(aanmelding, getVakken(aanmelding));
}
public CijferList getRecentCijfers(Aanmelding aanmelding, VakList vakken) throws IOException
{
loginIfNotLoggedIn();
String url = urls.recentCijfers(getAccount(), aanmelding);
Response response = connection.get(url, this);
try
{
return CijferList.fromResponse(response, vakken, aanmelding);
}
catch (ParseException | JSONException e)
{
e.printStackTrace();
throw new BadResponseException("Fout bij het ophalen van recente cijfers.");
}
}
public Cijfer.CijferInfo getCijferInfo(Cijfer cijfer) throws IOException
{
Aanmelding aanmelding = cijfer.aanmelding;
loginIfNotLoggedIn();
String url = urls.cijferDetails(getAccount(), aanmelding, cijfer);
Response response = connection.get(url, this);
try
{
return cijfer.new CijferInfo(response);
}
catch (ParseException | JSONException e)
{
e.printStackTrace();
throw new BadResponseException("Fout bij het ophalen van cijfer gegevens");
}
}
public Cijfer attachCijferInfo(Cijfer cijfer) throws IOException
{
return attachCijferInfo(getCijferInfo(cijfer), cijfer);
}
public Cijfer attachCijferInfo(Cijfer.CijferInfo info, Cijfer cijfer)
{
cijfer.setInfo(info);
return cijfer;
}
public AfspraakList getRoosterWijzigingen(DateTime van, DateTime tot) throws IOException
{
loginIfNotLoggedIn();
String url = urls.roosterWijzigingen(getAccount(), van, tot);
Response response = connection.get(url, this);
try
{
return AfspraakFactory.make(response, school, getAanmeldingen().getCurrentAanmelding());
}
catch (ParseException | JSONException e)
{
e.printStackTrace();
throw new BadResponseException("Fout bij het ophalen van roosterwijzigingen");
}
}
}
|
206445_1 | //Je project bevat 1 Translator class met daarin een HashMap variabele, een constructor met 2
// arrays als parameter en een translate functie;
import java.util.HashMap;
import java.util.Map;
public class Translator {
private Map<Integer, String> numericAlpha = new HashMap<>();
public Translator(int[] numeric, String[] alphabetic) {
for (int i = 0; i < numeric.length; i++) {
numericAlpha.put(numeric[i], alphabetic[i]);
}
}
// geen getter nodig, want we gaan die via constructor opvragen
// geen setter nodig want we gaan de hashmap niet aanpassen, alleen er iets uit op halen
// methods
public String translate(Integer number) {
return "The translation of your number " + number + " in text is: " + numericAlpha.get(number);
}
}
| Majda-Mech/Java-Collecties-Lussen | src/Translator.java | 237 | // arrays als parameter en een translate functie; | line_comment | nl | //Je project bevat 1 Translator class met daarin een HashMap variabele, een constructor met 2
// arrays als<SUF>
import java.util.HashMap;
import java.util.Map;
public class Translator {
private Map<Integer, String> numericAlpha = new HashMap<>();
public Translator(int[] numeric, String[] alphabetic) {
for (int i = 0; i < numeric.length; i++) {
numericAlpha.put(numeric[i], alphabetic[i]);
}
}
// geen getter nodig, want we gaan die via constructor opvragen
// geen setter nodig want we gaan de hashmap niet aanpassen, alleen er iets uit op halen
// methods
public String translate(Integer number) {
return "The translation of your number " + number + " in text is: " + numericAlpha.get(number);
}
}
|
38333_3 | //import java.util.Arrays;
//import java.util.List;
//
//public class Variabelen {
// /*deze komen meerdere keren voor*/
// type; /*""*/
// List<String> attacks = Arrays.asList(/*voer de aanvallen hier in*/);
// name;/*""*/
//
// /*deze variabelen komen eenmaal voor*/
// charizard;/*🔥*/
// blastoise;/*🌊*/
// venusaur;/*🌿*/
// ditto;/*🌿*/
// raichu;/*⚡*/
// gyarados;/*🌊*/
//
// List<Pokemon> pokemons;
// int level;
// int hp;
// food;
// sound;
//
// /*deze variabele is optioneel. Je hoeft deze niet te definieren, maar als je hem definieert, dan moet je hem ook ergens gebruiken*/
// village;/*""*/
//
//} | Majda-Mech/Java-Interfaces | src/Variablen.java | 257 | // /*deze variabelen komen eenmaal voor*/ | line_comment | nl | //import java.util.Arrays;
//import java.util.List;
//
//public class Variabelen {
// /*deze komen meerdere keren voor*/
// type; /*""*/
// List<String> attacks = Arrays.asList(/*voer de aanvallen hier in*/);
// name;/*""*/
//
// /*deze variabelen<SUF>
// charizard;/*🔥*/
// blastoise;/*🌊*/
// venusaur;/*🌿*/
// ditto;/*🌿*/
// raichu;/*⚡*/
// gyarados;/*🌊*/
//
// List<Pokemon> pokemons;
// int level;
// int hp;
// food;
// sound;
//
// /*deze variabele is optioneel. Je hoeft deze niet te definieren, maar als je hem definieert, dan moet je hem ook ergens gebruiken*/
// village;/*""*/
//
//} |
38999_4 | import java.util.ArrayList;
import java.util.List;
public class ApplePieRecipe {
// geen variabelen
// wel een heleboel methodes, zie onder de constructor
// geen constructor!! als ik een constructor maak, dan herkent ie roomboter.getHoeveelheid niet meer in volgende methode
// objecten instantieren voor ingredienten
Ingredient roomboter = new Ingredient(200, "gram", "ongezouten roomboter");
Ingredient basterSuiker = new Ingredient(200, "gram", "witte basterd suiker");
Ingredient bakmeel = new Ingredient(400, "gram", "zelfrijzend bakmeel");
Ingredient ei = new Ingredient(1, "stuk(s)", "ei");
Ingredient vanillesuiker = new Ingredient(8, "gram", "vanillesuiker");
Ingredient zout = new Ingredient(1, "snuf", "zout");
Ingredient appels = new Ingredient(1500, "gram", "zoetzure appels");
Ingredient kristalSuiker = new Ingredient(75, "gram", "kristalsuiker");
Ingredient kaneel = new Ingredient(3, "theelepels", "kaneel");
Ingredient paneermeel = new Ingredient(15, "gram", "paneermeel");
//extra door gebruik te maken van een arraylist en een eenvoudiger print method
List<Ingredient> taart = new ArrayList<>();
//extra door gebruik te maken van een arraylist en een eenvoudiger print method
public ApplePieRecipe() {
taart.add(roomboter);
taart.add(basterSuiker);
taart.add(bakmeel);
taart.add(ei);
taart.add(vanillesuiker);
taart.add(zout);
taart.add(appels);
taart.add(kristalSuiker);
taart.add(kaneel);
taart.add(paneermeel);
}
//extra door gebruik te maken van een arraylist en een eenvoudiger print method
public void printingTaart() {
for (int i = 0; i < taart.size(); i++) {
System.out.println(taart.get(i).getAmount() + " " + taart.get(i).getUnit() + " " + taart.get(i).getName());
}
}
// printen ingredienten
public void printIngredients() { // roomboter blijft onbereikbaar tenzij ik de printlns hierondere in de method appelPieRecipe zet, maar dan wordt de methode weer onbereikbaar en wil intelliJ een nwe public static void method toevoegen?
// System.out.println("\nRECEPT VOOR DE HEERLIJKSTE APPELTAART");
// System.out.println("Ingredienten:");
// System.out.println(roomboter.getAmount() + " " + roomboter.getUnit() + " " + roomboter.getName());
// System.out.println(basterSuiker.getAmount() + " " + basterSuiker.getUnit() + " " + basterSuiker.getName());
// System.out.println(bakmeel.getAmount() + " " + bakmeel.getUnit() + " " + bakmeel.getName());
// System.out.println(ei.getAmount() + " " + ei.getUnit() + " " + ei.getName());
// System.out.println(vanillesuiker.getAmount() + " " + vanillesuiker.getUnit() + " " + vanillesuiker.getName());
// System.out.println(zout.getAmount() + " " + zout.getUnit() + " " + zout.getName());
// System.out.println(appels.getAmount() + " " + appels.getUnit() + " " + appels.getName());
// System.out.println(kristalSuiker.getAmount() + " " + kristalSuiker.getUnit() + " " + kristalSuiker.getName());
// System.out.println(kaneel.getAmount() + " " + kaneel.getUnit() + " " + kaneel.getName());
// System.out.println(paneermeel.getAmount() + " " + paneermeel.getUnit() + " " + paneermeel.getName());
}
public static void printAllSteps() {
ApplePieRecipe.steps();
ApplePieRecipe.warmingOven();
ApplePieRecipe.eggs();
ApplePieRecipe.mixing();
ApplePieRecipe.apples();
ApplePieRecipe.ButterSpringCakeTin();
ApplePieRecipe.doughInSpringCakeTin();
ApplePieRecipe.fillingSpringCakeTin();
ApplePieRecipe.bandsOfDough();
ApplePieRecipe.bandsOnFilling();
ApplePieRecipe.baking();
}
// printen recept in losse methods zoals omschreven
public static void steps() {
System.out.println("\nStappen:");
}
public static void warmingOven() {
System.out.println("1. Verwarm de oven van te voren op 170 graden Celsius (boven en onderwarmte)");
}
public static void eggs() {
System.out.println("2. Klop het ei los en verdeel deze in twee delen. De ene helft is voor het deeg, het andere deel is voor het bestrijken van de appeltaart.");
}
public static void mixing() {
System.out.println("3. Meng de boter, bastard suiker, zelfrijzend bakmeel, een helft van het ei, vanille suiker en een snufje zout tot een stevig deeg en verdeel deze in 3 gelijke delen.");
}
public static void apples() {
System.out.println("4. Schil nu de appels en snij deze in plakjes. Vermeng in een kopje de suiker en kaneel.");
}
public static void ButterSpringCakeTin() {
System.out.println("5. Vet de springvorm in en bestrooi deze met bloem");
}
public static void doughInSpringCakeTin() {
System.out.println("6. Gebruik een deel van het deeg om de bodem van de vorm te bedekken. Gebruik een deel van het deeg om de rand van de springvorm te bekleden. Strooi het paneermeel op de bodem van de beklede vorm. De paneermeel neemt het vocht van de appels op.");
}
public static void fillingSpringCakeTin() {
System.out.println("7. Doe de heft van de appels in de vorm en strooi hier 1/3 van het kaneel-suiker mengsel overheen. Meng de ander helft van de appels met het overgebleven kaneel-suiker mengsel en leg deze in de vorm.");
}
public static void bandsOfDough() {
System.out.println("8. Rol het laatste deel van de deeg uit tot een dunne lap en snij stroken van ongeveer 1 cm breed.");
}
public static void bandsOnFilling() {
System.out.println("9. Leg de stroken kuislings op de appeltaart. Met wat extra deegstroken werk je de rand rondom af. Gebruik het overgebleven ei om de bovenkant van het deeg te bestrijken");
}
public static void baking() {
System.out.println("10. Zet de taart iets onder het midden van de oven. Bak de taart in 60 minuten op 170 graden Celsius (boven en onderwarmte) gaar en goudbruin.");
}
} // closing class ApplePieRecipe
| Majda-Mech/Java-Objects-Classes | src/ApplePieRecipe.java | 2,052 | //extra door gebruik te maken van een arraylist en een eenvoudiger print method | line_comment | nl | import java.util.ArrayList;
import java.util.List;
public class ApplePieRecipe {
// geen variabelen
// wel een heleboel methodes, zie onder de constructor
// geen constructor!! als ik een constructor maak, dan herkent ie roomboter.getHoeveelheid niet meer in volgende methode
// objecten instantieren voor ingredienten
Ingredient roomboter = new Ingredient(200, "gram", "ongezouten roomboter");
Ingredient basterSuiker = new Ingredient(200, "gram", "witte basterd suiker");
Ingredient bakmeel = new Ingredient(400, "gram", "zelfrijzend bakmeel");
Ingredient ei = new Ingredient(1, "stuk(s)", "ei");
Ingredient vanillesuiker = new Ingredient(8, "gram", "vanillesuiker");
Ingredient zout = new Ingredient(1, "snuf", "zout");
Ingredient appels = new Ingredient(1500, "gram", "zoetzure appels");
Ingredient kristalSuiker = new Ingredient(75, "gram", "kristalsuiker");
Ingredient kaneel = new Ingredient(3, "theelepels", "kaneel");
Ingredient paneermeel = new Ingredient(15, "gram", "paneermeel");
//extra door gebruik te maken van een arraylist en een eenvoudiger print method
List<Ingredient> taart = new ArrayList<>();
//extra door<SUF>
public ApplePieRecipe() {
taart.add(roomboter);
taart.add(basterSuiker);
taart.add(bakmeel);
taart.add(ei);
taart.add(vanillesuiker);
taart.add(zout);
taart.add(appels);
taart.add(kristalSuiker);
taart.add(kaneel);
taart.add(paneermeel);
}
//extra door gebruik te maken van een arraylist en een eenvoudiger print method
public void printingTaart() {
for (int i = 0; i < taart.size(); i++) {
System.out.println(taart.get(i).getAmount() + " " + taart.get(i).getUnit() + " " + taart.get(i).getName());
}
}
// printen ingredienten
public void printIngredients() { // roomboter blijft onbereikbaar tenzij ik de printlns hierondere in de method appelPieRecipe zet, maar dan wordt de methode weer onbereikbaar en wil intelliJ een nwe public static void method toevoegen?
// System.out.println("\nRECEPT VOOR DE HEERLIJKSTE APPELTAART");
// System.out.println("Ingredienten:");
// System.out.println(roomboter.getAmount() + " " + roomboter.getUnit() + " " + roomboter.getName());
// System.out.println(basterSuiker.getAmount() + " " + basterSuiker.getUnit() + " " + basterSuiker.getName());
// System.out.println(bakmeel.getAmount() + " " + bakmeel.getUnit() + " " + bakmeel.getName());
// System.out.println(ei.getAmount() + " " + ei.getUnit() + " " + ei.getName());
// System.out.println(vanillesuiker.getAmount() + " " + vanillesuiker.getUnit() + " " + vanillesuiker.getName());
// System.out.println(zout.getAmount() + " " + zout.getUnit() + " " + zout.getName());
// System.out.println(appels.getAmount() + " " + appels.getUnit() + " " + appels.getName());
// System.out.println(kristalSuiker.getAmount() + " " + kristalSuiker.getUnit() + " " + kristalSuiker.getName());
// System.out.println(kaneel.getAmount() + " " + kaneel.getUnit() + " " + kaneel.getName());
// System.out.println(paneermeel.getAmount() + " " + paneermeel.getUnit() + " " + paneermeel.getName());
}
public static void printAllSteps() {
ApplePieRecipe.steps();
ApplePieRecipe.warmingOven();
ApplePieRecipe.eggs();
ApplePieRecipe.mixing();
ApplePieRecipe.apples();
ApplePieRecipe.ButterSpringCakeTin();
ApplePieRecipe.doughInSpringCakeTin();
ApplePieRecipe.fillingSpringCakeTin();
ApplePieRecipe.bandsOfDough();
ApplePieRecipe.bandsOnFilling();
ApplePieRecipe.baking();
}
// printen recept in losse methods zoals omschreven
public static void steps() {
System.out.println("\nStappen:");
}
public static void warmingOven() {
System.out.println("1. Verwarm de oven van te voren op 170 graden Celsius (boven en onderwarmte)");
}
public static void eggs() {
System.out.println("2. Klop het ei los en verdeel deze in twee delen. De ene helft is voor het deeg, het andere deel is voor het bestrijken van de appeltaart.");
}
public static void mixing() {
System.out.println("3. Meng de boter, bastard suiker, zelfrijzend bakmeel, een helft van het ei, vanille suiker en een snufje zout tot een stevig deeg en verdeel deze in 3 gelijke delen.");
}
public static void apples() {
System.out.println("4. Schil nu de appels en snij deze in plakjes. Vermeng in een kopje de suiker en kaneel.");
}
public static void ButterSpringCakeTin() {
System.out.println("5. Vet de springvorm in en bestrooi deze met bloem");
}
public static void doughInSpringCakeTin() {
System.out.println("6. Gebruik een deel van het deeg om de bodem van de vorm te bedekken. Gebruik een deel van het deeg om de rand van de springvorm te bekleden. Strooi het paneermeel op de bodem van de beklede vorm. De paneermeel neemt het vocht van de appels op.");
}
public static void fillingSpringCakeTin() {
System.out.println("7. Doe de heft van de appels in de vorm en strooi hier 1/3 van het kaneel-suiker mengsel overheen. Meng de ander helft van de appels met het overgebleven kaneel-suiker mengsel en leg deze in de vorm.");
}
public static void bandsOfDough() {
System.out.println("8. Rol het laatste deel van de deeg uit tot een dunne lap en snij stroken van ongeveer 1 cm breed.");
}
public static void bandsOnFilling() {
System.out.println("9. Leg de stroken kuislings op de appeltaart. Met wat extra deegstroken werk je de rand rondom af. Gebruik het overgebleven ei om de bovenkant van het deeg te bestrijken");
}
public static void baking() {
System.out.println("10. Zet de taart iets onder het midden van de oven. Bak de taart in 60 minuten op 170 graden Celsius (boven en onderwarmte) gaar en goudbruin.");
}
} // closing class ApplePieRecipe
|
162572_0 | package Src;
public class Main {
//main method in mijn main class maken!
//short cut just type main to have line below
//int is without "" string is with "eats " (bijvoorbeeld)
//initialialiseren in main
public static void main(String[] args) {
// ElectricPokemon Picka = new ElectricPokemon("fireup",1,3,"fire","fireballs","vuuuuw","kaaaboemmmm","flash flash");
// Picka.eats(" fireballs");
//// Picka.getLevel("+1");
//// Picka.setLightup(Picka.getElectricity());
WaterPokemon Chocin = new WaterPokemon ("Chocin", 5, "40", "water", "fish", "brieeey");
System.out.println( Chocin.eats());
Chocin.setSwim(Chocin.isSwim());
Chocin.speaks("brieeeuj");
}
}
| Majda-Mech/Java-Pokemon-Application | Src/Main.java | 255 | //main method in mijn main class maken! | line_comment | nl | package Src;
public class Main {
//main method<SUF>
//short cut just type main to have line below
//int is without "" string is with "eats " (bijvoorbeeld)
//initialialiseren in main
public static void main(String[] args) {
// ElectricPokemon Picka = new ElectricPokemon("fireup",1,3,"fire","fireballs","vuuuuw","kaaaboemmmm","flash flash");
// Picka.eats(" fireballs");
//// Picka.getLevel("+1");
//// Picka.setLightup(Picka.getElectricity());
WaterPokemon Chocin = new WaterPokemon ("Chocin", 5, "40", "water", "fish", "brieeey");
System.out.println( Chocin.eats());
Chocin.setSwim(Chocin.isSwim());
Chocin.speaks("brieeeuj");
}
}
|
194331_1 | package nl.novi.techiteasy1121.config;
import nl.novi.techiteasy1121.filter.JwtRequestFilter;
import nl.novi.techiteasy1121.services.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
/* Deze security is niet de enige manier om het te doen.
In de andere branch van deze github repo staat een ander voorbeeld
*/
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig {
public final CustomUserDetailsService customUserDetailsService;
private final JwtRequestFilter jwtRequestFilter;
public SpringSecurityConfig(CustomUserDetailsService customUserDetailsService, JwtRequestFilter jwtRequestFilter) {
this.customUserDetailsService = customUserDetailsService;
this.jwtRequestFilter = jwtRequestFilter;
}
// PasswordEncoderBean. Deze kun je overal in je applicatie injecteren waar nodig.
// Je kunt dit ook in een aparte configuratie klasse zetten.
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
// Authenticatie met customUserDetailsService en passwordEncoder
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
return http.getSharedObject(AuthenticationManagerBuilder.class)
.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder())
.and()
.build();
}
// Authorizatie met jwt
@Bean
protected SecurityFilterChain filter (HttpSecurity http) throws Exception {
http
.csrf().disable()
.httpBasic().disable()
.cors().and()
.authorizeHttpRequests()
// Wanneer je deze uncomments, staat je hele security open. Je hebt dan alleen nog een jwt nodig.
// .requestMatchers("/**").permitAll()
.requestMatchers(HttpMethod.POST, "/users").permitAll()
.requestMatchers(HttpMethod.GET,"/users").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST,"/users/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST, "/cimodules").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/cimodules/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST, "/remotecontrollers").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/remotecontrollers/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST, "/televisions").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/televisions/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST, "/wallbrackets").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/wallbrackets/**").hasRole("ADMIN")
// Je mag meerdere paths tegelijk definieren
.requestMatchers("/cimodules", "/remotecontrollers", "/televisions", "/wallbrackets").hasAnyRole("ADMIN", "USER")
.requestMatchers("/authenticated").authenticated()
.requestMatchers("/authenticate").permitAll()
.anyRequest().denyAll()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
} | Majda-Mech/backend-spring-boot-tech-it-easy-security-uitwerkingen | src/main/java/nl/novi/techiteasy1121/config/SpringSecurityConfig.java | 1,140 | // PasswordEncoderBean. Deze kun je overal in je applicatie injecteren waar nodig. | line_comment | nl | package nl.novi.techiteasy1121.config;
import nl.novi.techiteasy1121.filter.JwtRequestFilter;
import nl.novi.techiteasy1121.services.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
/* Deze security is niet de enige manier om het te doen.
In de andere branch van deze github repo staat een ander voorbeeld
*/
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig {
public final CustomUserDetailsService customUserDetailsService;
private final JwtRequestFilter jwtRequestFilter;
public SpringSecurityConfig(CustomUserDetailsService customUserDetailsService, JwtRequestFilter jwtRequestFilter) {
this.customUserDetailsService = customUserDetailsService;
this.jwtRequestFilter = jwtRequestFilter;
}
// PasswordEncoderBean. Deze<SUF>
// Je kunt dit ook in een aparte configuratie klasse zetten.
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
// Authenticatie met customUserDetailsService en passwordEncoder
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
return http.getSharedObject(AuthenticationManagerBuilder.class)
.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder())
.and()
.build();
}
// Authorizatie met jwt
@Bean
protected SecurityFilterChain filter (HttpSecurity http) throws Exception {
http
.csrf().disable()
.httpBasic().disable()
.cors().and()
.authorizeHttpRequests()
// Wanneer je deze uncomments, staat je hele security open. Je hebt dan alleen nog een jwt nodig.
// .requestMatchers("/**").permitAll()
.requestMatchers(HttpMethod.POST, "/users").permitAll()
.requestMatchers(HttpMethod.GET,"/users").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST,"/users/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST, "/cimodules").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/cimodules/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST, "/remotecontrollers").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/remotecontrollers/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST, "/televisions").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/televisions/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST, "/wallbrackets").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/wallbrackets/**").hasRole("ADMIN")
// Je mag meerdere paths tegelijk definieren
.requestMatchers("/cimodules", "/remotecontrollers", "/televisions", "/wallbrackets").hasAnyRole("ADMIN", "USER")
.requestMatchers("/authenticated").authenticated()
.requestMatchers("/authenticate").permitAll()
.anyRequest().denyAll()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
} |
129159_15 | package nl.makertim.bikemod;
import java.util.List;
import javax.annotation.Nullable;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityBoat;
import net.minecraft.entity.passive.EntityAnimal;
import net.minecraft.entity.passive.EntityWaterMob;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.datasync.DataParameter;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraft.network.datasync.EntityDataManager;
import net.minecraft.network.play.client.CPacketSteerBoat;
import net.minecraft.network.play.client.CPacketVehicleMove;
import net.minecraft.util.*;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class BikeEntity extends Entity {
private static final DataParameter<Integer> TIME_SINCE_HIT = EntityDataManager.createKey(EntityBoat.class,
DataSerializers.VARINT);
private static final DataParameter<Integer> FORWARD_DIRECTION = EntityDataManager.createKey(EntityBoat.class,
DataSerializers.VARINT);
private static final DataParameter<Float> DAMAGE_TAKEN = EntityDataManager.createKey(EntityBoat.class,
DataSerializers.FLOAT);
private float prefMotion;
private boolean forwardInputDown;
private boolean backInputDown;
public BikeEntity(World worldIn) {
super(worldIn);
this.preventEntitySpawning = true;
this.setSize(1, 1);
}
public BikeEntity(World worldIn, double x, double y, double z) {
this(worldIn);
this.setPosition(x, y, z);
this.motionX = 0.0D;
this.motionY = 0.0D;
this.motionZ = 0.0D;
this.prevPosX = x;
this.prevPosY = y;
this.prevPosZ = z;
}
/**
* returns if this entity triggers Block.onEntityWalking on the blocks they
* walk on. used for spiders and wolves to prevent them from trampling crops
*/
protected boolean canTriggerWalking() {
return false;
}
protected void entityInit() {
this.dataManager.register(TIME_SINCE_HIT, 0);
this.dataManager.register(FORWARD_DIRECTION, 1);
this.dataManager.register(DAMAGE_TAKEN, 0F);
}
/**
* Returns a boundingBox used to collide the entity with other entities and
* blocks. This enables the entity to be pushable on contact, like boats or
* minecarts.
*/
public AxisAlignedBB getCollisionBox(Entity entityIn) {
return entityIn.getEntityBoundingBox();
}
/**
* Returns the collision bounding box for this entity
*/
public AxisAlignedBB getCollisionBoundingBox() {
return this.getEntityBoundingBox();
}
/**
* Returns true if this entity should push and be pushed by other entities
* when colliding.
*/
public boolean canBePushed() {
return false;
}
/**
* Returns the Y offset from the entity's position for any entity riding
* this one.
*/
public double getMountedYOffset() {
return 0.55D;
}
/**
* Called when the entity is attacked.
*/
public boolean attackEntityFrom(DamageSource source, float amount) {
if (this.isEntityInvulnerable(source)) {
return false;
} else if (!this.worldObj.isRemote && !this.isDead) {
if (source instanceof EntityDamageSourceIndirect && source.getEntity() != null
&& this.isPassenger(source.getEntity())) {
return false;
} else {
this.setForwardDirection(-this.getForwardDirection());
this.setTimeSinceHit(10);
this.setDamageTaken(this.getDamageTaken() + amount * 10.0F);
this.setBeenAttacked();
boolean flag = source.getEntity() instanceof EntityPlayer
&& ((EntityPlayer) source.getEntity()).capabilities.isCreativeMode;
if (flag || this.getDamageTaken() > 40.0F) {
if (!flag && this.worldObj.getGameRules().getBoolean("doEntityDrops")) {
this.dropItemWithOffset(Bikes.item, 1, 0.0F);
}
this.setDead();
}
return true;
}
} else {
return true;
}
}
/**
* Applies a velocity to the entities, to push them away from eachother.
*/
public void applyEntityCollision(Entity entityIn) {
if (entityIn instanceof BikeEntity) {
if (prefMotion > 1) {
this.setDead();
} else if (entityIn.getEntityBoundingBox().minY < this.getEntityBoundingBox().maxY) {
super.applyEntityCollision(entityIn);
}
} else if (entityIn.getEntityBoundingBox().minY <= this.getEntityBoundingBox().minY) {
super.applyEntityCollision(entityIn);
}
}
/**
* Setups the entity to do the hurt animation. Only used by packets in
* multiplayer.
*/
@SideOnly(Side.CLIENT)
public void performHurtAnimation() {
this.setForwardDirection(-this.getForwardDirection());
this.rotationYaw += (Math.random() * 10) - 5;
this.setTimeSinceHit(10);
this.setDamageTaken(this.getDamageTaken() * 11.0F);
}
/**
* Returns true if other Entities should be prevented from moving through
* this Entity.
*/
public boolean canBeCollidedWith() {
return !this.isDead;
}
/*
* Gets the horizontal facing direction of this Entity, adjusted to take
* specially-treated entity types into account.
*/
@Override
public EnumFacing getAdjustedHorizontalFacing() {
return this.getHorizontalFacing().rotateY();
}
/**
* Called to update the entity's position/logic.
*/
public void onUpdate() {
if (this.getTimeSinceHit() > 0) {
this.setTimeSinceHit(this.getTimeSinceHit() - 1);
}
if (this.getDamageTaken() > 0.0F) {
this.setDamageTaken(this.getDamageTaken() - 1.0F);
}
this.prevPosX = this.posX;
this.prevPosY = this.posY;
this.prevPosZ = this.posZ;
super.onUpdate();
this.updateMotion();
if (this.worldObj.isRemote) {
this.controlBoat();
this.worldObj.sendPacketToServer(new CPacketVehicleMove(this));
}
this.moveEntity(this.motionX, this.motionY, this.motionZ);
this.doBlockCollisions();
List<Entity> list = this.worldObj.getEntitiesInAABBexcluding(this,
this.getEntityBoundingBox().expand(0.2D, -0.01D, 0.2D), EntitySelectors.getTeamCollisionPredicate(this));
if (!list.isEmpty()) {
boolean flag = !this.worldObj.isRemote && !(this.getControllingPassenger() instanceof EntityPlayer);
for (Entity entity : list) {
if (!entity.isPassenger(this)) {
if (flag && this.getPassengers().size() < 2 && !entity.isRiding() && entity.width < this.width
&& entity instanceof EntityLivingBase && !(entity instanceof EntityWaterMob)
&& !(entity instanceof EntityPlayer)) {
entity.startRiding(this);
} else {
this.applyEntityCollision(entity);
}
}
}
}
}
/**
* Update the boat's speed, based on momentum.
*/
private void updateMotion() {
double d1 = this.func_189652_ae() ? 0.0D : -0.04D;
/* How much of current speed to retain. Value zero to one. */
float momentum = 0.9F;
this.motionX *= (double) momentum;
this.motionZ *= (double) momentum;
this.motionY += d1;
}
private void controlBoat() {
float f = (float) Math.pow(prefMotion, 2) / 1.5F;
if (this.isBeingRidden()) {
if (this.forwardInputDown) {
f += 0.075F;
}
if (this.backInputDown) {
f -= 0.075F;
}
if (!getPassengers().isEmpty()) {
Entity rider = getPassengers().get(0);
float riderYaw = rider.rotationYaw % 360;
if (Math.round(rotationYaw) != Math.round(riderYaw)) {
// TODO: Fix als je roteerd = sliprem
// TODO: Fix draaien
// TODO: hoe groter bocht = meer remmen
updateMotion();
System.out.printf("%f != %f\n", rotationYaw, riderYaw);
float yawDiff = rotationYaw - riderYaw;
float max = 50;
yawDiff = MathHelper.clamp_float(yawDiff, Math.min(-1F, -1F * f * max), Math.max(1F, 1F * f * max))
* (Math.abs(yawDiff) / 12);
if (yawDiff > max && !(yawDiff > max - 360)) {
yawDiff = rotationYaw - riderYaw;
}
prevRotationYaw = rotationYaw;
rotationYaw -= yawDiff;
rotationYaw %= 360;
}
}
if (f < 0) {
f = 0;
}
this.motionX += (double) (MathHelper.sin(-this.rotationYaw * 0.0175F) * f);
this.motionZ += (double) (MathHelper.cos(this.rotationYaw * 0.0175F) * f);
this.prefMotion = f;
} else {
f /= 3;
}
if (f > 2.5F) {
f = 2.5F;
}
this.motionX += (double) (MathHelper.sin(-this.rotationYaw * 0.0175F) * f);
this.motionZ += (double) (MathHelper.cos(this.rotationYaw * 0.0175F) * f);
this.prefMotion = f;
}
public void updatePassenger(Entity passenger) {
if (this.isPassenger(passenger)) {
float f = 0.0F;
float f1 = (float) ((this.isDead ? 0.001D : this.getMountedYOffset()) + passenger.getYOffset());
Vec3d vec3d = (new Vec3d((double) f, 0.0D, 0.0D))
.rotateYaw(-this.rotationYaw * 0.0175F - ((float) Math.PI / 2F));
passenger.setPosition(this.posX + vec3d.xCoord, this.posY + (double) f1, this.posZ + vec3d.zCoord);
this.applyYawToEntity(passenger);
if (passenger instanceof EntityAnimal && this.getPassengers().size() > 1) {
int j = passenger.getEntityId() % 2 == 0 ? 90 : 270;
passenger.setRenderYawOffset(((EntityAnimal) passenger).renderYawOffset + (float) j);
passenger.setRotationYawHead(passenger.getRotationYawHead() + (float) j);
}
}
}
/**
* Applies this boat's yaw to the given entity. Used to update the
* orientation of its passenger.
*/
protected void applyYawToEntity(Entity entityToUpdate) {
entityToUpdate.setRenderYawOffset(this.rotationYaw);
float f = MathHelper.wrapDegrees(entityToUpdate.rotationYaw - this.rotationYaw);
float f1 = MathHelper.clamp_float(f, -60.0F, 60.0F);
entityToUpdate.prevRotationYaw += f1 - f;
entityToUpdate.rotationYaw += f1 - f;
entityToUpdate.setRotationYawHead(entityToUpdate.rotationYaw);
}
/**
* Applies this entity's orientation (pitch/yaw) to another entity. Used to
* update passenger orientation.
*/
@SideOnly(Side.CLIENT)
public void applyOrientationToEntity(Entity entityToUpdate) {
this.applyYawToEntity(entityToUpdate);
}
protected void writeEntityToNBT(NBTTagCompound compound) {
}
protected void readEntityFromNBT(NBTTagCompound compound) {
}
public boolean processInitialInteract(EntityPlayer player, @Nullable ItemStack stack, EnumHand hand) {
if (!this.worldObj.isRemote && !player.isSneaking()) {
player.startRiding(this);
}
return true;
}
/**
* Sets the damage taken from the last hit.
*/
public void setDamageTaken(float damageTaken) {
this.dataManager.set(DAMAGE_TAKEN, damageTaken);
}
/**
* Gets the damage taken from the last hit.
*/
public float getDamageTaken() {
return this.dataManager.get(DAMAGE_TAKEN);
}
/**
* Sets the time to count down from since the last time entity was hit.
*/
public void setTimeSinceHit(int timeSinceHit) {
this.dataManager.set(TIME_SINCE_HIT, timeSinceHit);
}
/**
* Gets the time since the last hit.
*/
public int getTimeSinceHit() {
return this.dataManager.get(TIME_SINCE_HIT);
}
/**
* Sets the forward direction of the entity.
*/
public void setForwardDirection(int forwardDirection) {
this.dataManager.set(FORWARD_DIRECTION, forwardDirection);
}
/**
* Gets the forward direction of the entity.
*/
public int getForwardDirection() {
return this.dataManager.get(FORWARD_DIRECTION);
}
protected boolean canFitPassenger(Entity passenger) {
return this.getPassengers().size() < 2;
}
/**
* For vehicles, the first passenger is generally considered the controller
* and "drives" the vehicle. For example, Pigs, Horses, and Boats are
* generally "steered" by the controlling passenger.
*/
@Nullable
public Entity getControllingPassenger() {
List<Entity> list = this.getPassengers();
return list.isEmpty() ? null : list.get(0);
}
public void updateForward(boolean key) {
this.forwardInputDown = key;
}
public void updateBrake(boolean key) {
this.backInputDown = key;
}
}
| MakerTim/BikeMod | src/main/java/nl/makertim/bikemod/BikeEntity.java | 4,249 | // TODO: hoe groter bocht = meer remmen | line_comment | nl | package nl.makertim.bikemod;
import java.util.List;
import javax.annotation.Nullable;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityBoat;
import net.minecraft.entity.passive.EntityAnimal;
import net.minecraft.entity.passive.EntityWaterMob;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.datasync.DataParameter;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraft.network.datasync.EntityDataManager;
import net.minecraft.network.play.client.CPacketSteerBoat;
import net.minecraft.network.play.client.CPacketVehicleMove;
import net.minecraft.util.*;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class BikeEntity extends Entity {
private static final DataParameter<Integer> TIME_SINCE_HIT = EntityDataManager.createKey(EntityBoat.class,
DataSerializers.VARINT);
private static final DataParameter<Integer> FORWARD_DIRECTION = EntityDataManager.createKey(EntityBoat.class,
DataSerializers.VARINT);
private static final DataParameter<Float> DAMAGE_TAKEN = EntityDataManager.createKey(EntityBoat.class,
DataSerializers.FLOAT);
private float prefMotion;
private boolean forwardInputDown;
private boolean backInputDown;
public BikeEntity(World worldIn) {
super(worldIn);
this.preventEntitySpawning = true;
this.setSize(1, 1);
}
public BikeEntity(World worldIn, double x, double y, double z) {
this(worldIn);
this.setPosition(x, y, z);
this.motionX = 0.0D;
this.motionY = 0.0D;
this.motionZ = 0.0D;
this.prevPosX = x;
this.prevPosY = y;
this.prevPosZ = z;
}
/**
* returns if this entity triggers Block.onEntityWalking on the blocks they
* walk on. used for spiders and wolves to prevent them from trampling crops
*/
protected boolean canTriggerWalking() {
return false;
}
protected void entityInit() {
this.dataManager.register(TIME_SINCE_HIT, 0);
this.dataManager.register(FORWARD_DIRECTION, 1);
this.dataManager.register(DAMAGE_TAKEN, 0F);
}
/**
* Returns a boundingBox used to collide the entity with other entities and
* blocks. This enables the entity to be pushable on contact, like boats or
* minecarts.
*/
public AxisAlignedBB getCollisionBox(Entity entityIn) {
return entityIn.getEntityBoundingBox();
}
/**
* Returns the collision bounding box for this entity
*/
public AxisAlignedBB getCollisionBoundingBox() {
return this.getEntityBoundingBox();
}
/**
* Returns true if this entity should push and be pushed by other entities
* when colliding.
*/
public boolean canBePushed() {
return false;
}
/**
* Returns the Y offset from the entity's position for any entity riding
* this one.
*/
public double getMountedYOffset() {
return 0.55D;
}
/**
* Called when the entity is attacked.
*/
public boolean attackEntityFrom(DamageSource source, float amount) {
if (this.isEntityInvulnerable(source)) {
return false;
} else if (!this.worldObj.isRemote && !this.isDead) {
if (source instanceof EntityDamageSourceIndirect && source.getEntity() != null
&& this.isPassenger(source.getEntity())) {
return false;
} else {
this.setForwardDirection(-this.getForwardDirection());
this.setTimeSinceHit(10);
this.setDamageTaken(this.getDamageTaken() + amount * 10.0F);
this.setBeenAttacked();
boolean flag = source.getEntity() instanceof EntityPlayer
&& ((EntityPlayer) source.getEntity()).capabilities.isCreativeMode;
if (flag || this.getDamageTaken() > 40.0F) {
if (!flag && this.worldObj.getGameRules().getBoolean("doEntityDrops")) {
this.dropItemWithOffset(Bikes.item, 1, 0.0F);
}
this.setDead();
}
return true;
}
} else {
return true;
}
}
/**
* Applies a velocity to the entities, to push them away from eachother.
*/
public void applyEntityCollision(Entity entityIn) {
if (entityIn instanceof BikeEntity) {
if (prefMotion > 1) {
this.setDead();
} else if (entityIn.getEntityBoundingBox().minY < this.getEntityBoundingBox().maxY) {
super.applyEntityCollision(entityIn);
}
} else if (entityIn.getEntityBoundingBox().minY <= this.getEntityBoundingBox().minY) {
super.applyEntityCollision(entityIn);
}
}
/**
* Setups the entity to do the hurt animation. Only used by packets in
* multiplayer.
*/
@SideOnly(Side.CLIENT)
public void performHurtAnimation() {
this.setForwardDirection(-this.getForwardDirection());
this.rotationYaw += (Math.random() * 10) - 5;
this.setTimeSinceHit(10);
this.setDamageTaken(this.getDamageTaken() * 11.0F);
}
/**
* Returns true if other Entities should be prevented from moving through
* this Entity.
*/
public boolean canBeCollidedWith() {
return !this.isDead;
}
/*
* Gets the horizontal facing direction of this Entity, adjusted to take
* specially-treated entity types into account.
*/
@Override
public EnumFacing getAdjustedHorizontalFacing() {
return this.getHorizontalFacing().rotateY();
}
/**
* Called to update the entity's position/logic.
*/
public void onUpdate() {
if (this.getTimeSinceHit() > 0) {
this.setTimeSinceHit(this.getTimeSinceHit() - 1);
}
if (this.getDamageTaken() > 0.0F) {
this.setDamageTaken(this.getDamageTaken() - 1.0F);
}
this.prevPosX = this.posX;
this.prevPosY = this.posY;
this.prevPosZ = this.posZ;
super.onUpdate();
this.updateMotion();
if (this.worldObj.isRemote) {
this.controlBoat();
this.worldObj.sendPacketToServer(new CPacketVehicleMove(this));
}
this.moveEntity(this.motionX, this.motionY, this.motionZ);
this.doBlockCollisions();
List<Entity> list = this.worldObj.getEntitiesInAABBexcluding(this,
this.getEntityBoundingBox().expand(0.2D, -0.01D, 0.2D), EntitySelectors.getTeamCollisionPredicate(this));
if (!list.isEmpty()) {
boolean flag = !this.worldObj.isRemote && !(this.getControllingPassenger() instanceof EntityPlayer);
for (Entity entity : list) {
if (!entity.isPassenger(this)) {
if (flag && this.getPassengers().size() < 2 && !entity.isRiding() && entity.width < this.width
&& entity instanceof EntityLivingBase && !(entity instanceof EntityWaterMob)
&& !(entity instanceof EntityPlayer)) {
entity.startRiding(this);
} else {
this.applyEntityCollision(entity);
}
}
}
}
}
/**
* Update the boat's speed, based on momentum.
*/
private void updateMotion() {
double d1 = this.func_189652_ae() ? 0.0D : -0.04D;
/* How much of current speed to retain. Value zero to one. */
float momentum = 0.9F;
this.motionX *= (double) momentum;
this.motionZ *= (double) momentum;
this.motionY += d1;
}
private void controlBoat() {
float f = (float) Math.pow(prefMotion, 2) / 1.5F;
if (this.isBeingRidden()) {
if (this.forwardInputDown) {
f += 0.075F;
}
if (this.backInputDown) {
f -= 0.075F;
}
if (!getPassengers().isEmpty()) {
Entity rider = getPassengers().get(0);
float riderYaw = rider.rotationYaw % 360;
if (Math.round(rotationYaw) != Math.round(riderYaw)) {
// TODO: Fix als je roteerd = sliprem
// TODO: Fix draaien
// TODO: hoe<SUF>
updateMotion();
System.out.printf("%f != %f\n", rotationYaw, riderYaw);
float yawDiff = rotationYaw - riderYaw;
float max = 50;
yawDiff = MathHelper.clamp_float(yawDiff, Math.min(-1F, -1F * f * max), Math.max(1F, 1F * f * max))
* (Math.abs(yawDiff) / 12);
if (yawDiff > max && !(yawDiff > max - 360)) {
yawDiff = rotationYaw - riderYaw;
}
prevRotationYaw = rotationYaw;
rotationYaw -= yawDiff;
rotationYaw %= 360;
}
}
if (f < 0) {
f = 0;
}
this.motionX += (double) (MathHelper.sin(-this.rotationYaw * 0.0175F) * f);
this.motionZ += (double) (MathHelper.cos(this.rotationYaw * 0.0175F) * f);
this.prefMotion = f;
} else {
f /= 3;
}
if (f > 2.5F) {
f = 2.5F;
}
this.motionX += (double) (MathHelper.sin(-this.rotationYaw * 0.0175F) * f);
this.motionZ += (double) (MathHelper.cos(this.rotationYaw * 0.0175F) * f);
this.prefMotion = f;
}
public void updatePassenger(Entity passenger) {
if (this.isPassenger(passenger)) {
float f = 0.0F;
float f1 = (float) ((this.isDead ? 0.001D : this.getMountedYOffset()) + passenger.getYOffset());
Vec3d vec3d = (new Vec3d((double) f, 0.0D, 0.0D))
.rotateYaw(-this.rotationYaw * 0.0175F - ((float) Math.PI / 2F));
passenger.setPosition(this.posX + vec3d.xCoord, this.posY + (double) f1, this.posZ + vec3d.zCoord);
this.applyYawToEntity(passenger);
if (passenger instanceof EntityAnimal && this.getPassengers().size() > 1) {
int j = passenger.getEntityId() % 2 == 0 ? 90 : 270;
passenger.setRenderYawOffset(((EntityAnimal) passenger).renderYawOffset + (float) j);
passenger.setRotationYawHead(passenger.getRotationYawHead() + (float) j);
}
}
}
/**
* Applies this boat's yaw to the given entity. Used to update the
* orientation of its passenger.
*/
protected void applyYawToEntity(Entity entityToUpdate) {
entityToUpdate.setRenderYawOffset(this.rotationYaw);
float f = MathHelper.wrapDegrees(entityToUpdate.rotationYaw - this.rotationYaw);
float f1 = MathHelper.clamp_float(f, -60.0F, 60.0F);
entityToUpdate.prevRotationYaw += f1 - f;
entityToUpdate.rotationYaw += f1 - f;
entityToUpdate.setRotationYawHead(entityToUpdate.rotationYaw);
}
/**
* Applies this entity's orientation (pitch/yaw) to another entity. Used to
* update passenger orientation.
*/
@SideOnly(Side.CLIENT)
public void applyOrientationToEntity(Entity entityToUpdate) {
this.applyYawToEntity(entityToUpdate);
}
protected void writeEntityToNBT(NBTTagCompound compound) {
}
protected void readEntityFromNBT(NBTTagCompound compound) {
}
public boolean processInitialInteract(EntityPlayer player, @Nullable ItemStack stack, EnumHand hand) {
if (!this.worldObj.isRemote && !player.isSneaking()) {
player.startRiding(this);
}
return true;
}
/**
* Sets the damage taken from the last hit.
*/
public void setDamageTaken(float damageTaken) {
this.dataManager.set(DAMAGE_TAKEN, damageTaken);
}
/**
* Gets the damage taken from the last hit.
*/
public float getDamageTaken() {
return this.dataManager.get(DAMAGE_TAKEN);
}
/**
* Sets the time to count down from since the last time entity was hit.
*/
public void setTimeSinceHit(int timeSinceHit) {
this.dataManager.set(TIME_SINCE_HIT, timeSinceHit);
}
/**
* Gets the time since the last hit.
*/
public int getTimeSinceHit() {
return this.dataManager.get(TIME_SINCE_HIT);
}
/**
* Sets the forward direction of the entity.
*/
public void setForwardDirection(int forwardDirection) {
this.dataManager.set(FORWARD_DIRECTION, forwardDirection);
}
/**
* Gets the forward direction of the entity.
*/
public int getForwardDirection() {
return this.dataManager.get(FORWARD_DIRECTION);
}
protected boolean canFitPassenger(Entity passenger) {
return this.getPassengers().size() < 2;
}
/**
* For vehicles, the first passenger is generally considered the controller
* and "drives" the vehicle. For example, Pigs, Horses, and Boats are
* generally "steered" by the controlling passenger.
*/
@Nullable
public Entity getControllingPassenger() {
List<Entity> list = this.getPassengers();
return list.isEmpty() ? null : list.get(0);
}
public void updateForward(boolean key) {
this.forwardInputDown = key;
}
public void updateBrake(boolean key) {
this.backInputDown = key;
}
}
|
205498_20 | package nl.groep4.kvc.server;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import nl.groep4.kvc.common.enumeration.Color;
import nl.groep4.kvc.common.enumeration.Direction;
import nl.groep4.kvc.common.enumeration.Point;
import nl.groep4.kvc.common.map.Coordinate;
import nl.groep4.kvc.common.map.Map;
import nl.groep4.kvc.common.map.Street;
import nl.groep4.kvc.common.map.Tile;
import nl.groep4.kvc.common.map.TileLand;
import nl.groep4.kvc.common.map.TileType;
import nl.groep4.kvc.server.model.ServerPlayer;
import nl.groep4.kvc.server.model.map.ServerMap;
public class MapTester {
private Map map;
@Before
public void build() {
map = new ServerMap();
map.createMap();
}
@Test
public void testRelativeTile() {
Tile tile = map.getTile(new Coordinate(0, 0));
Tile foundTile;
foundTile = map.getRelativeTile(tile, Direction.NORTH);
assertEquals(new Coordinate(0, -1), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH);
assertEquals(new Coordinate(0, 1), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_EAST);
assertEquals(new Coordinate(1, 1), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_WEST);
assertEquals(new Coordinate(-1, 1), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_EAST);
assertEquals(new Coordinate(1, 0), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_WEST);
assertEquals(new Coordinate(-1, 0), foundTile.getPosition());
tile = map.getTile(new Coordinate(0, 2));
foundTile = map.getRelativeTile(tile, Direction.NORTH);
assertEquals(new Coordinate(0, 1), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH);
assertEquals(new Coordinate(0, 3), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_EAST);
assertEquals(new Coordinate(1, 3), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_WEST);
assertEquals(new Coordinate(-1, 3), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_EAST);
assertEquals(new Coordinate(1, 2), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_WEST);
assertEquals(new Coordinate(-1, 2), foundTile.getPosition());
tile = map.getTile(new Coordinate(-2, -1));
foundTile = map.getRelativeTile(tile, Direction.NORTH);
assertEquals(new Coordinate(-2, -2), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH);
assertEquals(new Coordinate(-2, 0), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_EAST);
assertEquals(new Coordinate(-1, 0), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_WEST);
assertEquals(new Coordinate(-3, 0), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_EAST);
assertEquals(new Coordinate(-1, -1), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_WEST);
assertEquals(new Coordinate(-3, -1), foundTile.getPosition());
tile = map.getTile(new Coordinate(0, -4));
assertNotNull(foundTile);
foundTile = map.getRelativeTile(tile, Direction.NORTH);
assertNull(null);
foundTile = map.getRelativeTile(tile, Direction.SOUTH);
assertEquals(new Coordinate(0, -3), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_EAST);
assertEquals(new Coordinate(1, -3), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_WEST);
assertEquals(new Coordinate(-1, -3), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_EAST);
assertNull(null);
foundTile = map.getRelativeTile(tile, Direction.NORTH_WEST);
assertNull(null);
// Kijken of daadwerkelijk een tegel naast de ander zit
// map.getRelativeTile(tile, direction)
}
@Test
public void testTilesCreated() {
int counterFOREST = 0;
int counterMESA = 0;
int counterPLAINS = 0;
int counterMOUNTAIN = 0;
int counterWHEAT = 0;
int counterDESERT = 0;
int counterWATER = 0;
List<Tile> tiles = map.getTiles();
for (int i = 0; i < tiles.size(); i++) {
Tile tile = tiles.get(i);
tile.getType();
switch (tile.getType()) {
case FOREST:
counterFOREST++;
break;
case MESA:
counterMESA++;
break;
case PLAINS:
counterPLAINS++;
break;
case MOUNTAIN:
counterMOUNTAIN++;
break;
case WHEAT:
counterWHEAT++;
break;
case DESERT:
counterDESERT++;
break;
case WATER:
case WATER_TRADE:
case WATER_OPEN_TRADE:
counterWATER++;
break;
default:
break;
}
}
assertEquals(6, counterFOREST);
assertEquals(5, counterMESA);
assertEquals(6, counterPLAINS);
assertEquals(5, counterMOUNTAIN);
assertEquals(6, counterWHEAT);
assertEquals(2, counterDESERT);
assertEquals(22, counterWATER);
Tile tile = map.getTile(0, -4);
assertEquals(TileType.WATER, tile.getType());
Tile tile2 = map.getTile(1, -3);
assertEquals(TileType.WATER, tile2.getType());
Tile tile3 = map.getTile(2, -3);
assertEquals(TileType.WATER, tile3.getType());
Tile tile4 = map.getTile(3, -2);
assertEquals(TileType.WATER, tile4.getType());
Tile tile5 = map.getTile(4, -2);
assertEquals(TileType.WATER, tile5.getType());
Tile tile6 = map.getTile(4, -1);
assertEquals(TileType.WATER, tile6.getType());
Tile tile7 = map.getTile(4, 0);
assertEquals(TileType.WATER, tile7.getType());
Tile tile8 = map.getTile(4, 1);
assertEquals(TileType.WATER, tile8.getType());
Tile tile9 = map.getTile(3, 2);
assertEquals(TileType.WATER, tile9.getType());
Tile tile10 = map.getTile(2, 2);
assertEquals(TileType.WATER, tile10.getType());
Tile tile11 = map.getTile(1, 3);
assertEquals(TileType.WATER, tile11.getType());
Tile tile12 = map.getTile(0, 3);
assertEquals(TileType.WATER, tile12.getType());
Tile tile13 = map.getTile(-1, 3);
assertEquals(TileType.WATER, tile13.getType());
Tile tile14 = map.getTile(-2, 2);
assertEquals(TileType.WATER, tile14.getType());
Tile tile15 = map.getTile(-3, 2);
assertEquals(TileType.WATER, tile15.getType());
Tile tile16 = map.getTile(-4, 1);
assertEquals(TileType.WATER, tile16.getType());
Tile tile17 = map.getTile(-4, 0);
assertEquals(TileType.WATER, tile17.getType());
Tile tile18 = map.getTile(-4, -1);
assertEquals(TileType.WATER, tile18.getType());
Tile tile19 = map.getTile(-4, -2);
assertEquals(TileType.WATER, tile19.getType());
Tile tile20 = map.getTile(-3, -2);
assertEquals(TileType.WATER, tile20.getType());
Tile tile21 = map.getTile(-2, -3);
assertEquals(TileType.WATER, tile21.getType());
Tile tile22 = map.getTile(-1, -3);
assertEquals(TileType.WATER, tile22.getType());
}
// map.getTiles() #
// kijken of de desert op goede plek staat MOET NOG GEFIXED WORDEN WACHT OP
// TIM!
// kijken of er 6forest,6...,6... 5mesa, 5mountain #
// kijken of buitenrand helemaal uit water bestaat #
@Test
public void correctStreets() {
// alle relatieve tiles van de evengetalcentrale tile
Tile landtileNorth = map.getTile(new Coordinate(0, -3));
Tile landtileSouth = map.getTile(new Coordinate(0, -1));
Tile landtileCenter = map.getTile(new Coordinate(0, -2));
Tile landtileNE = map.getTile(new Coordinate(1, -2));
Tile landtileNW = map.getTile(new Coordinate(-1, -2));
Tile landtileSE = map.getTile(new Coordinate(1, -1));
Tile landtileSW = map.getTile(new Coordinate(-1, -1));
// Tile testTile = map.getTile(new Coordinate(0, -3));
// assertNotNull(testTile.getStreet(Direction.NORTH));
// de verschillende tiles met elkaar vergelijken
assertNotNull(landtileCenter.getStreet(Direction.NORTH));
assertNotNull(landtileCenter.getStreet(Direction.NORTH_EAST));
assertNotNull(landtileCenter.getStreet(Direction.NORTH_WEST));
assertNotNull(landtileCenter.getStreet(Direction.SOUTH));
assertNotNull(landtileCenter.getStreet(Direction.SOUTH_EAST));
assertNotNull(landtileCenter.getStreet(Direction.SOUTH_WEST));
assertEquals(landtileNorth.getStreet(Direction.SOUTH), landtileCenter.getStreet(Direction.NORTH));
// evengetal tiles hier getest
assertEquals(landtileNE.getStreet(Direction.SOUTH_WEST), landtileCenter.getStreet(Direction.NORTH_EAST));
assertEquals(landtileNW.getStreet(Direction.SOUTH_EAST), landtileCenter.getStreet(Direction.NORTH_WEST));
assertEquals(landtileSE.getStreet(Direction.NORTH_WEST), landtileCenter.getStreet(Direction.SOUTH_EAST));
assertEquals(landtileSW.getStreet(Direction.NORTH_EAST), landtileCenter.getStreet(Direction.SOUTH_WEST));
assertEquals(landtileSouth.getStreet(Direction.NORTH), landtileCenter.getStreet(Direction.SOUTH));
landtileNorth = map.getTile(new Coordinate(-1, -2));
landtileSouth = map.getTile(new Coordinate(-1, 0));
landtileCenter = map.getTile(new Coordinate(-1, -1));
landtileNE = map.getTile(new Coordinate(0, -2));
landtileNW = map.getTile(new Coordinate(-2, -2));
landtileSE = map.getTile(new Coordinate(0, -1));
landtileSW = map.getTile(new Coordinate(-2, -1));
// niet evengetal tiles worden hier getest
assertEquals(landtileNE.getStreet(Direction.SOUTH_WEST), landtileCenter.getStreet(Direction.NORTH_EAST));
assertEquals(landtileNorth.getStreet(Direction.SOUTH), landtileCenter.getStreet(Direction.NORTH));
assertEquals(landtileNW.getStreet(Direction.SOUTH_EAST), landtileCenter.getStreet(Direction.NORTH_WEST));
assertEquals(landtileSE.getStreet(Direction.NORTH_WEST), landtileCenter.getStreet(Direction.SOUTH_EAST));
assertEquals(landtileSW.getStreet(Direction.NORTH_EAST), landtileCenter.getStreet(Direction.SOUTH_WEST));
assertEquals(landtileSouth.getStreet(Direction.NORTH), landtileCenter.getStreet(Direction.SOUTH));
landtileNorth = map.getTile(new Coordinate(3, 0));
landtileSouth = map.getTile(new Coordinate(3, 2));
landtileCenter = map.getTile(new Coordinate(3, 1));
landtileNE = map.getTile(new Coordinate(4, 0));
landtileNW = map.getTile(new Coordinate(2, -0));
landtileSE = map.getTile(new Coordinate(4, 1));
landtileSW = map.getTile(new Coordinate(2, 1));
assertEquals(landtileNE.getStreet(Direction.SOUTH_WEST), landtileCenter.getStreet(Direction.NORTH_EAST));
assertEquals(landtileNorth.getStreet(Direction.SOUTH), landtileCenter.getStreet(Direction.NORTH));
assertEquals(landtileNW.getStreet(Direction.SOUTH_EAST), landtileCenter.getStreet(Direction.NORTH_WEST));
assertEquals(landtileSE.getStreet(Direction.NORTH_WEST), landtileCenter.getStreet(Direction.SOUTH_EAST));
assertEquals(landtileSW.getStreet(Direction.NORTH_EAST), landtileCenter.getStreet(Direction.SOUTH_WEST));
assertEquals(landtileSouth.getStreet(Direction.NORTH), landtileCenter.getStreet(Direction.SOUTH));
// voor elke street kijken of het 2 tiles heeft
for (Street street : map.getAllStreets()) {
int tilesConnected = 0;
for (Tile tile : street.getConnectedTiles()) {
if (tile != null) {
tilesConnected++;
}
}
assertEquals(2, tilesConnected);
}
}
// Kijken of elke landtegel 6 straten heeft #
// map.getAllStreets() #
// Kijk of Tile x met als buur tile y dezelfde street delen #
@Test
public void correctBuilding() {
// tile.isValidPlace(Point point) om te kijken of de plek wel geschikt
// 1) bij een evengetal tile
Tile evengetalTile = map.getTile(new Coordinate(0, -2));
assertTrue(evengetalTile.isValidPlace(map, Point.NORTH_EAST));
assertTrue(evengetalTile.isValidPlace(map, Point.EAST));
assertTrue(evengetalTile.isValidPlace(map, Point.SOUTH_EAST));
assertTrue(evengetalTile.isValidPlace(map, Point.NORTH_WEST));
assertTrue(evengetalTile.isValidPlace(map, Point.WEST));
assertTrue(evengetalTile.isValidPlace(map, Point.SOUTH_WEST));
// 2) bij een onevengetal tile
Tile OnevengetalTile = map.getTile(new Coordinate(0, -2));
assertTrue(OnevengetalTile.isValidPlace(map, Point.NORTH_EAST));
assertTrue(OnevengetalTile.isValidPlace(map, Point.EAST));
assertTrue(OnevengetalTile.isValidPlace(map, Point.SOUTH_EAST));
assertTrue(OnevengetalTile.isValidPlace(map, Point.NORTH_WEST));
assertTrue(OnevengetalTile.isValidPlace(map, Point.WEST));
assertTrue(OnevengetalTile.isValidPlace(map, Point.SOUTH_WEST));
Tile landtileEven1 = map.getTile(new Coordinate(0, -3));
Tile landtileEven2 = map.getTile(new Coordinate(0, -1));
Tile landtileEven3 = map.getTile(new Coordinate(0, -2));
Tile landtileOnEven1 = map.getTile(new Coordinate(1, -2));
Tile landtileOnEven2 = map.getTile(new Coordinate(-1, -2));
Tile landtileOnEven3 = map.getTile(new Coordinate(1, -1));
Tile landtileOnEven4 = map.getTile(new Coordinate(-1, -1));
// Kijken of elke landtegel 6 buildings heeft
// kijken of elke tile van de evengetallen landtiles een building heeft
// #
assertNotNull(landtileEven1.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileEven1.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileEven1.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileEven1.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileEven1.getBuilding(Point.WEST));
assertNotNull(landtileEven1.getBuilding(Point.EAST));
assertNotNull(landtileEven2.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileEven2.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileEven2.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileEven2.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileEven2.getBuilding(Point.WEST));
assertNotNull(landtileEven2.getBuilding(Point.EAST));
assertNotNull(landtileEven3.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileEven3.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileEven3.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileEven3.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileEven3.getBuilding(Point.WEST));
assertNotNull(landtileEven3.getBuilding(Point.EAST));
// kijken of elke tile van de onvengetallen landtiles een building heeft
assertNotNull(landtileOnEven1.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileOnEven1.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileOnEven1.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileOnEven1.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileOnEven1.getBuilding(Point.WEST));
assertNotNull(landtileOnEven1.getBuilding(Point.EAST));
assertNotNull(landtileOnEven2.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileOnEven2.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileOnEven2.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileOnEven2.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileOnEven2.getBuilding(Point.WEST));
assertNotNull(landtileOnEven2.getBuilding(Point.EAST));
assertNotNull(landtileOnEven3.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileOnEven3.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileOnEven3.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileOnEven3.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileOnEven3.getBuilding(Point.WEST));
assertNotNull(landtileOnEven3.getBuilding(Point.EAST));
assertNotNull(landtileOnEven4.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileOnEven4.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileOnEven4.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileOnEven4.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileOnEven4.getBuilding(Point.WEST));
assertNotNull(landtileOnEven4.getBuilding(Point.EAST));
// map.getAllBuidlings()
// Kijk of Tile x met als buur tile y dezelfde building delen #
Tile landtileCentral = map.getTile(new Coordinate(0, -2));
Tile landtileNorth = map.getTile(new Coordinate(0, -3));
Tile landtileSouth = map.getTile(new Coordinate(0, -1));
Tile landtileNE = map.getTile(new Coordinate(1, -2));
Tile landtileNW = map.getTile(new Coordinate(-1, -2));
Tile landtileSE = map.getTile(new Coordinate(1, -1));
Tile landtileSW = map.getTile(new Coordinate(-1, -1));
assertEquals(landtileCentral.getBuilding(Point.NORTH_EAST), landtileNorth.getBuilding(Point.SOUTH_EAST));
assertEquals(landtileCentral.getBuilding(Point.NORTH_EAST), landtileNE.getBuilding(Point.WEST));
assertEquals(landtileCentral.getBuilding(Point.EAST), landtileNE.getBuilding(Point.SOUTH_WEST));
assertEquals(landtileCentral.getBuilding(Point.EAST), landtileSE.getBuilding(Point.NORTH_WEST));
assertEquals(landtileCentral.getBuilding(Point.SOUTH_EAST), landtileSE.getBuilding(Point.WEST));
assertEquals(landtileCentral.getBuilding(Point.SOUTH_EAST), landtileSouth.getBuilding(Point.NORTH_EAST));
assertEquals(landtileCentral.getBuilding(Point.SOUTH_WEST), landtileSouth.getBuilding(Point.NORTH_WEST));
assertEquals(landtileCentral.getBuilding(Point.SOUTH_WEST), landtileSW.getBuilding(Point.EAST));
assertEquals(landtileCentral.getBuilding(Point.WEST), landtileSW.getBuilding(Point.NORTH_EAST));
assertEquals(landtileCentral.getBuilding(Point.WEST), landtileNW.getBuilding(Point.SOUTH_EAST));
assertEquals(landtileCentral.getBuilding(Point.NORTH_WEST), landtileNW.getBuilding(Point.EAST));
assertEquals(landtileCentral.getBuilding(Point.NORTH_WEST), landtileNorth.getBuilding(Point.SOUTH_WEST));
// Building met coordinaat en kijken of de 3 tiles eromheen kloppen
Tile buildingTile1 = map.getTile(new Coordinate(0, -2));
Tile buildingTile2 = map.getTile(new Coordinate(0, -1));
Tile buildingTile3 = map.getTile(new Coordinate(-1, -1));
assertEquals(buildingTile1.getBuilding(Point.SOUTH_WEST), buildingTile2.getBuilding(Point.NORTH_WEST));
assertEquals(buildingTile3.getBuilding(Point.EAST), buildingTile2.getBuilding(Point.NORTH_WEST));
assertEquals(buildingTile2.getBuilding(Point.NORTH_WEST), buildingTile1.getBuilding(Point.SOUTH_WEST));
assertEquals(buildingTile1.getBuilding(Point.SOUTH_WEST), buildingTile3.getBuilding(Point.EAST));
// Op een desert moet standaard een rover en op een normale tile niet #
// tile.hasRover() #
TileLand desertTile1 = (TileLand) map.getTile(new Coordinate(0, -2));
TileLand desertTile2 = (TileLand) map.getTile(new Coordinate(0, 1));
TileLand normalTile = (TileLand) map.getTile(new Coordinate(-1, -1));
TileLand normalTile2 = (TileLand) map.getTile(new Coordinate(-2, 0));
TileLand normalTile3 = (TileLand) map.getTile(new Coordinate(-3, -1));
TileLand normalTile4 = (TileLand) map.getTile(new Coordinate(3, -1));
TileLand normalTile5 = (TileLand) map.getTile(new Coordinate(2, 1));
assertTrue(desertTile1.hasRover());
assertTrue(desertTile2.hasRover());
assertTrue(!normalTile.hasRover());
assertTrue(!normalTile2.hasRover());
assertTrue(!normalTile3.hasRover());
assertTrue(!normalTile4.hasRover());
assertTrue(!normalTile5.hasRover());
}
@Test
public void onValidTest() {
ServerPlayer testUser = new ServerPlayer("TEST_PERSOON");
testUser.setColor(Color.BLUE);
Tile north = map.getTile(new Coordinate(0, -1));
Tile center = map.getTile(new Coordinate(0, 0));
Tile east = map.getTile(new Coordinate(1, 0));
north.getBuilding(Point.SOUTH_EAST).setOwner(testUser);
assertTrue(!center.isValidPlace(map, Point.NORTH_EAST));
assertTrue(!center.isValidPlace(map, Point.NORTH_WEST));
assertTrue(!center.isValidPlace(map, Point.EAST));
assertTrue(center.isValidPlace(map, Point.SOUTH_EAST));
assertTrue(center.isValidPlace(map, Point.SOUTH_WEST));
assertTrue(center.isValidPlace(map, Point.WEST));
center.getBuilding(Point.NORTH_EAST).setOwner(testUser);
assertTrue(east.isValidPlace(map, Point.NORTH_EAST));
assertTrue(east.isValidPlace(map, Point.EAST));
assertTrue(east.isValidPlace(map, Point.SOUTH_EAST));
assertTrue(!east.isValidPlace(map, Point.SOUTH_WEST));
assertTrue(!east.isValidPlace(map, Point.WEST));
assertTrue(!east.isValidPlace(map, Point.NORTH_WEST));
// Toevoegen derde tile
}
}
| MakerTim/KolonistenVanCatan | KvC-Server/src/test/java/nl/groep4/kvc/server/MapTester.java | 7,276 | // Op een desert moet standaard een rover en op een normale tile niet # | line_comment | nl | package nl.groep4.kvc.server;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import nl.groep4.kvc.common.enumeration.Color;
import nl.groep4.kvc.common.enumeration.Direction;
import nl.groep4.kvc.common.enumeration.Point;
import nl.groep4.kvc.common.map.Coordinate;
import nl.groep4.kvc.common.map.Map;
import nl.groep4.kvc.common.map.Street;
import nl.groep4.kvc.common.map.Tile;
import nl.groep4.kvc.common.map.TileLand;
import nl.groep4.kvc.common.map.TileType;
import nl.groep4.kvc.server.model.ServerPlayer;
import nl.groep4.kvc.server.model.map.ServerMap;
public class MapTester {
private Map map;
@Before
public void build() {
map = new ServerMap();
map.createMap();
}
@Test
public void testRelativeTile() {
Tile tile = map.getTile(new Coordinate(0, 0));
Tile foundTile;
foundTile = map.getRelativeTile(tile, Direction.NORTH);
assertEquals(new Coordinate(0, -1), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH);
assertEquals(new Coordinate(0, 1), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_EAST);
assertEquals(new Coordinate(1, 1), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_WEST);
assertEquals(new Coordinate(-1, 1), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_EAST);
assertEquals(new Coordinate(1, 0), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_WEST);
assertEquals(new Coordinate(-1, 0), foundTile.getPosition());
tile = map.getTile(new Coordinate(0, 2));
foundTile = map.getRelativeTile(tile, Direction.NORTH);
assertEquals(new Coordinate(0, 1), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH);
assertEquals(new Coordinate(0, 3), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_EAST);
assertEquals(new Coordinate(1, 3), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_WEST);
assertEquals(new Coordinate(-1, 3), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_EAST);
assertEquals(new Coordinate(1, 2), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_WEST);
assertEquals(new Coordinate(-1, 2), foundTile.getPosition());
tile = map.getTile(new Coordinate(-2, -1));
foundTile = map.getRelativeTile(tile, Direction.NORTH);
assertEquals(new Coordinate(-2, -2), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH);
assertEquals(new Coordinate(-2, 0), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_EAST);
assertEquals(new Coordinate(-1, 0), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_WEST);
assertEquals(new Coordinate(-3, 0), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_EAST);
assertEquals(new Coordinate(-1, -1), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_WEST);
assertEquals(new Coordinate(-3, -1), foundTile.getPosition());
tile = map.getTile(new Coordinate(0, -4));
assertNotNull(foundTile);
foundTile = map.getRelativeTile(tile, Direction.NORTH);
assertNull(null);
foundTile = map.getRelativeTile(tile, Direction.SOUTH);
assertEquals(new Coordinate(0, -3), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_EAST);
assertEquals(new Coordinate(1, -3), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.SOUTH_WEST);
assertEquals(new Coordinate(-1, -3), foundTile.getPosition());
foundTile = map.getRelativeTile(tile, Direction.NORTH_EAST);
assertNull(null);
foundTile = map.getRelativeTile(tile, Direction.NORTH_WEST);
assertNull(null);
// Kijken of daadwerkelijk een tegel naast de ander zit
// map.getRelativeTile(tile, direction)
}
@Test
public void testTilesCreated() {
int counterFOREST = 0;
int counterMESA = 0;
int counterPLAINS = 0;
int counterMOUNTAIN = 0;
int counterWHEAT = 0;
int counterDESERT = 0;
int counterWATER = 0;
List<Tile> tiles = map.getTiles();
for (int i = 0; i < tiles.size(); i++) {
Tile tile = tiles.get(i);
tile.getType();
switch (tile.getType()) {
case FOREST:
counterFOREST++;
break;
case MESA:
counterMESA++;
break;
case PLAINS:
counterPLAINS++;
break;
case MOUNTAIN:
counterMOUNTAIN++;
break;
case WHEAT:
counterWHEAT++;
break;
case DESERT:
counterDESERT++;
break;
case WATER:
case WATER_TRADE:
case WATER_OPEN_TRADE:
counterWATER++;
break;
default:
break;
}
}
assertEquals(6, counterFOREST);
assertEquals(5, counterMESA);
assertEquals(6, counterPLAINS);
assertEquals(5, counterMOUNTAIN);
assertEquals(6, counterWHEAT);
assertEquals(2, counterDESERT);
assertEquals(22, counterWATER);
Tile tile = map.getTile(0, -4);
assertEquals(TileType.WATER, tile.getType());
Tile tile2 = map.getTile(1, -3);
assertEquals(TileType.WATER, tile2.getType());
Tile tile3 = map.getTile(2, -3);
assertEquals(TileType.WATER, tile3.getType());
Tile tile4 = map.getTile(3, -2);
assertEquals(TileType.WATER, tile4.getType());
Tile tile5 = map.getTile(4, -2);
assertEquals(TileType.WATER, tile5.getType());
Tile tile6 = map.getTile(4, -1);
assertEquals(TileType.WATER, tile6.getType());
Tile tile7 = map.getTile(4, 0);
assertEquals(TileType.WATER, tile7.getType());
Tile tile8 = map.getTile(4, 1);
assertEquals(TileType.WATER, tile8.getType());
Tile tile9 = map.getTile(3, 2);
assertEquals(TileType.WATER, tile9.getType());
Tile tile10 = map.getTile(2, 2);
assertEquals(TileType.WATER, tile10.getType());
Tile tile11 = map.getTile(1, 3);
assertEquals(TileType.WATER, tile11.getType());
Tile tile12 = map.getTile(0, 3);
assertEquals(TileType.WATER, tile12.getType());
Tile tile13 = map.getTile(-1, 3);
assertEquals(TileType.WATER, tile13.getType());
Tile tile14 = map.getTile(-2, 2);
assertEquals(TileType.WATER, tile14.getType());
Tile tile15 = map.getTile(-3, 2);
assertEquals(TileType.WATER, tile15.getType());
Tile tile16 = map.getTile(-4, 1);
assertEquals(TileType.WATER, tile16.getType());
Tile tile17 = map.getTile(-4, 0);
assertEquals(TileType.WATER, tile17.getType());
Tile tile18 = map.getTile(-4, -1);
assertEquals(TileType.WATER, tile18.getType());
Tile tile19 = map.getTile(-4, -2);
assertEquals(TileType.WATER, tile19.getType());
Tile tile20 = map.getTile(-3, -2);
assertEquals(TileType.WATER, tile20.getType());
Tile tile21 = map.getTile(-2, -3);
assertEquals(TileType.WATER, tile21.getType());
Tile tile22 = map.getTile(-1, -3);
assertEquals(TileType.WATER, tile22.getType());
}
// map.getTiles() #
// kijken of de desert op goede plek staat MOET NOG GEFIXED WORDEN WACHT OP
// TIM!
// kijken of er 6forest,6...,6... 5mesa, 5mountain #
// kijken of buitenrand helemaal uit water bestaat #
@Test
public void correctStreets() {
// alle relatieve tiles van de evengetalcentrale tile
Tile landtileNorth = map.getTile(new Coordinate(0, -3));
Tile landtileSouth = map.getTile(new Coordinate(0, -1));
Tile landtileCenter = map.getTile(new Coordinate(0, -2));
Tile landtileNE = map.getTile(new Coordinate(1, -2));
Tile landtileNW = map.getTile(new Coordinate(-1, -2));
Tile landtileSE = map.getTile(new Coordinate(1, -1));
Tile landtileSW = map.getTile(new Coordinate(-1, -1));
// Tile testTile = map.getTile(new Coordinate(0, -3));
// assertNotNull(testTile.getStreet(Direction.NORTH));
// de verschillende tiles met elkaar vergelijken
assertNotNull(landtileCenter.getStreet(Direction.NORTH));
assertNotNull(landtileCenter.getStreet(Direction.NORTH_EAST));
assertNotNull(landtileCenter.getStreet(Direction.NORTH_WEST));
assertNotNull(landtileCenter.getStreet(Direction.SOUTH));
assertNotNull(landtileCenter.getStreet(Direction.SOUTH_EAST));
assertNotNull(landtileCenter.getStreet(Direction.SOUTH_WEST));
assertEquals(landtileNorth.getStreet(Direction.SOUTH), landtileCenter.getStreet(Direction.NORTH));
// evengetal tiles hier getest
assertEquals(landtileNE.getStreet(Direction.SOUTH_WEST), landtileCenter.getStreet(Direction.NORTH_EAST));
assertEquals(landtileNW.getStreet(Direction.SOUTH_EAST), landtileCenter.getStreet(Direction.NORTH_WEST));
assertEquals(landtileSE.getStreet(Direction.NORTH_WEST), landtileCenter.getStreet(Direction.SOUTH_EAST));
assertEquals(landtileSW.getStreet(Direction.NORTH_EAST), landtileCenter.getStreet(Direction.SOUTH_WEST));
assertEquals(landtileSouth.getStreet(Direction.NORTH), landtileCenter.getStreet(Direction.SOUTH));
landtileNorth = map.getTile(new Coordinate(-1, -2));
landtileSouth = map.getTile(new Coordinate(-1, 0));
landtileCenter = map.getTile(new Coordinate(-1, -1));
landtileNE = map.getTile(new Coordinate(0, -2));
landtileNW = map.getTile(new Coordinate(-2, -2));
landtileSE = map.getTile(new Coordinate(0, -1));
landtileSW = map.getTile(new Coordinate(-2, -1));
// niet evengetal tiles worden hier getest
assertEquals(landtileNE.getStreet(Direction.SOUTH_WEST), landtileCenter.getStreet(Direction.NORTH_EAST));
assertEquals(landtileNorth.getStreet(Direction.SOUTH), landtileCenter.getStreet(Direction.NORTH));
assertEquals(landtileNW.getStreet(Direction.SOUTH_EAST), landtileCenter.getStreet(Direction.NORTH_WEST));
assertEquals(landtileSE.getStreet(Direction.NORTH_WEST), landtileCenter.getStreet(Direction.SOUTH_EAST));
assertEquals(landtileSW.getStreet(Direction.NORTH_EAST), landtileCenter.getStreet(Direction.SOUTH_WEST));
assertEquals(landtileSouth.getStreet(Direction.NORTH), landtileCenter.getStreet(Direction.SOUTH));
landtileNorth = map.getTile(new Coordinate(3, 0));
landtileSouth = map.getTile(new Coordinate(3, 2));
landtileCenter = map.getTile(new Coordinate(3, 1));
landtileNE = map.getTile(new Coordinate(4, 0));
landtileNW = map.getTile(new Coordinate(2, -0));
landtileSE = map.getTile(new Coordinate(4, 1));
landtileSW = map.getTile(new Coordinate(2, 1));
assertEquals(landtileNE.getStreet(Direction.SOUTH_WEST), landtileCenter.getStreet(Direction.NORTH_EAST));
assertEquals(landtileNorth.getStreet(Direction.SOUTH), landtileCenter.getStreet(Direction.NORTH));
assertEquals(landtileNW.getStreet(Direction.SOUTH_EAST), landtileCenter.getStreet(Direction.NORTH_WEST));
assertEquals(landtileSE.getStreet(Direction.NORTH_WEST), landtileCenter.getStreet(Direction.SOUTH_EAST));
assertEquals(landtileSW.getStreet(Direction.NORTH_EAST), landtileCenter.getStreet(Direction.SOUTH_WEST));
assertEquals(landtileSouth.getStreet(Direction.NORTH), landtileCenter.getStreet(Direction.SOUTH));
// voor elke street kijken of het 2 tiles heeft
for (Street street : map.getAllStreets()) {
int tilesConnected = 0;
for (Tile tile : street.getConnectedTiles()) {
if (tile != null) {
tilesConnected++;
}
}
assertEquals(2, tilesConnected);
}
}
// Kijken of elke landtegel 6 straten heeft #
// map.getAllStreets() #
// Kijk of Tile x met als buur tile y dezelfde street delen #
@Test
public void correctBuilding() {
// tile.isValidPlace(Point point) om te kijken of de plek wel geschikt
// 1) bij een evengetal tile
Tile evengetalTile = map.getTile(new Coordinate(0, -2));
assertTrue(evengetalTile.isValidPlace(map, Point.NORTH_EAST));
assertTrue(evengetalTile.isValidPlace(map, Point.EAST));
assertTrue(evengetalTile.isValidPlace(map, Point.SOUTH_EAST));
assertTrue(evengetalTile.isValidPlace(map, Point.NORTH_WEST));
assertTrue(evengetalTile.isValidPlace(map, Point.WEST));
assertTrue(evengetalTile.isValidPlace(map, Point.SOUTH_WEST));
// 2) bij een onevengetal tile
Tile OnevengetalTile = map.getTile(new Coordinate(0, -2));
assertTrue(OnevengetalTile.isValidPlace(map, Point.NORTH_EAST));
assertTrue(OnevengetalTile.isValidPlace(map, Point.EAST));
assertTrue(OnevengetalTile.isValidPlace(map, Point.SOUTH_EAST));
assertTrue(OnevengetalTile.isValidPlace(map, Point.NORTH_WEST));
assertTrue(OnevengetalTile.isValidPlace(map, Point.WEST));
assertTrue(OnevengetalTile.isValidPlace(map, Point.SOUTH_WEST));
Tile landtileEven1 = map.getTile(new Coordinate(0, -3));
Tile landtileEven2 = map.getTile(new Coordinate(0, -1));
Tile landtileEven3 = map.getTile(new Coordinate(0, -2));
Tile landtileOnEven1 = map.getTile(new Coordinate(1, -2));
Tile landtileOnEven2 = map.getTile(new Coordinate(-1, -2));
Tile landtileOnEven3 = map.getTile(new Coordinate(1, -1));
Tile landtileOnEven4 = map.getTile(new Coordinate(-1, -1));
// Kijken of elke landtegel 6 buildings heeft
// kijken of elke tile van de evengetallen landtiles een building heeft
// #
assertNotNull(landtileEven1.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileEven1.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileEven1.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileEven1.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileEven1.getBuilding(Point.WEST));
assertNotNull(landtileEven1.getBuilding(Point.EAST));
assertNotNull(landtileEven2.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileEven2.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileEven2.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileEven2.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileEven2.getBuilding(Point.WEST));
assertNotNull(landtileEven2.getBuilding(Point.EAST));
assertNotNull(landtileEven3.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileEven3.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileEven3.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileEven3.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileEven3.getBuilding(Point.WEST));
assertNotNull(landtileEven3.getBuilding(Point.EAST));
// kijken of elke tile van de onvengetallen landtiles een building heeft
assertNotNull(landtileOnEven1.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileOnEven1.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileOnEven1.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileOnEven1.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileOnEven1.getBuilding(Point.WEST));
assertNotNull(landtileOnEven1.getBuilding(Point.EAST));
assertNotNull(landtileOnEven2.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileOnEven2.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileOnEven2.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileOnEven2.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileOnEven2.getBuilding(Point.WEST));
assertNotNull(landtileOnEven2.getBuilding(Point.EAST));
assertNotNull(landtileOnEven3.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileOnEven3.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileOnEven3.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileOnEven3.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileOnEven3.getBuilding(Point.WEST));
assertNotNull(landtileOnEven3.getBuilding(Point.EAST));
assertNotNull(landtileOnEven4.getBuilding(Point.NORTH_EAST));
assertNotNull(landtileOnEven4.getBuilding(Point.NORTH_WEST));
assertNotNull(landtileOnEven4.getBuilding(Point.SOUTH_EAST));
assertNotNull(landtileOnEven4.getBuilding(Point.SOUTH_WEST));
assertNotNull(landtileOnEven4.getBuilding(Point.WEST));
assertNotNull(landtileOnEven4.getBuilding(Point.EAST));
// map.getAllBuidlings()
// Kijk of Tile x met als buur tile y dezelfde building delen #
Tile landtileCentral = map.getTile(new Coordinate(0, -2));
Tile landtileNorth = map.getTile(new Coordinate(0, -3));
Tile landtileSouth = map.getTile(new Coordinate(0, -1));
Tile landtileNE = map.getTile(new Coordinate(1, -2));
Tile landtileNW = map.getTile(new Coordinate(-1, -2));
Tile landtileSE = map.getTile(new Coordinate(1, -1));
Tile landtileSW = map.getTile(new Coordinate(-1, -1));
assertEquals(landtileCentral.getBuilding(Point.NORTH_EAST), landtileNorth.getBuilding(Point.SOUTH_EAST));
assertEquals(landtileCentral.getBuilding(Point.NORTH_EAST), landtileNE.getBuilding(Point.WEST));
assertEquals(landtileCentral.getBuilding(Point.EAST), landtileNE.getBuilding(Point.SOUTH_WEST));
assertEquals(landtileCentral.getBuilding(Point.EAST), landtileSE.getBuilding(Point.NORTH_WEST));
assertEquals(landtileCentral.getBuilding(Point.SOUTH_EAST), landtileSE.getBuilding(Point.WEST));
assertEquals(landtileCentral.getBuilding(Point.SOUTH_EAST), landtileSouth.getBuilding(Point.NORTH_EAST));
assertEquals(landtileCentral.getBuilding(Point.SOUTH_WEST), landtileSouth.getBuilding(Point.NORTH_WEST));
assertEquals(landtileCentral.getBuilding(Point.SOUTH_WEST), landtileSW.getBuilding(Point.EAST));
assertEquals(landtileCentral.getBuilding(Point.WEST), landtileSW.getBuilding(Point.NORTH_EAST));
assertEquals(landtileCentral.getBuilding(Point.WEST), landtileNW.getBuilding(Point.SOUTH_EAST));
assertEquals(landtileCentral.getBuilding(Point.NORTH_WEST), landtileNW.getBuilding(Point.EAST));
assertEquals(landtileCentral.getBuilding(Point.NORTH_WEST), landtileNorth.getBuilding(Point.SOUTH_WEST));
// Building met coordinaat en kijken of de 3 tiles eromheen kloppen
Tile buildingTile1 = map.getTile(new Coordinate(0, -2));
Tile buildingTile2 = map.getTile(new Coordinate(0, -1));
Tile buildingTile3 = map.getTile(new Coordinate(-1, -1));
assertEquals(buildingTile1.getBuilding(Point.SOUTH_WEST), buildingTile2.getBuilding(Point.NORTH_WEST));
assertEquals(buildingTile3.getBuilding(Point.EAST), buildingTile2.getBuilding(Point.NORTH_WEST));
assertEquals(buildingTile2.getBuilding(Point.NORTH_WEST), buildingTile1.getBuilding(Point.SOUTH_WEST));
assertEquals(buildingTile1.getBuilding(Point.SOUTH_WEST), buildingTile3.getBuilding(Point.EAST));
// Op een<SUF>
// tile.hasRover() #
TileLand desertTile1 = (TileLand) map.getTile(new Coordinate(0, -2));
TileLand desertTile2 = (TileLand) map.getTile(new Coordinate(0, 1));
TileLand normalTile = (TileLand) map.getTile(new Coordinate(-1, -1));
TileLand normalTile2 = (TileLand) map.getTile(new Coordinate(-2, 0));
TileLand normalTile3 = (TileLand) map.getTile(new Coordinate(-3, -1));
TileLand normalTile4 = (TileLand) map.getTile(new Coordinate(3, -1));
TileLand normalTile5 = (TileLand) map.getTile(new Coordinate(2, 1));
assertTrue(desertTile1.hasRover());
assertTrue(desertTile2.hasRover());
assertTrue(!normalTile.hasRover());
assertTrue(!normalTile2.hasRover());
assertTrue(!normalTile3.hasRover());
assertTrue(!normalTile4.hasRover());
assertTrue(!normalTile5.hasRover());
}
@Test
public void onValidTest() {
ServerPlayer testUser = new ServerPlayer("TEST_PERSOON");
testUser.setColor(Color.BLUE);
Tile north = map.getTile(new Coordinate(0, -1));
Tile center = map.getTile(new Coordinate(0, 0));
Tile east = map.getTile(new Coordinate(1, 0));
north.getBuilding(Point.SOUTH_EAST).setOwner(testUser);
assertTrue(!center.isValidPlace(map, Point.NORTH_EAST));
assertTrue(!center.isValidPlace(map, Point.NORTH_WEST));
assertTrue(!center.isValidPlace(map, Point.EAST));
assertTrue(center.isValidPlace(map, Point.SOUTH_EAST));
assertTrue(center.isValidPlace(map, Point.SOUTH_WEST));
assertTrue(center.isValidPlace(map, Point.WEST));
center.getBuilding(Point.NORTH_EAST).setOwner(testUser);
assertTrue(east.isValidPlace(map, Point.NORTH_EAST));
assertTrue(east.isValidPlace(map, Point.EAST));
assertTrue(east.isValidPlace(map, Point.SOUTH_EAST));
assertTrue(!east.isValidPlace(map, Point.SOUTH_WEST));
assertTrue(!east.isValidPlace(map, Point.WEST));
assertTrue(!east.isValidPlace(map, Point.NORTH_WEST));
// Toevoegen derde tile
}
}
|
158422_35 | package com.example.mwojcik.recyclerviewone;
import android.content.Intent;
import android.os.Build;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.util.Pair;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.util.DiffUtil;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.transition.Explode;
import android.util.Log;
import android.view.View;
import android.view.Window;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
FloatingActionButton fab;
/***
* Zamockowane dane na potrzeby prezentacji recyclerView - normalnie pobieralibysmy to z internetu czy bazy danych.
* Musimy je zrobic globalne dla klasy, zeby mozna bylo je w dowolych metodach zmieniac. Tak samo adapter,
* zebysmy mogli go w dowolnym miejscu zmodyfikować (np. dodać itemy do listy)
*/
List<Model> mockData;
RecyclerViewAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
// getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);
// getWindow().setExitTransition(new Explode());
// getWindow().setTransitionBackgroundFadeDuration(1000);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.main_recycler_view);
fab = (FloatingActionButton) findViewById(R.id.fab);
// final List<Model> mockData = new ArrayList<>(); - po ustawieniu globalnie
mockData = new ArrayList<>();
mockData.add(new Model(2, "Zorro", "Opowiesc o zorro"));
mockData.add(new Model(1, "Batman", "Opowiesc o batmanie"));
mockData.add(new Model(5, "Spiderman", "Opowiesc o spidermanie"));
mockData.add(new Model(7, "Wolverine", "Opowiesc o wolverinie"));
mockData.add(new Model(3, "Silversurfer", "Opowiesc o silversurferze"));
mockData.add(new Model(8, "Flash", "Opowiesc o flashu"));
mockData.add(new Model(4, "Anakin Skywalker", "Opowiesc o darth vaderze"));
mockData.add(new Model(6, "Superman", "Opowiesc o klarku kencie"));
mockData.add(new Model(9, "Wonderwoman", "Opowiesc o wonderwoman"));
mockData.add(new Model(10, "Magneto", "Opowiesc o magneto"));
mockData.add(new Model(11, "Hulk", "Opowiesc o hulku"));
// RecyclerViewAdapter adapter = new RecyclerViewAdapter(mockData); - po ustawieniu globalnej
adapter = new RecyclerViewAdapter(mockData);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
/***
* Ustawiamy sobie naszego customowego listenera do oderbania na adapterze
*/
adapter.setOnItemClickListener(new RecyclerViewAdapter.RecyclerViewOnItemClickListener() {
@Override
public void onItemClick(View itemView, int position) {
/***
* Dzięki temu, że ustawiliśmy sobie wcześniej TAG w viewHolderze, możemy go również
* użyć tutaj, bo przecież itemView jest cały czas ten sam - row item
*/
// Model model = mockData.get(position);
Model model = (Model) itemView.getTag();
Log.d("MainActivity", "Received itemClick from listener for item: " + model.getTitle());
// mozemy np. usunac item po klikninięciu:
// deleteItem(position);
//przeniesienie do nowego activity. Moze byc tu lub np. w viewholderze
Intent intent = new Intent(MainActivity.this, NewActivity.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(MainActivity.this, Pair.create(itemView.findViewById(R.id.recyclerview_item_title), "text1"),
Pair.create(itemView.findViewById(R.id.recyclerview_item_description), "text2"));
startActivity(intent, options.toBundle());
} else {
startActivity(intent);
}
}
});
//Customowy itemDecoraton: https://gist.github.com/nesquena/db922669798eba3e3661
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
MyDividerItemDecoration myDividerItemDecoration = new MyDividerItemDecoration(this, LinearLayoutManager.VERTICAL, 16);
RecyclerView.ItemAnimator itemAnimator = new DefaultItemAnimator();
itemAnimator.setAddDuration(500);
itemAnimator.setRemoveDuration(500);
// itemAnimator.setMoveDuration(1000);
// recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setItemAnimator(itemAnimator);
// recyclerView.addItemDecoration(itemDecoration);
recyclerView.addItemDecoration(myDividerItemDecoration);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
//Click listenery: https://gist.github.com/nesquena/231e356f372f214c4fe6
/***
* Listener kliknięcia floating action buttona. Co warte tutaj uwagi, jak dodamy floating action buttona (najlepiej w coordinator layoucie)
* to jego kliknięcie nic nie da, nie zainicjalizuje zadnej animacji itp, a nawet kliknie się item z recyclerview, który jest pod\
* danym fab buttonem - czyli button jest widoczny, ale tak jakby nie istniał.
*/
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("MainActivity", "Floating action button tapped");
addNewItemToList();
// Snackbar.make(view, "Floating button tapped", Snackbar.LENGTH_SHORT)
// .setAction("UNDO", new View.OnClickListener() {
// @Override
// public void onClick(View view) {
//
// }
// }).show();
}
});
}
/***
* DOdajemy sobie nowy item do listy i powiadamiamy adapter o zmianie. Co tutaj jest warte uwagi, w przeciwienstwie do listview
* w RecyclerView nie powinnismy naduzywać notifyDataSetChanged, tylko bardziej szczegółowe działania - a takie działania,
* takie metody nam recyclerview udostępnia. Mamy tak:
* notifyItemChanged(int position), notifyItemInserted(int position), notifyItemRemoved(int position), notifyDataSetChanged()).
* notifyDataSetChanged() powinno być używane w konieczności, lepiej robić to szczegółowo - po to są te metody.
*
* Nizej pokazane przyklady. Ale jeszcze jedno ważne do powiedzenia tutaj - często możemy mieć bardziej kompleksowe zmiany,
* bardziej skomplikowane, jak np. sortowanie - wtedy nie możemy powiedzieć tak łatwo który item row się zmienił, które elementy itp.
* W takim wypadku zazwyczaj wywołalibyśmy notifyDataSetChanged() na całym adapterze, co jednak eliminuje możliwość
* wykonania sekwencji animacji do pokazania co się zmieniło. Tutaj recyclerView od 27.1. support library udostępnił nowe rzeczy, takie
* jak np. ListAdapter dla RecyclerView, klsa która ułatwia rozpoznanie czy item został wsatwione, usunięty, zupdejtowany itp.
* Taki ListAdapter zbudowany jest na DiffUtil - my możemy więc też użyć tego DiffUtil, który został dodany wcześniej,
* bo chyba w v24. Jest to klasa, który pomaga wyznaczyć/obliczyć różnice między starą a nową listą. Klasa ta używa takiego samego jak
* ListAdapter algorytmy do obliczania tych zmian. Rekomendowane jest jednak dla większych list, żeby wykonywane te obliczenia były
* w background threadzie. Zobaczymy jak taki DiffUtil użyć.Dla tego przykładu zrobiłem klasę ModelDiffUtil, która możemyt wywołać tutaj
* lub najlpeiej - dla czystosci kodu - w adapterze, bo to z nim pracuje ta klasa.
*/
private void addNewItemToList(){
addNewItemWithInserted();
// addNewItemWithDiffUtil();
// sortItemsWithDiffUtil();
}
private void addNewItemWithDataSetChanged(){
//Doda nam nowy item na dole listy - (zwrócmy uwage, że to nam nie scrolluje, tylko dodaje się nowy item a nasz scroll)
mockData.add(new Model(13, "Nowy item nr. " + (mockData.size()+1), "opis"));
adapter.notifyDataSetChanged();
}
private void addNewItemWithInserted(){
//// Doda nam nowy item na dole listy - (zwrócmy uwage, że to nam nie scrolluje, tylko dodaje się nowy item a nasz scroll)
// mockData.add(mockData.size(), new Model(mockData.size()+1, "Nowy item nr. " + (mockData.size()+1), "opis"));
// adapter.notifyItemInserted(mockData.size());
// //Dodany scroll do nowej pozycji -1, dlatego ze indeksujemy przeciez od 0 a nie od 1 i po prostu probowalibysmy
// //wskoczyc na miejsce nie istniejace - co mnei dziwi tutaj, ze nie leci zaden exception w takim wypadku?
// recyclerView.scrollToPosition(mockData.size()-1);
//Lub na początek: (zwrócmy uwage, że to nam nie scrolluje, tylko dodaje się nowy item a nasz scroll)
//na liście jest dalej w tym samym miejscu
mockData.add(0, new Model(mockData.size()+1, "Nowy item nr. " + (mockData.size()+1), "opis"));
adapter.notifyItemInserted(0);
recyclerView.scrollToPosition(0);
}
private void addNewItemWithRangeChanged(){
//Lub jeszcze inaczej, jak chcemy dodać więcej niż 1 elementów to najlepiej tak:
int curSize = adapter.getItemCount();
ArrayList<Model> newItems = new ArrayList<>();
for (int i = curSize; i < curSize+6; i++){
newItems.add(new Model(i+1, "numer " + (i+1), "opis"));
}
mockData.addAll(newItems);
adapter.notifyItemRangeChanged(curSize, newItems.size());
recyclerView.scrollToPosition(curSize);
}
private void sortItemsWithDiffUtil(){
List<Model> models = new ArrayList<>();
models.addAll(mockData);
Collections.sort(models, new Comparator<Model>() {
@Override
public int compare(Model model, Model t1) {
return model.getId() - t1.getId();
}
});
adapter.updateSortedList(models);
}
/***
* Tutaj mamy przykład wywołania DiffUtil do zmiany listy. Uzywac jak chcemy wiecej elemtnow dodac
*/
private void addNewItemWithDiffUtil(){
int curSize = adapter.getItemCount();
ArrayList<Model> newItems = new ArrayList<>();
for (int i = curSize; i < curSize+6; i++){
newItems.add(new Model(i+1, "numer " + (i+1), "opis"));
}
adapter.diffUtilTest(newItems);
}
private void deleteItem(int position){
mockData.remove(position);
// adapter.notifyDataSetChanged();
adapter.notifyItemRemoved(position);
// Albo jak byśmy przekazali obiekt Model jako parametr metody
// int position = list.indexOf(model);
// list.remove(position);
// notifyItemRemoved(position);
}
// private void diffUtilTest(List<Model> modelList){
// RecyclerViewDiffUtilCallback callback = new RecyclerViewDiffUtilCallback(this.mockData, modelList);
// DiffUtil.DiffResult result = DiffUtil.calculateDiff(callback);
//
// this.mockData.clear();
// this.mockData.addAll(modelList);
// result.dispatchUpdatesTo(adapter);
// }
}
// //Doda nam nowy item na dole listy - (zwrócmy uwage, że to nam nie scrolluje, tylko dodaje się nowy item a nasz scroll)
//// mockData.add(new Model(13, "Nowy item nr. " + (mockData.size()+1), "opis"));
////// adapter.notifyDataSetChanged();
//// adapter.notifyItemInserted(mockData.size()+1);
//
//
// //Lub na początek: (zwrócmy uwage, że to nam nie scrolluje, tylko dodaje się nowy item a nasz scroll)
// //na liście jest dalej w tym samym miejscu
//// mockData.add(0, new Model(13, "Nowy item nr. " + (mockData.size()+1), "opis"));
//// adapter.notifyItemInserted(0);
//
//
// //Lub jeszcze inaczej, jak chcemy dodać więcej niż 1 elementów to najlepiej tak:
// int curSize = adapter.getItemCount();
//
// ArrayList<Model> newItems = new ArrayList<>();
// for (int i = curSize; i < curSize+6; i++){
// newItems.add(new Model(i+1, "numer " + (i+1), "opis"));
// }
// //zakomentowane zeby sprawdic diffUtil.
//// mockData.addAll(newItems);
//// adapter.notifyItemRangeChanged(curSize, newItems.size());
//
// /***
// * Tutaj mamy przykład wywołania DiffUtil do zmiany listy.
// */
// adapter.diffUtilTest(newItems); | MaksymilianWojcik/Mastering_RecyclerView | app/src/main/java/com/example/mwojcik/recyclerviewone/MainActivity.java | 4,412 | // int curSize = adapter.getItemCount(); | line_comment | nl | package com.example.mwojcik.recyclerviewone;
import android.content.Intent;
import android.os.Build;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.util.Pair;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.util.DiffUtil;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.transition.Explode;
import android.util.Log;
import android.view.View;
import android.view.Window;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
FloatingActionButton fab;
/***
* Zamockowane dane na potrzeby prezentacji recyclerView - normalnie pobieralibysmy to z internetu czy bazy danych.
* Musimy je zrobic globalne dla klasy, zeby mozna bylo je w dowolych metodach zmieniac. Tak samo adapter,
* zebysmy mogli go w dowolnym miejscu zmodyfikować (np. dodać itemy do listy)
*/
List<Model> mockData;
RecyclerViewAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
// getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);
// getWindow().setExitTransition(new Explode());
// getWindow().setTransitionBackgroundFadeDuration(1000);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.main_recycler_view);
fab = (FloatingActionButton) findViewById(R.id.fab);
// final List<Model> mockData = new ArrayList<>(); - po ustawieniu globalnie
mockData = new ArrayList<>();
mockData.add(new Model(2, "Zorro", "Opowiesc o zorro"));
mockData.add(new Model(1, "Batman", "Opowiesc o batmanie"));
mockData.add(new Model(5, "Spiderman", "Opowiesc o spidermanie"));
mockData.add(new Model(7, "Wolverine", "Opowiesc o wolverinie"));
mockData.add(new Model(3, "Silversurfer", "Opowiesc o silversurferze"));
mockData.add(new Model(8, "Flash", "Opowiesc o flashu"));
mockData.add(new Model(4, "Anakin Skywalker", "Opowiesc o darth vaderze"));
mockData.add(new Model(6, "Superman", "Opowiesc o klarku kencie"));
mockData.add(new Model(9, "Wonderwoman", "Opowiesc o wonderwoman"));
mockData.add(new Model(10, "Magneto", "Opowiesc o magneto"));
mockData.add(new Model(11, "Hulk", "Opowiesc o hulku"));
// RecyclerViewAdapter adapter = new RecyclerViewAdapter(mockData); - po ustawieniu globalnej
adapter = new RecyclerViewAdapter(mockData);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
/***
* Ustawiamy sobie naszego customowego listenera do oderbania na adapterze
*/
adapter.setOnItemClickListener(new RecyclerViewAdapter.RecyclerViewOnItemClickListener() {
@Override
public void onItemClick(View itemView, int position) {
/***
* Dzięki temu, że ustawiliśmy sobie wcześniej TAG w viewHolderze, możemy go również
* użyć tutaj, bo przecież itemView jest cały czas ten sam - row item
*/
// Model model = mockData.get(position);
Model model = (Model) itemView.getTag();
Log.d("MainActivity", "Received itemClick from listener for item: " + model.getTitle());
// mozemy np. usunac item po klikninięciu:
// deleteItem(position);
//przeniesienie do nowego activity. Moze byc tu lub np. w viewholderze
Intent intent = new Intent(MainActivity.this, NewActivity.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(MainActivity.this, Pair.create(itemView.findViewById(R.id.recyclerview_item_title), "text1"),
Pair.create(itemView.findViewById(R.id.recyclerview_item_description), "text2"));
startActivity(intent, options.toBundle());
} else {
startActivity(intent);
}
}
});
//Customowy itemDecoraton: https://gist.github.com/nesquena/db922669798eba3e3661
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
MyDividerItemDecoration myDividerItemDecoration = new MyDividerItemDecoration(this, LinearLayoutManager.VERTICAL, 16);
RecyclerView.ItemAnimator itemAnimator = new DefaultItemAnimator();
itemAnimator.setAddDuration(500);
itemAnimator.setRemoveDuration(500);
// itemAnimator.setMoveDuration(1000);
// recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setItemAnimator(itemAnimator);
// recyclerView.addItemDecoration(itemDecoration);
recyclerView.addItemDecoration(myDividerItemDecoration);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
//Click listenery: https://gist.github.com/nesquena/231e356f372f214c4fe6
/***
* Listener kliknięcia floating action buttona. Co warte tutaj uwagi, jak dodamy floating action buttona (najlepiej w coordinator layoucie)
* to jego kliknięcie nic nie da, nie zainicjalizuje zadnej animacji itp, a nawet kliknie się item z recyclerview, który jest pod\
* danym fab buttonem - czyli button jest widoczny, ale tak jakby nie istniał.
*/
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("MainActivity", "Floating action button tapped");
addNewItemToList();
// Snackbar.make(view, "Floating button tapped", Snackbar.LENGTH_SHORT)
// .setAction("UNDO", new View.OnClickListener() {
// @Override
// public void onClick(View view) {
//
// }
// }).show();
}
});
}
/***
* DOdajemy sobie nowy item do listy i powiadamiamy adapter o zmianie. Co tutaj jest warte uwagi, w przeciwienstwie do listview
* w RecyclerView nie powinnismy naduzywać notifyDataSetChanged, tylko bardziej szczegółowe działania - a takie działania,
* takie metody nam recyclerview udostępnia. Mamy tak:
* notifyItemChanged(int position), notifyItemInserted(int position), notifyItemRemoved(int position), notifyDataSetChanged()).
* notifyDataSetChanged() powinno być używane w konieczności, lepiej robić to szczegółowo - po to są te metody.
*
* Nizej pokazane przyklady. Ale jeszcze jedno ważne do powiedzenia tutaj - często możemy mieć bardziej kompleksowe zmiany,
* bardziej skomplikowane, jak np. sortowanie - wtedy nie możemy powiedzieć tak łatwo który item row się zmienił, które elementy itp.
* W takim wypadku zazwyczaj wywołalibyśmy notifyDataSetChanged() na całym adapterze, co jednak eliminuje możliwość
* wykonania sekwencji animacji do pokazania co się zmieniło. Tutaj recyclerView od 27.1. support library udostępnił nowe rzeczy, takie
* jak np. ListAdapter dla RecyclerView, klsa która ułatwia rozpoznanie czy item został wsatwione, usunięty, zupdejtowany itp.
* Taki ListAdapter zbudowany jest na DiffUtil - my możemy więc też użyć tego DiffUtil, który został dodany wcześniej,
* bo chyba w v24. Jest to klasa, który pomaga wyznaczyć/obliczyć różnice między starą a nową listą. Klasa ta używa takiego samego jak
* ListAdapter algorytmy do obliczania tych zmian. Rekomendowane jest jednak dla większych list, żeby wykonywane te obliczenia były
* w background threadzie. Zobaczymy jak taki DiffUtil użyć.Dla tego przykładu zrobiłem klasę ModelDiffUtil, która możemyt wywołać tutaj
* lub najlpeiej - dla czystosci kodu - w adapterze, bo to z nim pracuje ta klasa.
*/
private void addNewItemToList(){
addNewItemWithInserted();
// addNewItemWithDiffUtil();
// sortItemsWithDiffUtil();
}
private void addNewItemWithDataSetChanged(){
//Doda nam nowy item na dole listy - (zwrócmy uwage, że to nam nie scrolluje, tylko dodaje się nowy item a nasz scroll)
mockData.add(new Model(13, "Nowy item nr. " + (mockData.size()+1), "opis"));
adapter.notifyDataSetChanged();
}
private void addNewItemWithInserted(){
//// Doda nam nowy item na dole listy - (zwrócmy uwage, że to nam nie scrolluje, tylko dodaje się nowy item a nasz scroll)
// mockData.add(mockData.size(), new Model(mockData.size()+1, "Nowy item nr. " + (mockData.size()+1), "opis"));
// adapter.notifyItemInserted(mockData.size());
// //Dodany scroll do nowej pozycji -1, dlatego ze indeksujemy przeciez od 0 a nie od 1 i po prostu probowalibysmy
// //wskoczyc na miejsce nie istniejace - co mnei dziwi tutaj, ze nie leci zaden exception w takim wypadku?
// recyclerView.scrollToPosition(mockData.size()-1);
//Lub na początek: (zwrócmy uwage, że to nam nie scrolluje, tylko dodaje się nowy item a nasz scroll)
//na liście jest dalej w tym samym miejscu
mockData.add(0, new Model(mockData.size()+1, "Nowy item nr. " + (mockData.size()+1), "opis"));
adapter.notifyItemInserted(0);
recyclerView.scrollToPosition(0);
}
private void addNewItemWithRangeChanged(){
//Lub jeszcze inaczej, jak chcemy dodać więcej niż 1 elementów to najlepiej tak:
int curSize = adapter.getItemCount();
ArrayList<Model> newItems = new ArrayList<>();
for (int i = curSize; i < curSize+6; i++){
newItems.add(new Model(i+1, "numer " + (i+1), "opis"));
}
mockData.addAll(newItems);
adapter.notifyItemRangeChanged(curSize, newItems.size());
recyclerView.scrollToPosition(curSize);
}
private void sortItemsWithDiffUtil(){
List<Model> models = new ArrayList<>();
models.addAll(mockData);
Collections.sort(models, new Comparator<Model>() {
@Override
public int compare(Model model, Model t1) {
return model.getId() - t1.getId();
}
});
adapter.updateSortedList(models);
}
/***
* Tutaj mamy przykład wywołania DiffUtil do zmiany listy. Uzywac jak chcemy wiecej elemtnow dodac
*/
private void addNewItemWithDiffUtil(){
int curSize = adapter.getItemCount();
ArrayList<Model> newItems = new ArrayList<>();
for (int i = curSize; i < curSize+6; i++){
newItems.add(new Model(i+1, "numer " + (i+1), "opis"));
}
adapter.diffUtilTest(newItems);
}
private void deleteItem(int position){
mockData.remove(position);
// adapter.notifyDataSetChanged();
adapter.notifyItemRemoved(position);
// Albo jak byśmy przekazali obiekt Model jako parametr metody
// int position = list.indexOf(model);
// list.remove(position);
// notifyItemRemoved(position);
}
// private void diffUtilTest(List<Model> modelList){
// RecyclerViewDiffUtilCallback callback = new RecyclerViewDiffUtilCallback(this.mockData, modelList);
// DiffUtil.DiffResult result = DiffUtil.calculateDiff(callback);
//
// this.mockData.clear();
// this.mockData.addAll(modelList);
// result.dispatchUpdatesTo(adapter);
// }
}
// //Doda nam nowy item na dole listy - (zwrócmy uwage, że to nam nie scrolluje, tylko dodaje się nowy item a nasz scroll)
//// mockData.add(new Model(13, "Nowy item nr. " + (mockData.size()+1), "opis"));
////// adapter.notifyDataSetChanged();
//// adapter.notifyItemInserted(mockData.size()+1);
//
//
// //Lub na początek: (zwrócmy uwage, że to nam nie scrolluje, tylko dodaje się nowy item a nasz scroll)
// //na liście jest dalej w tym samym miejscu
//// mockData.add(0, new Model(13, "Nowy item nr. " + (mockData.size()+1), "opis"));
//// adapter.notifyItemInserted(0);
//
//
// //Lub jeszcze inaczej, jak chcemy dodać więcej niż 1 elementów to najlepiej tak:
// int curSize<SUF>
//
// ArrayList<Model> newItems = new ArrayList<>();
// for (int i = curSize; i < curSize+6; i++){
// newItems.add(new Model(i+1, "numer " + (i+1), "opis"));
// }
// //zakomentowane zeby sprawdic diffUtil.
//// mockData.addAll(newItems);
//// adapter.notifyItemRangeChanged(curSize, newItems.size());
//
// /***
// * Tutaj mamy przykład wywołania DiffUtil do zmiany listy.
// */
// adapter.diffUtilTest(newItems); |
105237_1 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.pepsoft.worldpainter.layers.exporters;
import com.google.common.collect.ImmutableMap;
import org.pepsoft.minecraft.Chunk;
import org.pepsoft.minecraft.Material;
import org.pepsoft.util.PerlinNoise;
import org.pepsoft.worldpainter.Dimension;
import org.pepsoft.worldpainter.Platform;
import org.pepsoft.worldpainter.Tile;
import org.pepsoft.worldpainter.exporting.AbstractLayerExporter;
import org.pepsoft.worldpainter.exporting.FirstPassLayerExporter;
import org.pepsoft.worldpainter.layers.Resources;
import org.pepsoft.worldpainter.layers.Void;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.*;
import static org.pepsoft.minecraft.Constants.*;
import static org.pepsoft.minecraft.Material.*;
import static org.pepsoft.worldpainter.Constants.*;
import static org.pepsoft.worldpainter.DefaultPlugin.*;
import static org.pepsoft.worldpainter.layers.exporters.ResourcesExporter.ResourcesExporterSettings.defaultSettings;
/**
*
* @author pepijn
*/
public class ResourcesExporter extends AbstractLayerExporter<Resources> implements FirstPassLayerExporter {
public ResourcesExporter() {
super(Resources.INSTANCE);
}
@Override
public void setSettings(ExporterSettings settings) {
super.setSettings(settings);
ResourcesExporterSettings resourcesSettings = (ResourcesExporterSettings) getSettings();
if (resourcesSettings != null) {
Set<Material> allMaterials = resourcesSettings.getMaterials();
List<Material> activeMaterials = new ArrayList<>(allMaterials.size());
for (Material material: allMaterials) {
if (resourcesSettings.getChance(material) > 0) {
activeMaterials.add(material);
}
}
this.activeMaterials = activeMaterials.toArray(new Material[activeMaterials.size()]);
noiseGenerators = new PerlinNoise[this.activeMaterials.length];
seedOffsets = new long[this.activeMaterials.length];
minLevels = new int[this.activeMaterials.length];
maxLevels = new int[this.activeMaterials.length];
chances = new float[this.activeMaterials.length][16];
for (int i = 0; i < this.activeMaterials.length; i++) {
noiseGenerators[i] = new PerlinNoise(0);
seedOffsets[i] = resourcesSettings.getSeedOffset(this.activeMaterials[i]);
minLevels[i] = resourcesSettings.getMinLevel(this.activeMaterials[i]);
maxLevels[i] = resourcesSettings.getMaxLevel(this.activeMaterials[i]);
chances[i] = new float[16];
for (int j = 0; j < 16; j++) {
chances[i][j] = PerlinNoise.getLevelForPromillage(Math.min(resourcesSettings.getChance(this.activeMaterials[i]) * j / 8f, 1000f));
}
}
}
}
@Override
public void render(Dimension dimension, Tile tile, Chunk chunk, Platform platform) {
ResourcesExporterSettings settings = (ResourcesExporterSettings) getSettings();
if (settings == null) {
settings = defaultSettings(platform, dimension.getDim(), dimension.getMaxHeight());
setSettings(settings);
}
final int minimumLevel = settings.getMinimumLevel();
final int xOffset = (chunk.getxPos() & 7) << 4;
final int zOffset = (chunk.getzPos() & 7) << 4;
final long seed = dimension.getSeed();
final int minY = dimension.getMinHeight(), maxY = dimension.getMaxHeight() - 1;
final boolean coverSteepTerrain = dimension.isCoverSteepTerrain(), nether = (dimension.getDim() == DIM_NETHER);
if ((currentSeed == 0) || (currentSeed != seed)) {
for (int i = 0; i < activeMaterials.length; i++) {
if (noiseGenerators[i].getSeed() != (seed + seedOffsets[i])) {
noiseGenerators[i].setSeed(seed + seedOffsets[i]);
}
}
currentSeed = seed;
}
// int[] counts = new int[256];
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
final int localX = xOffset + x, localY = zOffset + z;
final int worldX = tile.getX() * TILE_SIZE + localX, worldY = tile.getY() * TILE_SIZE + localY;
if (tile.getBitLayerValue(Void.INSTANCE, localX, localY)) {
continue;
}
final int resourcesValue = Math.max(minimumLevel, tile.getLayerValue(Resources.INSTANCE, localX, localY));
if (resourcesValue > 0) {
final int terrainheight = tile.getIntHeight(localX, localY);
final int topLayerDepth = dimension.getTopLayerDepth(worldX, worldY, terrainheight);
int subsurfaceMaxHeight = terrainheight - topLayerDepth;
if (coverSteepTerrain) {
subsurfaceMaxHeight = Math.min(subsurfaceMaxHeight,
Math.min(Math.min(dimension.getIntHeightAt(worldX - 1, worldY, Integer.MAX_VALUE),
dimension.getIntHeightAt(worldX + 1, worldY, Integer.MAX_VALUE)),
Math.min(dimension.getIntHeightAt(worldX, worldY - 1, Integer.MAX_VALUE),
dimension.getIntHeightAt(worldX, worldY + 1, Integer.MAX_VALUE))));
}
final double dx = worldX / TINY_BLOBS, dy = worldY / TINY_BLOBS;
final double dirtX = worldX / SMALL_BLOBS, dirtY = worldY / SMALL_BLOBS;
// Capping to maxY really shouldn't be necessary, but we've
// had several reports from the wild of this going higher
// than maxHeight, so there must be some obscure way in
// which the terrainHeight can be raised too high
for (int y = Math.min(subsurfaceMaxHeight, maxY); y > minY; y--) {
final double dz = y / TINY_BLOBS;
final double dirtZ = y / SMALL_BLOBS;
for (int i = 0; i < activeMaterials.length; i++) {
final float chance = chances[i][resourcesValue];
if ((chance <= 0.5f)
&& (y >= minLevels[i])
&& (y <= maxLevels[i])
&& (activeMaterials[i].isNamedOneOf(MC_DIRT, MC_GRAVEL)
? (noiseGenerators[i].getPerlinNoise(dirtX, dirtY, dirtZ) >= chance)
: (noiseGenerators[i].getPerlinNoise(dx, dy, dz) >= chance))) {
// counts[oreType]++;
final Material existingMaterial = chunk.getMaterial(x, y, z);
if (existingMaterial.isNamed(MC_DEEPSLATE) && ORE_TO_DEEPSLATE_VARIANT.containsKey(activeMaterials[i].name)) {
chunk.setMaterial(x, y, z, ORE_TO_DEEPSLATE_VARIANT.get(activeMaterials[i].name));
} else if (nether && (activeMaterials[i].isNamed(MC_GOLD_ORE))) {
chunk.setMaterial(x, y, z, NETHER_GOLD_ORE);
} else {
chunk.setMaterial(x, y, z, activeMaterials[i]);
}
break;
}
}
}
}
}
}
// System.out.println("Tile " + tile.getX() + "," + tile.getY());
// for (i = 0; i < 256; i++) {
// if (counts[i] > 0) {
// System.out.printf("Exported %6d of ore type %3d%n", counts[i], i);
// }
// }
// System.out.println();
}
// TODO: resource frequenties onderzoeken met Statistics tool!
private Material[] activeMaterials;
private PerlinNoise[] noiseGenerators;
private long[] seedOffsets;
private int[] minLevels, maxLevels;
private float[][] chances;
private long currentSeed;
private static final Map<String, Material> ORE_TO_DEEPSLATE_VARIANT = ImmutableMap.of(
MC_COAL_ORE, DEEPSLATE_COAL_ORE,
MC_COPPER_ORE, DEEPSLATE_COPPER_ORE,
MC_LAPIS_ORE, DEEPSLATE_LAPIS_ORE,
MC_IRON_ORE, DEEPSLATE_IRON_ORE,
MC_GOLD_ORE, DEEPSLATE_GOLD_ORE,
MC_REDSTONE_ORE, DEEPSLATE_REDSTONE_ORE,
MC_DIAMOND_ORE, DEEPSLATE_DIAMOND_ORE,
MC_EMERALD_ORE, DEEPSLATE_EMERALD_ORE
);
public static class ResourcesExporterSettings implements ExporterSettings {
private ResourcesExporterSettings(Map<Material, ResourceSettings> settings) {
this.settings = settings;
}
@Override
public boolean isApplyEverywhere() {
return minimumLevel > 0;
}
public int getMinimumLevel() {
return minimumLevel;
}
public void setMinimumLevel(int minimumLevel) {
this.minimumLevel = minimumLevel;
}
public Set<Material> getMaterials() {
return settings.keySet();
}
public int getMinLevel(Material material) {
return settings.get(material).minLevel;
}
public void setMinLevel(Material material, int minLevel) {
settings.get(material).minLevel = minLevel;
}
public int getMaxLevel(Material material) {
return settings.get(material).maxLevel;
}
public void setMaxLevel(Material material, int maxLevel) {
settings.get(material).maxLevel = maxLevel;
}
public int getChance(Material material) {
return settings.get(material).chance;
}
public void setChance(Material material, int chance) {
settings.get(material).chance = chance;
}
public long getSeedOffset(Material material) {
return settings.get(material).seedOffset;
}
@Override
public Resources getLayer() {
return Resources.INSTANCE;
}
@Override
public ResourcesExporterSettings clone() {
try {
ResourcesExporterSettings clone = (ResourcesExporterSettings) super.clone();
clone.settings = new LinkedHashMap<>();
settings.forEach((material, settings) -> clone.settings.put(material, settings.clone()));
return clone;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
public static ResourcesExporterSettings defaultSettings(Platform platform, int dim, int maxHeight) {
final Random random = new Random();
final Map<Material, ResourceSettings> settings = new HashMap<>();
switch (dim) {
case DIM_NORMAL:
// TODO make these normal distributions or something else more similar to Minecraft
settings.put(DIRT, new ResourceSettings(DIRT, 0 , maxHeight - 1, 57, random.nextLong()));
settings.put(GRAVEL, new ResourceSettings(GRAVEL, platform.minZ, maxHeight - 1, 28, random.nextLong()));
settings.put(GOLD_ORE, new ResourceSettings(GOLD_ORE, platform.minZ, 31, 1, random.nextLong()));
settings.put(IRON_ORE, new ResourceSettings(IRON_ORE, platform.minZ, maxHeight - 1, 6, random.nextLong()));
settings.put(COAL, new ResourceSettings(COAL, 0 , maxHeight - 1, 10, random.nextLong()));
settings.put(LAPIS_LAZULI_ORE, new ResourceSettings(LAPIS_LAZULI_ORE, platform.minZ, 31, 1, random.nextLong()));
settings.put(DIAMOND_ORE, new ResourceSettings(DIAMOND_ORE, platform.minZ, 15, 1, random.nextLong()));
settings.put(REDSTONE_ORE, new ResourceSettings(REDSTONE_ORE, platform.minZ, 15, 8, random.nextLong()));
settings.put(WATER, new ResourceSettings(WATER, platform.minZ, maxHeight - 1, 1, random.nextLong()));
settings.put(LAVA, new ResourceSettings(LAVA, platform.minZ, 15, 2, random.nextLong()));
settings.put(EMERALD_ORE, new ResourceSettings(EMERALD_ORE, 64, maxHeight - 1, (platform != JAVA_MCREGION) ?
1 : 0, random.nextLong()));
settings.put(COPPER_ORE, new ResourceSettings(COPPER_ORE, 0, 88, ((platform == JAVA_ANVIL_1_17) || (platform == JAVA_ANVIL_1_18)) ?
6 : 0, random.nextLong()));
settings.put(QUARTZ_ORE, new ResourceSettings(QUARTZ_ORE, platform.minZ, maxHeight - 1, 0, random.nextLong()));
settings.put(ANCIENT_DEBRIS, new ResourceSettings(ANCIENT_DEBRIS, platform.minZ, maxHeight - 1, 0, random.nextLong()));
break;
case DIM_NETHER:
settings.put(QUARTZ_ORE, new ResourceSettings(QUARTZ_ORE, platform.minZ, maxHeight - 1, (platform != JAVA_MCREGION) ?
7 : 0, random.nextLong()));
settings.put(GOLD_ORE, new ResourceSettings(GOLD_ORE, platform.minZ, maxHeight - 1, ((platform == JAVA_ANVIL_1_15) || (platform == JAVA_ANVIL_1_17) || (platform == JAVA_ANVIL_1_18)) ?
3 : 0, random.nextLong()));
settings.put(ANCIENT_DEBRIS, new ResourceSettings(ANCIENT_DEBRIS, platform.minZ, maxHeight - 1, ((platform == JAVA_ANVIL_1_15) || (platform == JAVA_ANVIL_1_17) || (platform == JAVA_ANVIL_1_18)) ?
1 : 0, random.nextLong()));
settings.put(DIRT, new ResourceSettings(DIRT, 0 , maxHeight - 1, 0, random.nextLong()));
settings.put(GRAVEL, new ResourceSettings(GRAVEL, platform.minZ, maxHeight - 1, 0, random.nextLong()));
settings.put(IRON_ORE, new ResourceSettings(IRON_ORE, platform.minZ, maxHeight - 1, 0, random.nextLong()));
settings.put(COAL, new ResourceSettings(COAL, 0 , maxHeight - 1, 0, random.nextLong()));
settings.put(LAPIS_LAZULI_ORE, new ResourceSettings(LAPIS_LAZULI_ORE, platform.minZ, 31, 0, random.nextLong()));
settings.put(DIAMOND_ORE, new ResourceSettings(DIAMOND_ORE, platform.minZ, 15, 0, random.nextLong()));
settings.put(REDSTONE_ORE, new ResourceSettings(REDSTONE_ORE, platform.minZ, 15, 0, random.nextLong()));
settings.put(WATER, new ResourceSettings(WATER, platform.minZ, maxHeight - 1, 0, random.nextLong()));
settings.put(LAVA, new ResourceSettings(LAVA, platform.minZ, 15, 0, random.nextLong()));
settings.put(EMERALD_ORE, new ResourceSettings(EMERALD_ORE, 64, maxHeight - 1, 0, random.nextLong()));
settings.put(COPPER_ORE, new ResourceSettings(COPPER_ORE, 0, 88, 0, random.nextLong()));
break;
case DIM_END:
settings.put(DIRT, new ResourceSettings(DIRT, 0 , maxHeight - 1, 0, random.nextLong()));
settings.put(GRAVEL, new ResourceSettings(GRAVEL, platform.minZ, maxHeight - 1, 0, random.nextLong()));
settings.put(GOLD_ORE, new ResourceSettings(GOLD_ORE, platform.minZ, 31, 0, random.nextLong()));
settings.put(IRON_ORE, new ResourceSettings(IRON_ORE, platform.minZ, maxHeight - 1, 0, random.nextLong()));
settings.put(COAL, new ResourceSettings(COAL, 0 , maxHeight - 1, 0, random.nextLong()));
settings.put(LAPIS_LAZULI_ORE, new ResourceSettings(LAPIS_LAZULI_ORE, platform.minZ, 31, 0, random.nextLong()));
settings.put(DIAMOND_ORE, new ResourceSettings(DIAMOND_ORE, platform.minZ, 15, 0, random.nextLong()));
settings.put(REDSTONE_ORE, new ResourceSettings(REDSTONE_ORE, platform.minZ, 15, 0, random.nextLong()));
settings.put(WATER, new ResourceSettings(WATER, platform.minZ, maxHeight - 1, 0, random.nextLong()));
settings.put(LAVA, new ResourceSettings(LAVA, platform.minZ, 15, 0, random.nextLong()));
settings.put(EMERALD_ORE, new ResourceSettings(EMERALD_ORE, 64, maxHeight - 1, 0, random.nextLong()));
settings.put(COPPER_ORE, new ResourceSettings(COPPER_ORE, 0, 88, 0, random.nextLong()));
settings.put(QUARTZ_ORE, new ResourceSettings(QUARTZ_ORE, platform.minZ, maxHeight - 1, 0, random.nextLong()));
settings.put(ANCIENT_DEBRIS, new ResourceSettings(ANCIENT_DEBRIS, platform.minZ, maxHeight - 1, 0, random.nextLong()));
break;
default:
throw new IllegalArgumentException("Dimension " + dim + " not supported");
}
return new ResourcesExporterSettings(settings);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
if (version < 1) {
// Legacy conversions
// Fix static water and lava
if (! maxLevels.containsKey(BLK_WATER)) {
logger.warn("Fixing water and lava settings");
maxLevels.put(BLK_WATER, maxLevels.get(BLK_STATIONARY_WATER));
chances.put(BLK_WATER, chances.get(BLK_STATIONARY_WATER));
seedOffsets.put(BLK_WATER, seedOffsets.get(BLK_STATIONARY_WATER));
maxLevels.put(BLK_LAVA, maxLevels.get(BLK_STATIONARY_LAVA));
chances.put(BLK_LAVA, chances.get(BLK_STATIONARY_LAVA));
seedOffsets.put(BLK_LAVA, seedOffsets.get(BLK_STATIONARY_LAVA));
maxLevels.remove(BLK_STATIONARY_WATER);
chances.remove(BLK_STATIONARY_WATER);
seedOffsets.remove(BLK_STATIONARY_WATER);
maxLevels.remove(BLK_STATIONARY_LAVA);
chances.remove(BLK_STATIONARY_LAVA);
seedOffsets.remove(BLK_STATIONARY_LAVA);
}
if (! maxLevels.containsKey(BLK_EMERALD_ORE)) {
maxLevels.put(BLK_EMERALD_ORE, 31);
chances.put(BLK_EMERALD_ORE, 0);
}
Random random = new Random();
if (! seedOffsets.containsKey(BLK_EMERALD_ORE)) {
seedOffsets.put(BLK_EMERALD_ORE, random.nextLong());
}
if (minLevels == null) {
minLevels = new HashMap<>();
for (int blockType: maxLevels.keySet()) {
minLevels.put(blockType, 0);
}
}
if (! minLevels.containsKey(BLK_QUARTZ_ORE)) {
minLevels.put(BLK_QUARTZ_ORE, 0);
maxLevels.put(BLK_QUARTZ_ORE, 255);
chances.put(BLK_QUARTZ_ORE, 0);
seedOffsets.put(BLK_QUARTZ_ORE, random.nextLong());
}
// Convert integer-based settings to material-based settings
settings = new LinkedHashMap<>();
for (int blockType: maxLevels.keySet()) {
Material material = get(blockType);
settings.put(material, new ResourceSettings(material, minLevels.get(blockType), maxLevels.get(blockType),
chances.get(blockType), seedOffsets.get(blockType)));
}
minLevels = null;
maxLevels = null;
chances = null;
seedOffsets = null;
}
if (version < 2) {
// Add new resources
final Random random = new Random();
settings.put(COPPER_ORE, new ResourceSettings(COPPER_ORE, 0, 88, 0, random.nextLong()));
settings.put(ANCIENT_DEBRIS, new ResourceSettings(ANCIENT_DEBRIS, -64, 319, 0, random.nextLong()));
}
version = 2;
// Not sure how, but the liquids are reverting to the stationary
// variants (something to do with the Minecraft 1.14 migration?).
// Just keep changing them back
if (settings.containsKey(STATIONARY_WATER)) {
settings.put(WATER, settings.get(STATIONARY_WATER));
settings.remove(STATIONARY_WATER);
}
if (settings.containsKey(STATIONARY_LAVA)) {
settings.put(LAVA, settings.get(STATIONARY_LAVA));
settings.remove(STATIONARY_LAVA);
}
}
private int minimumLevel = 8;
private Map<Material, ResourceSettings> settings = new LinkedHashMap<>();
/** @deprecated */
private Map<Integer, Integer> maxLevels = null;
/** @deprecated */
private Map<Integer, Integer> chances = null;
/** @deprecated */
private Map<Integer, Long> seedOffsets = null;
/** @deprecated */
private Map<Integer, Integer> minLevels = null;
private int version = 1;
private static final long serialVersionUID = 1L;
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ResourcesExporter.class);
}
static class ResourceSettings implements Serializable, Cloneable {
ResourceSettings(Material material, int minLevel, int maxLevel, int chance, long seedOffset) {
this.material = material;
this.minLevel = minLevel;
this.maxLevel = maxLevel;
this.chance = chance;
this.seedOffset = seedOffset;
}
@Override
public ResourceSettings clone() {
try {
return (ResourceSettings) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
Material material;
int minLevel, maxLevel, chance;
long seedOffset;
private static final long serialVersionUID = 1L;
}
} | Malfrador/WorldPainter | WorldPainter/WPCore/src/main/java/org/pepsoft/worldpainter/layers/exporters/ResourcesExporter.java | 6,841 | /**
*
* @author pepijn
*/ | block_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.pepsoft.worldpainter.layers.exporters;
import com.google.common.collect.ImmutableMap;
import org.pepsoft.minecraft.Chunk;
import org.pepsoft.minecraft.Material;
import org.pepsoft.util.PerlinNoise;
import org.pepsoft.worldpainter.Dimension;
import org.pepsoft.worldpainter.Platform;
import org.pepsoft.worldpainter.Tile;
import org.pepsoft.worldpainter.exporting.AbstractLayerExporter;
import org.pepsoft.worldpainter.exporting.FirstPassLayerExporter;
import org.pepsoft.worldpainter.layers.Resources;
import org.pepsoft.worldpainter.layers.Void;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.*;
import static org.pepsoft.minecraft.Constants.*;
import static org.pepsoft.minecraft.Material.*;
import static org.pepsoft.worldpainter.Constants.*;
import static org.pepsoft.worldpainter.DefaultPlugin.*;
import static org.pepsoft.worldpainter.layers.exporters.ResourcesExporter.ResourcesExporterSettings.defaultSettings;
/**
*
* @author pepijn
<SUF>*/
public class ResourcesExporter extends AbstractLayerExporter<Resources> implements FirstPassLayerExporter {
public ResourcesExporter() {
super(Resources.INSTANCE);
}
@Override
public void setSettings(ExporterSettings settings) {
super.setSettings(settings);
ResourcesExporterSettings resourcesSettings = (ResourcesExporterSettings) getSettings();
if (resourcesSettings != null) {
Set<Material> allMaterials = resourcesSettings.getMaterials();
List<Material> activeMaterials = new ArrayList<>(allMaterials.size());
for (Material material: allMaterials) {
if (resourcesSettings.getChance(material) > 0) {
activeMaterials.add(material);
}
}
this.activeMaterials = activeMaterials.toArray(new Material[activeMaterials.size()]);
noiseGenerators = new PerlinNoise[this.activeMaterials.length];
seedOffsets = new long[this.activeMaterials.length];
minLevels = new int[this.activeMaterials.length];
maxLevels = new int[this.activeMaterials.length];
chances = new float[this.activeMaterials.length][16];
for (int i = 0; i < this.activeMaterials.length; i++) {
noiseGenerators[i] = new PerlinNoise(0);
seedOffsets[i] = resourcesSettings.getSeedOffset(this.activeMaterials[i]);
minLevels[i] = resourcesSettings.getMinLevel(this.activeMaterials[i]);
maxLevels[i] = resourcesSettings.getMaxLevel(this.activeMaterials[i]);
chances[i] = new float[16];
for (int j = 0; j < 16; j++) {
chances[i][j] = PerlinNoise.getLevelForPromillage(Math.min(resourcesSettings.getChance(this.activeMaterials[i]) * j / 8f, 1000f));
}
}
}
}
@Override
public void render(Dimension dimension, Tile tile, Chunk chunk, Platform platform) {
ResourcesExporterSettings settings = (ResourcesExporterSettings) getSettings();
if (settings == null) {
settings = defaultSettings(platform, dimension.getDim(), dimension.getMaxHeight());
setSettings(settings);
}
final int minimumLevel = settings.getMinimumLevel();
final int xOffset = (chunk.getxPos() & 7) << 4;
final int zOffset = (chunk.getzPos() & 7) << 4;
final long seed = dimension.getSeed();
final int minY = dimension.getMinHeight(), maxY = dimension.getMaxHeight() - 1;
final boolean coverSteepTerrain = dimension.isCoverSteepTerrain(), nether = (dimension.getDim() == DIM_NETHER);
if ((currentSeed == 0) || (currentSeed != seed)) {
for (int i = 0; i < activeMaterials.length; i++) {
if (noiseGenerators[i].getSeed() != (seed + seedOffsets[i])) {
noiseGenerators[i].setSeed(seed + seedOffsets[i]);
}
}
currentSeed = seed;
}
// int[] counts = new int[256];
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
final int localX = xOffset + x, localY = zOffset + z;
final int worldX = tile.getX() * TILE_SIZE + localX, worldY = tile.getY() * TILE_SIZE + localY;
if (tile.getBitLayerValue(Void.INSTANCE, localX, localY)) {
continue;
}
final int resourcesValue = Math.max(minimumLevel, tile.getLayerValue(Resources.INSTANCE, localX, localY));
if (resourcesValue > 0) {
final int terrainheight = tile.getIntHeight(localX, localY);
final int topLayerDepth = dimension.getTopLayerDepth(worldX, worldY, terrainheight);
int subsurfaceMaxHeight = terrainheight - topLayerDepth;
if (coverSteepTerrain) {
subsurfaceMaxHeight = Math.min(subsurfaceMaxHeight,
Math.min(Math.min(dimension.getIntHeightAt(worldX - 1, worldY, Integer.MAX_VALUE),
dimension.getIntHeightAt(worldX + 1, worldY, Integer.MAX_VALUE)),
Math.min(dimension.getIntHeightAt(worldX, worldY - 1, Integer.MAX_VALUE),
dimension.getIntHeightAt(worldX, worldY + 1, Integer.MAX_VALUE))));
}
final double dx = worldX / TINY_BLOBS, dy = worldY / TINY_BLOBS;
final double dirtX = worldX / SMALL_BLOBS, dirtY = worldY / SMALL_BLOBS;
// Capping to maxY really shouldn't be necessary, but we've
// had several reports from the wild of this going higher
// than maxHeight, so there must be some obscure way in
// which the terrainHeight can be raised too high
for (int y = Math.min(subsurfaceMaxHeight, maxY); y > minY; y--) {
final double dz = y / TINY_BLOBS;
final double dirtZ = y / SMALL_BLOBS;
for (int i = 0; i < activeMaterials.length; i++) {
final float chance = chances[i][resourcesValue];
if ((chance <= 0.5f)
&& (y >= minLevels[i])
&& (y <= maxLevels[i])
&& (activeMaterials[i].isNamedOneOf(MC_DIRT, MC_GRAVEL)
? (noiseGenerators[i].getPerlinNoise(dirtX, dirtY, dirtZ) >= chance)
: (noiseGenerators[i].getPerlinNoise(dx, dy, dz) >= chance))) {
// counts[oreType]++;
final Material existingMaterial = chunk.getMaterial(x, y, z);
if (existingMaterial.isNamed(MC_DEEPSLATE) && ORE_TO_DEEPSLATE_VARIANT.containsKey(activeMaterials[i].name)) {
chunk.setMaterial(x, y, z, ORE_TO_DEEPSLATE_VARIANT.get(activeMaterials[i].name));
} else if (nether && (activeMaterials[i].isNamed(MC_GOLD_ORE))) {
chunk.setMaterial(x, y, z, NETHER_GOLD_ORE);
} else {
chunk.setMaterial(x, y, z, activeMaterials[i]);
}
break;
}
}
}
}
}
}
// System.out.println("Tile " + tile.getX() + "," + tile.getY());
// for (i = 0; i < 256; i++) {
// if (counts[i] > 0) {
// System.out.printf("Exported %6d of ore type %3d%n", counts[i], i);
// }
// }
// System.out.println();
}
// TODO: resource frequenties onderzoeken met Statistics tool!
private Material[] activeMaterials;
private PerlinNoise[] noiseGenerators;
private long[] seedOffsets;
private int[] minLevels, maxLevels;
private float[][] chances;
private long currentSeed;
private static final Map<String, Material> ORE_TO_DEEPSLATE_VARIANT = ImmutableMap.of(
MC_COAL_ORE, DEEPSLATE_COAL_ORE,
MC_COPPER_ORE, DEEPSLATE_COPPER_ORE,
MC_LAPIS_ORE, DEEPSLATE_LAPIS_ORE,
MC_IRON_ORE, DEEPSLATE_IRON_ORE,
MC_GOLD_ORE, DEEPSLATE_GOLD_ORE,
MC_REDSTONE_ORE, DEEPSLATE_REDSTONE_ORE,
MC_DIAMOND_ORE, DEEPSLATE_DIAMOND_ORE,
MC_EMERALD_ORE, DEEPSLATE_EMERALD_ORE
);
public static class ResourcesExporterSettings implements ExporterSettings {
private ResourcesExporterSettings(Map<Material, ResourceSettings> settings) {
this.settings = settings;
}
@Override
public boolean isApplyEverywhere() {
return minimumLevel > 0;
}
public int getMinimumLevel() {
return minimumLevel;
}
public void setMinimumLevel(int minimumLevel) {
this.minimumLevel = minimumLevel;
}
public Set<Material> getMaterials() {
return settings.keySet();
}
public int getMinLevel(Material material) {
return settings.get(material).minLevel;
}
public void setMinLevel(Material material, int minLevel) {
settings.get(material).minLevel = minLevel;
}
public int getMaxLevel(Material material) {
return settings.get(material).maxLevel;
}
public void setMaxLevel(Material material, int maxLevel) {
settings.get(material).maxLevel = maxLevel;
}
public int getChance(Material material) {
return settings.get(material).chance;
}
public void setChance(Material material, int chance) {
settings.get(material).chance = chance;
}
public long getSeedOffset(Material material) {
return settings.get(material).seedOffset;
}
@Override
public Resources getLayer() {
return Resources.INSTANCE;
}
@Override
public ResourcesExporterSettings clone() {
try {
ResourcesExporterSettings clone = (ResourcesExporterSettings) super.clone();
clone.settings = new LinkedHashMap<>();
settings.forEach((material, settings) -> clone.settings.put(material, settings.clone()));
return clone;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
public static ResourcesExporterSettings defaultSettings(Platform platform, int dim, int maxHeight) {
final Random random = new Random();
final Map<Material, ResourceSettings> settings = new HashMap<>();
switch (dim) {
case DIM_NORMAL:
// TODO make these normal distributions or something else more similar to Minecraft
settings.put(DIRT, new ResourceSettings(DIRT, 0 , maxHeight - 1, 57, random.nextLong()));
settings.put(GRAVEL, new ResourceSettings(GRAVEL, platform.minZ, maxHeight - 1, 28, random.nextLong()));
settings.put(GOLD_ORE, new ResourceSettings(GOLD_ORE, platform.minZ, 31, 1, random.nextLong()));
settings.put(IRON_ORE, new ResourceSettings(IRON_ORE, platform.minZ, maxHeight - 1, 6, random.nextLong()));
settings.put(COAL, new ResourceSettings(COAL, 0 , maxHeight - 1, 10, random.nextLong()));
settings.put(LAPIS_LAZULI_ORE, new ResourceSettings(LAPIS_LAZULI_ORE, platform.minZ, 31, 1, random.nextLong()));
settings.put(DIAMOND_ORE, new ResourceSettings(DIAMOND_ORE, platform.minZ, 15, 1, random.nextLong()));
settings.put(REDSTONE_ORE, new ResourceSettings(REDSTONE_ORE, platform.minZ, 15, 8, random.nextLong()));
settings.put(WATER, new ResourceSettings(WATER, platform.minZ, maxHeight - 1, 1, random.nextLong()));
settings.put(LAVA, new ResourceSettings(LAVA, platform.minZ, 15, 2, random.nextLong()));
settings.put(EMERALD_ORE, new ResourceSettings(EMERALD_ORE, 64, maxHeight - 1, (platform != JAVA_MCREGION) ?
1 : 0, random.nextLong()));
settings.put(COPPER_ORE, new ResourceSettings(COPPER_ORE, 0, 88, ((platform == JAVA_ANVIL_1_17) || (platform == JAVA_ANVIL_1_18)) ?
6 : 0, random.nextLong()));
settings.put(QUARTZ_ORE, new ResourceSettings(QUARTZ_ORE, platform.minZ, maxHeight - 1, 0, random.nextLong()));
settings.put(ANCIENT_DEBRIS, new ResourceSettings(ANCIENT_DEBRIS, platform.minZ, maxHeight - 1, 0, random.nextLong()));
break;
case DIM_NETHER:
settings.put(QUARTZ_ORE, new ResourceSettings(QUARTZ_ORE, platform.minZ, maxHeight - 1, (platform != JAVA_MCREGION) ?
7 : 0, random.nextLong()));
settings.put(GOLD_ORE, new ResourceSettings(GOLD_ORE, platform.minZ, maxHeight - 1, ((platform == JAVA_ANVIL_1_15) || (platform == JAVA_ANVIL_1_17) || (platform == JAVA_ANVIL_1_18)) ?
3 : 0, random.nextLong()));
settings.put(ANCIENT_DEBRIS, new ResourceSettings(ANCIENT_DEBRIS, platform.minZ, maxHeight - 1, ((platform == JAVA_ANVIL_1_15) || (platform == JAVA_ANVIL_1_17) || (platform == JAVA_ANVIL_1_18)) ?
1 : 0, random.nextLong()));
settings.put(DIRT, new ResourceSettings(DIRT, 0 , maxHeight - 1, 0, random.nextLong()));
settings.put(GRAVEL, new ResourceSettings(GRAVEL, platform.minZ, maxHeight - 1, 0, random.nextLong()));
settings.put(IRON_ORE, new ResourceSettings(IRON_ORE, platform.minZ, maxHeight - 1, 0, random.nextLong()));
settings.put(COAL, new ResourceSettings(COAL, 0 , maxHeight - 1, 0, random.nextLong()));
settings.put(LAPIS_LAZULI_ORE, new ResourceSettings(LAPIS_LAZULI_ORE, platform.minZ, 31, 0, random.nextLong()));
settings.put(DIAMOND_ORE, new ResourceSettings(DIAMOND_ORE, platform.minZ, 15, 0, random.nextLong()));
settings.put(REDSTONE_ORE, new ResourceSettings(REDSTONE_ORE, platform.minZ, 15, 0, random.nextLong()));
settings.put(WATER, new ResourceSettings(WATER, platform.minZ, maxHeight - 1, 0, random.nextLong()));
settings.put(LAVA, new ResourceSettings(LAVA, platform.minZ, 15, 0, random.nextLong()));
settings.put(EMERALD_ORE, new ResourceSettings(EMERALD_ORE, 64, maxHeight - 1, 0, random.nextLong()));
settings.put(COPPER_ORE, new ResourceSettings(COPPER_ORE, 0, 88, 0, random.nextLong()));
break;
case DIM_END:
settings.put(DIRT, new ResourceSettings(DIRT, 0 , maxHeight - 1, 0, random.nextLong()));
settings.put(GRAVEL, new ResourceSettings(GRAVEL, platform.minZ, maxHeight - 1, 0, random.nextLong()));
settings.put(GOLD_ORE, new ResourceSettings(GOLD_ORE, platform.minZ, 31, 0, random.nextLong()));
settings.put(IRON_ORE, new ResourceSettings(IRON_ORE, platform.minZ, maxHeight - 1, 0, random.nextLong()));
settings.put(COAL, new ResourceSettings(COAL, 0 , maxHeight - 1, 0, random.nextLong()));
settings.put(LAPIS_LAZULI_ORE, new ResourceSettings(LAPIS_LAZULI_ORE, platform.minZ, 31, 0, random.nextLong()));
settings.put(DIAMOND_ORE, new ResourceSettings(DIAMOND_ORE, platform.minZ, 15, 0, random.nextLong()));
settings.put(REDSTONE_ORE, new ResourceSettings(REDSTONE_ORE, platform.minZ, 15, 0, random.nextLong()));
settings.put(WATER, new ResourceSettings(WATER, platform.minZ, maxHeight - 1, 0, random.nextLong()));
settings.put(LAVA, new ResourceSettings(LAVA, platform.minZ, 15, 0, random.nextLong()));
settings.put(EMERALD_ORE, new ResourceSettings(EMERALD_ORE, 64, maxHeight - 1, 0, random.nextLong()));
settings.put(COPPER_ORE, new ResourceSettings(COPPER_ORE, 0, 88, 0, random.nextLong()));
settings.put(QUARTZ_ORE, new ResourceSettings(QUARTZ_ORE, platform.minZ, maxHeight - 1, 0, random.nextLong()));
settings.put(ANCIENT_DEBRIS, new ResourceSettings(ANCIENT_DEBRIS, platform.minZ, maxHeight - 1, 0, random.nextLong()));
break;
default:
throw new IllegalArgumentException("Dimension " + dim + " not supported");
}
return new ResourcesExporterSettings(settings);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
if (version < 1) {
// Legacy conversions
// Fix static water and lava
if (! maxLevels.containsKey(BLK_WATER)) {
logger.warn("Fixing water and lava settings");
maxLevels.put(BLK_WATER, maxLevels.get(BLK_STATIONARY_WATER));
chances.put(BLK_WATER, chances.get(BLK_STATIONARY_WATER));
seedOffsets.put(BLK_WATER, seedOffsets.get(BLK_STATIONARY_WATER));
maxLevels.put(BLK_LAVA, maxLevels.get(BLK_STATIONARY_LAVA));
chances.put(BLK_LAVA, chances.get(BLK_STATIONARY_LAVA));
seedOffsets.put(BLK_LAVA, seedOffsets.get(BLK_STATIONARY_LAVA));
maxLevels.remove(BLK_STATIONARY_WATER);
chances.remove(BLK_STATIONARY_WATER);
seedOffsets.remove(BLK_STATIONARY_WATER);
maxLevels.remove(BLK_STATIONARY_LAVA);
chances.remove(BLK_STATIONARY_LAVA);
seedOffsets.remove(BLK_STATIONARY_LAVA);
}
if (! maxLevels.containsKey(BLK_EMERALD_ORE)) {
maxLevels.put(BLK_EMERALD_ORE, 31);
chances.put(BLK_EMERALD_ORE, 0);
}
Random random = new Random();
if (! seedOffsets.containsKey(BLK_EMERALD_ORE)) {
seedOffsets.put(BLK_EMERALD_ORE, random.nextLong());
}
if (minLevels == null) {
minLevels = new HashMap<>();
for (int blockType: maxLevels.keySet()) {
minLevels.put(blockType, 0);
}
}
if (! minLevels.containsKey(BLK_QUARTZ_ORE)) {
minLevels.put(BLK_QUARTZ_ORE, 0);
maxLevels.put(BLK_QUARTZ_ORE, 255);
chances.put(BLK_QUARTZ_ORE, 0);
seedOffsets.put(BLK_QUARTZ_ORE, random.nextLong());
}
// Convert integer-based settings to material-based settings
settings = new LinkedHashMap<>();
for (int blockType: maxLevels.keySet()) {
Material material = get(blockType);
settings.put(material, new ResourceSettings(material, minLevels.get(blockType), maxLevels.get(blockType),
chances.get(blockType), seedOffsets.get(blockType)));
}
minLevels = null;
maxLevels = null;
chances = null;
seedOffsets = null;
}
if (version < 2) {
// Add new resources
final Random random = new Random();
settings.put(COPPER_ORE, new ResourceSettings(COPPER_ORE, 0, 88, 0, random.nextLong()));
settings.put(ANCIENT_DEBRIS, new ResourceSettings(ANCIENT_DEBRIS, -64, 319, 0, random.nextLong()));
}
version = 2;
// Not sure how, but the liquids are reverting to the stationary
// variants (something to do with the Minecraft 1.14 migration?).
// Just keep changing them back
if (settings.containsKey(STATIONARY_WATER)) {
settings.put(WATER, settings.get(STATIONARY_WATER));
settings.remove(STATIONARY_WATER);
}
if (settings.containsKey(STATIONARY_LAVA)) {
settings.put(LAVA, settings.get(STATIONARY_LAVA));
settings.remove(STATIONARY_LAVA);
}
}
private int minimumLevel = 8;
private Map<Material, ResourceSettings> settings = new LinkedHashMap<>();
/** @deprecated */
private Map<Integer, Integer> maxLevels = null;
/** @deprecated */
private Map<Integer, Integer> chances = null;
/** @deprecated */
private Map<Integer, Long> seedOffsets = null;
/** @deprecated */
private Map<Integer, Integer> minLevels = null;
private int version = 1;
private static final long serialVersionUID = 1L;
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ResourcesExporter.class);
}
static class ResourceSettings implements Serializable, Cloneable {
ResourceSettings(Material material, int minLevel, int maxLevel, int chance, long seedOffset) {
this.material = material;
this.minLevel = minLevel;
this.maxLevel = maxLevel;
this.chance = chance;
this.seedOffset = seedOffset;
}
@Override
public ResourceSettings clone() {
try {
return (ResourceSettings) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
Material material;
int minLevel, maxLevel, chance;
long seedOffset;
private static final long serialVersionUID = 1L;
}
} |
178432_2 | package database;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class AccountRegistratie {
@Autowired
private AccountDao accountDao;
@SuppressWarnings("unused")
@Autowired
private PlayerDao playerDao;
/**
* Toon een overzicht van alle accounts
*/
@RequestMapping("/")
public String overzicht(Model model) {
model.addAttribute("accounts", accountDao.allAccounts());
return "frontpage";
}
/**
* Toon een detail-view van een enkele account
*/
@RequestMapping(value="/account/{id}")
public String detailView(@PathVariable String id, Model model){
Long key;
try{
key = Long.valueOf(id);
}
catch(NumberFormatException e){
// id is geen getal? error 404
return null;
}
Account account = accountDao.findAccount(key);
if(account == null){
// geen account met gegeven id? error 404
return null;
} else {
model.addAttribute("account", account);
return "detail";
}
}
/**
* Verwijdert gegeven account -- zonder om bevestiging te vragen ;)
*/
@RequestMapping(value="/delete/{id}")
public String deleteView(@PathVariable String id){
Long key;
try{
key = Long.valueOf(id);
}
catch(NumberFormatException e){
// id is geen getal? error 404
return null;
}
accountDao.remove(key);
return "redirect:/";
}
/*@RequestMapping(value="/register", method=RequestMethod.POST)
public String nieuw(String username, String password){
AccountDao.create(username, password);
return "redirect:/charactercreation";
}*/
}
| Mallechai/DarkFantasy2 | src/database/AccountRegistratie.java | 556 | // id is geen getal? error 404 | line_comment | nl | package database;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class AccountRegistratie {
@Autowired
private AccountDao accountDao;
@SuppressWarnings("unused")
@Autowired
private PlayerDao playerDao;
/**
* Toon een overzicht van alle accounts
*/
@RequestMapping("/")
public String overzicht(Model model) {
model.addAttribute("accounts", accountDao.allAccounts());
return "frontpage";
}
/**
* Toon een detail-view van een enkele account
*/
@RequestMapping(value="/account/{id}")
public String detailView(@PathVariable String id, Model model){
Long key;
try{
key = Long.valueOf(id);
}
catch(NumberFormatException e){
// id is<SUF>
return null;
}
Account account = accountDao.findAccount(key);
if(account == null){
// geen account met gegeven id? error 404
return null;
} else {
model.addAttribute("account", account);
return "detail";
}
}
/**
* Verwijdert gegeven account -- zonder om bevestiging te vragen ;)
*/
@RequestMapping(value="/delete/{id}")
public String deleteView(@PathVariable String id){
Long key;
try{
key = Long.valueOf(id);
}
catch(NumberFormatException e){
// id is geen getal? error 404
return null;
}
accountDao.remove(key);
return "redirect:/";
}
/*@RequestMapping(value="/register", method=RequestMethod.POST)
public String nieuw(String username, String password){
AccountDao.create(username, password);
return "redirect:/charactercreation";
}*/
}
|
183347_0 | package excelimporter.reader.readers;
import java.util.HashMap;
import org.apache.poi.hssf.eventusermodel.HSSFListener;
import org.apache.poi.hssf.record.BOFRecord;
import org.apache.poi.hssf.record.LabelSSTRecord;
import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.RowRecord;
/**
*
*
* @author H. van Kranenburg, J. van der Hoek, J. Veldhuizen
* @version $Id: ExcelXLSReaderHeaderFirstPassListener.java 8202 2008-10-03 10:05:54Z Jonathan Veldhuizen $
*/
public class ExcelXLSReaderHeaderFirstPassListener implements HSSFListener {
private final int sheet;
private final int row;
int workbookNow = -1;
int sheetNow = -1;
int firstcol;
int lastcol;
// sstmap: list of unique strings occurring
// at first pass these will be marked with an empty dummy string when processing
// the LabelSSTRecord fields that are relevant to us
// at second pass this dummy string will be replaced by the actual string from the sst map
private HashMap<Integer, String> sstmap;
public ExcelXLSReaderHeaderFirstPassListener( int sheet, int row ) {
// this worksheet contains the row with template header fields
this.sheet = sheet;
// the row that contains template header fields
this.row = row;
}
/**
* This method listens for incoming records and handles them as required.
*
* @param record The record that was found while reading.
*/
@Override
public void processRecord( Record record ) {
// Most frequent encountered first...
switch (record.getSid()) {
case LabelSSTRecord.sid:
// LabelSSTRecord is a record that holds a pointer to a unicode string in the Static String Table
if ( this.sheetNow == this.sheet ) {
LabelSSTRecord lrec = (LabelSSTRecord) record;
// is this cell of interest to us?
if ( lrec.getRow() == this.row ) {
int sstindex = lrec.getSSTIndex();
// mark this spot in the sstlist, so it will be filled with the string at second pass
this.sstmap.put(sstindex, "");
}
}
break;
case RowRecord.sid:
if ( this.sheetNow == this.sheet ) {
RowRecord rowrec = (RowRecord) record;
if ( rowrec.getRowNumber() == this.row ) {
this.firstcol = Integer.valueOf(rowrec.getFirstCol());
this.lastcol = Integer.valueOf(rowrec.getLastCol());
// http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashMap.html
// "As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs."
int sstmapsize = (int) ((this.lastcol - this.firstcol) / 0.75);
this.sstmap = new HashMap<Integer, String>(sstmapsize);
}
}
break;
case BOFRecord.sid:
// BOFRecord can represent either the beginning of a sheet or the workbook
BOFRecord bof = (BOFRecord) record;
if ( bof.getType() == BOFRecord.TYPE_WORKBOOK ) {
++this.workbookNow;
}
else if ( bof.getType() == BOFRecord.TYPE_WORKSHEET ) {
++this.sheetNow;
}
break;
}
}
public HashMap<Integer, String> getSSTMap() {
return this.sstmap;
}
public int getRowWidth() {
return this.lastcol - this.firstcol;
}
}
| Mallikarjun67/LETSTRAVEL | .svn/pristine/9f/9f12b8f3c3c6cfb2baac80979293fed40134f5ea.svn-base | 1,025 | /**
*
*
* @author H. van Kranenburg, J. van der Hoek, J. Veldhuizen
* @version $Id: ExcelXLSReaderHeaderFirstPassListener.java 8202 2008-10-03 10:05:54Z Jonathan Veldhuizen $
*/ | block_comment | nl | package excelimporter.reader.readers;
import java.util.HashMap;
import org.apache.poi.hssf.eventusermodel.HSSFListener;
import org.apache.poi.hssf.record.BOFRecord;
import org.apache.poi.hssf.record.LabelSSTRecord;
import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.RowRecord;
/**
*
*
* @author H. van<SUF>*/
public class ExcelXLSReaderHeaderFirstPassListener implements HSSFListener {
private final int sheet;
private final int row;
int workbookNow = -1;
int sheetNow = -1;
int firstcol;
int lastcol;
// sstmap: list of unique strings occurring
// at first pass these will be marked with an empty dummy string when processing
// the LabelSSTRecord fields that are relevant to us
// at second pass this dummy string will be replaced by the actual string from the sst map
private HashMap<Integer, String> sstmap;
public ExcelXLSReaderHeaderFirstPassListener( int sheet, int row ) {
// this worksheet contains the row with template header fields
this.sheet = sheet;
// the row that contains template header fields
this.row = row;
}
/**
* This method listens for incoming records and handles them as required.
*
* @param record The record that was found while reading.
*/
@Override
public void processRecord( Record record ) {
// Most frequent encountered first...
switch (record.getSid()) {
case LabelSSTRecord.sid:
// LabelSSTRecord is a record that holds a pointer to a unicode string in the Static String Table
if ( this.sheetNow == this.sheet ) {
LabelSSTRecord lrec = (LabelSSTRecord) record;
// is this cell of interest to us?
if ( lrec.getRow() == this.row ) {
int sstindex = lrec.getSSTIndex();
// mark this spot in the sstlist, so it will be filled with the string at second pass
this.sstmap.put(sstindex, "");
}
}
break;
case RowRecord.sid:
if ( this.sheetNow == this.sheet ) {
RowRecord rowrec = (RowRecord) record;
if ( rowrec.getRowNumber() == this.row ) {
this.firstcol = Integer.valueOf(rowrec.getFirstCol());
this.lastcol = Integer.valueOf(rowrec.getLastCol());
// http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashMap.html
// "As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs."
int sstmapsize = (int) ((this.lastcol - this.firstcol) / 0.75);
this.sstmap = new HashMap<Integer, String>(sstmapsize);
}
}
break;
case BOFRecord.sid:
// BOFRecord can represent either the beginning of a sheet or the workbook
BOFRecord bof = (BOFRecord) record;
if ( bof.getType() == BOFRecord.TYPE_WORKBOOK ) {
++this.workbookNow;
}
else if ( bof.getType() == BOFRecord.TYPE_WORKSHEET ) {
++this.sheetNow;
}
break;
}
}
public HashMap<Integer, String> getSSTMap() {
return this.sstmap;
}
public int getRowWidth() {
return this.lastcol - this.firstcol;
}
}
|
15313_0 | /**
*
*/
package dammen.gui;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JPanel;
import dammen.model.Coord;
import dammen.model.Nodes;
/**
* Class description
* Een customized JPanel.
* Heeft een array met NodeComponents, die weer gekoppeld zijn aan Nodes.
* Zorgt ervoor dat alle Nodes op de juiste plek komen te staan.
*
* @version 1.00 17 jul. 2014
* @author Pieter
*/
public class BordPanel extends JPanel {
private NodeComponent[][] nodeList;
private static final long serialVersionUID = 3268182264406801064L;
private GridBagLayout layout;
private GridBagConstraints c;
{
layout = new GridBagLayout();
this.setLayout(layout);
c = new GridBagConstraints ();
}
/**
* Krijgt het virtuele speelbord binnen, en koppelt de Nodes van het virtuele speelbord aan de
* Nodes (NodeComponents) van het visuele speelbord.
*
* @remember Rare onvoorspelbare nullpointerException.. Oplossing: het daadwerkelijke toevoegen van componenten
* in een nieuwe methode (paintSpeelbord) doen. Waarschijnlijk ging het allemaal wat te snel voor de VM..
* @param Nodes[][] speelbord
*/
public void addSpeelBord (Nodes [][] speelbord) {
nodeList = null;
this.removeAll();
paintSpeelbord(speelbord);
this.repaint();
}
/**
* Methode om de nodeList te vullen met nodeComponents die worden aangemaakt
* op basis van een Node uit het speelbord.
* @param speelbord
*/
public void paintSpeelbord(Nodes[][] speelbord) {
nodeList = new NodeComponent [speelbord.length][speelbord[0].length];
//System.out.println (speelbord.length + " " + speelbord[0].length);
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
for (int i = 0; i <= Coord.getKolommen(); i++) {
for (int j = 0; j <= Coord.getRijen(); j++) {
c.gridx = i;
c.gridy = j;
NodeComponent nodeComp = new NodeComponent(speelbord[i][Coord.getRijen()-j]);
nodeList[i][Coord.getRijen()-j] = nodeComp;
this.add(nodeComp, c);
}
}
}
/**
* Haal een nodeComponent uit de lijst op basis van x en y coordinaat.
* Volgens mij kan deze wel weg.
* @param x
* @param y
* @return
*/
public NodeComponent getNodeComponent (int x, int y) {
return nodeList[x][y];
}
/**
* Haal een nodeComponent uit de lijst op basis van een Coord.
* Volgens mij kan deze wel weg.
* @param x
* @param y
* @return
*/
public NodeComponent getNodeComponent (Coord coord) {
return nodeList[coord.getX()][coord.getY()];
}
/**
* Custom preferredSize (op basis van een NodeSize in de statische screensize klasse,
* en het aantal rijen/kolommen van het speelveld.
*/
public Dimension getPreferredSize() {
return new Dimension(ScreenSize.KOLOMMEN * ScreenSize.NODESIZE ,ScreenSize.RIJEN * ScreenSize.NODESIZE);
}
}
| Mandiax/GameSuite | GameSuiteMain/src/dammen/gui/BordPanel.java | 1,131 | /**
* Class description
* Een customized JPanel.
* Heeft een array met NodeComponents, die weer gekoppeld zijn aan Nodes.
* Zorgt ervoor dat alle Nodes op de juiste plek komen te staan.
*
* @version 1.00 17 jul. 2014
* @author Pieter
*/ | block_comment | nl | /**
*
*/
package dammen.gui;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JPanel;
import dammen.model.Coord;
import dammen.model.Nodes;
/**
* Class description
<SUF>*/
public class BordPanel extends JPanel {
private NodeComponent[][] nodeList;
private static final long serialVersionUID = 3268182264406801064L;
private GridBagLayout layout;
private GridBagConstraints c;
{
layout = new GridBagLayout();
this.setLayout(layout);
c = new GridBagConstraints ();
}
/**
* Krijgt het virtuele speelbord binnen, en koppelt de Nodes van het virtuele speelbord aan de
* Nodes (NodeComponents) van het visuele speelbord.
*
* @remember Rare onvoorspelbare nullpointerException.. Oplossing: het daadwerkelijke toevoegen van componenten
* in een nieuwe methode (paintSpeelbord) doen. Waarschijnlijk ging het allemaal wat te snel voor de VM..
* @param Nodes[][] speelbord
*/
public void addSpeelBord (Nodes [][] speelbord) {
nodeList = null;
this.removeAll();
paintSpeelbord(speelbord);
this.repaint();
}
/**
* Methode om de nodeList te vullen met nodeComponents die worden aangemaakt
* op basis van een Node uit het speelbord.
* @param speelbord
*/
public void paintSpeelbord(Nodes[][] speelbord) {
nodeList = new NodeComponent [speelbord.length][speelbord[0].length];
//System.out.println (speelbord.length + " " + speelbord[0].length);
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
for (int i = 0; i <= Coord.getKolommen(); i++) {
for (int j = 0; j <= Coord.getRijen(); j++) {
c.gridx = i;
c.gridy = j;
NodeComponent nodeComp = new NodeComponent(speelbord[i][Coord.getRijen()-j]);
nodeList[i][Coord.getRijen()-j] = nodeComp;
this.add(nodeComp, c);
}
}
}
/**
* Haal een nodeComponent uit de lijst op basis van x en y coordinaat.
* Volgens mij kan deze wel weg.
* @param x
* @param y
* @return
*/
public NodeComponent getNodeComponent (int x, int y) {
return nodeList[x][y];
}
/**
* Haal een nodeComponent uit de lijst op basis van een Coord.
* Volgens mij kan deze wel weg.
* @param x
* @param y
* @return
*/
public NodeComponent getNodeComponent (Coord coord) {
return nodeList[coord.getX()][coord.getY()];
}
/**
* Custom preferredSize (op basis van een NodeSize in de statische screensize klasse,
* en het aantal rijen/kolommen van het speelveld.
*/
public Dimension getPreferredSize() {
return new Dimension(ScreenSize.KOLOMMEN * ScreenSize.NODESIZE ,ScreenSize.RIJEN * ScreenSize.NODESIZE);
}
}
|
23323_16 | package nl.uva.nccslave;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.content.pm.ActivityInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.mymodule.app2.DevicePacket;
import com.example.mymodule.app2.DeviceType;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
public class MainActivity extends Activity implements
ConnectionCallbacks,
OnConnectionFailedListener,
LocationListener,
SensorEventListener {
private static final int MILLISECONDS_PER_SECOND = 1000;
private static final int UPDATE_INTERVAL_IN_SECONDS = 5;
private static final long UPDATE_INTERVAL = MILLISECONDS_PER_SECOND * UPDATE_INTERVAL_IN_SECONDS;
private static final int FASTEST_INTERVAL_IN_SECONDS = 1;
private static final long FASTEST_INTERVAL = MILLISECONDS_PER_SECOND * FASTEST_INTERVAL_IN_SECONDS;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
// Location
LocationRequest mLocationRequest;
LocationClient mLocationClient;
// Bearing
private SensorManager sensorManager;
float[] mGravity = null;
float[] mGeomagnetic = null;
float mBearing = 0;
WifiP2pManager mManager;
WifiP2pManager.Channel mChannel;
WiFiDirectBroadcastReceiver mReceiver;
IntentFilter mIntentFilter;
// UI elements
private TextView mTvLatitude;
private TextView mTvLongitude;
private EditText mNameInput;
private Spinner mDeviceTypeSpinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
// Setup location requests
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(
LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationClient = new LocationClient(this, this, this);
// setup wifi direct framework
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel);
// register broadcastreceiver
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
registerReceiver(mReceiver, mIntentFilter);
// get ui elements
mTvLatitude = (TextView) findViewById(R.id.tvLatitude);
mTvLongitude = (TextView) findViewById(R.id.tvLongitude);
Button mButton = (Button) findViewById(R.id.button_discover);
mNameInput = (EditText) findViewById(R.id.input_name);
mDeviceTypeSpinner = (Spinner) findViewById(R.id.device_type_spinner);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mReceiver.startDiscovery();
mDeviceTypeSpinner.setEnabled(false);
}
});
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.device_types, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
mDeviceTypeSpinner.setAdapter(adapter);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
}
/* start location requests */
@Override
protected void onStart() {
super.onStart();
mLocationClient.connect();
}
/* register the broadcast receiver with the intent values to be matched */
@Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
// Register for sensors
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
sensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
sensorManager.SENSOR_DELAY_NORMAL);
}
/* unregister the broadcast receiver */
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
// Unregister for sensors
sensorManager.unregisterListener(this);
}
/*
* LOCATION
*/
//TODO: doet op het moment helemaal niks..
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Decide what to do based on the original request code
switch (requestCode) {
case CONNECTION_FAILURE_RESOLUTION_REQUEST :
/*
* If the result code is Activity.RESULT_OK, try
* to connect again
*/
switch (resultCode) {
case Activity.RESULT_OK :
/*
* Try the request again
*/
break;
}
}
}
//TODO: Wordt niet gebruikt..
private boolean servicesConnected() {
// Check that Google Play services is available
int resultCode =
GooglePlayServicesUtil.
isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
// In debug mode, log the status
Log.d("Location Updates",
"Google Play services is available.");
// Continue
return true;
// Google Play services was not available for some reason
} else {
// Get the error code
showErrorDialog(resultCode);
return false;
}
}
private void showErrorDialog(int resultCode) {
GooglePlayServicesUtil.getErrorDialog(
resultCode,
this,
resultCode).show();
}
@Override
public void onConnected(Bundle dataBundle) {
// Display the connection status
Toast.makeText(this, "Connected to Google Play services", Toast.LENGTH_SHORT).show();
mLocationClient.requestLocationUpdates(mLocationRequest, this);
}
@Override
public void onDisconnected() {
// Display the connection status
Toast.makeText(this, "Disconnected from Google Play services. Please re-connect.",
Toast.LENGTH_SHORT).show();
}
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
showErrorDialog(connectionResult.getErrorCode());
}
}
@Override
public void onLocationChanged(Location location) {
// Show location in UI
mTvLatitude.setText(Double.toString(location.getLatitude()));
mTvLongitude.setText(Double.toString(location.getLongitude()));
// Get own MAC address to send to master
WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = manager.getConnectionInfo();
String address = info.getMacAddress();
// Get own name
String name = "";
if (mNameInput.getText() != null && mNameInput.getText().length() != 0) {
name = mNameInput.getText().toString();
}
// Get device type
String deviceTypeStr = (String) mDeviceTypeSpinner.getSelectedItem();
DeviceType deviceType = DevicePacket.stringToDeviceType(deviceTypeStr);
// Create slave object to send to master
DevicePacket devicePacket = new DevicePacket();
devicePacket.setIdentifier(address);
devicePacket.setName(name);
devicePacket.setLatitude(location.getLatitude());
devicePacket.setLongitude(location.getLongitude());
devicePacket.setDeviceType(deviceType);
devicePacket.setBearing(mBearing);
// Send location to server
new ClientTask().execute(devicePacket);
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {}
// from http://stackoverflow.com/questions/15155985/android-compass-bearing
// Gets bearing in degrees. 0/360 = north
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
// Get gravity
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
mGravity = sensorEvent.values;
// Get magnetic field
if (sensorEvent.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
mGeomagnetic = sensorEvent.values;
// Get bearing
if (mGravity != null && mGeomagnetic != null) {
float R[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, mGravity,
mGeomagnetic);
if (success) {
float orientation[] = new float[3];
SensorManager.getOrientation(R, orientation);
float azimuthInRadians = orientation[0];
float azimuthInDegrees = (float)(Math.toDegrees(azimuthInRadians)+360)%360;
mBearing = azimuthInDegrees;
}
}
}
}
| ManuelOverdijk/ncc | slave/app/src/main/java/nl/uva/nccslave/MainActivity.java | 3,145 | //TODO: Wordt niet gebruikt.. | line_comment | nl | package nl.uva.nccslave;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.content.pm.ActivityInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.mymodule.app2.DevicePacket;
import com.example.mymodule.app2.DeviceType;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
public class MainActivity extends Activity implements
ConnectionCallbacks,
OnConnectionFailedListener,
LocationListener,
SensorEventListener {
private static final int MILLISECONDS_PER_SECOND = 1000;
private static final int UPDATE_INTERVAL_IN_SECONDS = 5;
private static final long UPDATE_INTERVAL = MILLISECONDS_PER_SECOND * UPDATE_INTERVAL_IN_SECONDS;
private static final int FASTEST_INTERVAL_IN_SECONDS = 1;
private static final long FASTEST_INTERVAL = MILLISECONDS_PER_SECOND * FASTEST_INTERVAL_IN_SECONDS;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
// Location
LocationRequest mLocationRequest;
LocationClient mLocationClient;
// Bearing
private SensorManager sensorManager;
float[] mGravity = null;
float[] mGeomagnetic = null;
float mBearing = 0;
WifiP2pManager mManager;
WifiP2pManager.Channel mChannel;
WiFiDirectBroadcastReceiver mReceiver;
IntentFilter mIntentFilter;
// UI elements
private TextView mTvLatitude;
private TextView mTvLongitude;
private EditText mNameInput;
private Spinner mDeviceTypeSpinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
// Setup location requests
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(
LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationClient = new LocationClient(this, this, this);
// setup wifi direct framework
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel);
// register broadcastreceiver
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
registerReceiver(mReceiver, mIntentFilter);
// get ui elements
mTvLatitude = (TextView) findViewById(R.id.tvLatitude);
mTvLongitude = (TextView) findViewById(R.id.tvLongitude);
Button mButton = (Button) findViewById(R.id.button_discover);
mNameInput = (EditText) findViewById(R.id.input_name);
mDeviceTypeSpinner = (Spinner) findViewById(R.id.device_type_spinner);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mReceiver.startDiscovery();
mDeviceTypeSpinner.setEnabled(false);
}
});
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.device_types, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
mDeviceTypeSpinner.setAdapter(adapter);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
}
/* start location requests */
@Override
protected void onStart() {
super.onStart();
mLocationClient.connect();
}
/* register the broadcast receiver with the intent values to be matched */
@Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
// Register for sensors
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
sensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
sensorManager.SENSOR_DELAY_NORMAL);
}
/* unregister the broadcast receiver */
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
// Unregister for sensors
sensorManager.unregisterListener(this);
}
/*
* LOCATION
*/
//TODO: doet op het moment helemaal niks..
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Decide what to do based on the original request code
switch (requestCode) {
case CONNECTION_FAILURE_RESOLUTION_REQUEST :
/*
* If the result code is Activity.RESULT_OK, try
* to connect again
*/
switch (resultCode) {
case Activity.RESULT_OK :
/*
* Try the request again
*/
break;
}
}
}
//TODO: Wordt<SUF>
private boolean servicesConnected() {
// Check that Google Play services is available
int resultCode =
GooglePlayServicesUtil.
isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
// In debug mode, log the status
Log.d("Location Updates",
"Google Play services is available.");
// Continue
return true;
// Google Play services was not available for some reason
} else {
// Get the error code
showErrorDialog(resultCode);
return false;
}
}
private void showErrorDialog(int resultCode) {
GooglePlayServicesUtil.getErrorDialog(
resultCode,
this,
resultCode).show();
}
@Override
public void onConnected(Bundle dataBundle) {
// Display the connection status
Toast.makeText(this, "Connected to Google Play services", Toast.LENGTH_SHORT).show();
mLocationClient.requestLocationUpdates(mLocationRequest, this);
}
@Override
public void onDisconnected() {
// Display the connection status
Toast.makeText(this, "Disconnected from Google Play services. Please re-connect.",
Toast.LENGTH_SHORT).show();
}
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
showErrorDialog(connectionResult.getErrorCode());
}
}
@Override
public void onLocationChanged(Location location) {
// Show location in UI
mTvLatitude.setText(Double.toString(location.getLatitude()));
mTvLongitude.setText(Double.toString(location.getLongitude()));
// Get own MAC address to send to master
WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = manager.getConnectionInfo();
String address = info.getMacAddress();
// Get own name
String name = "";
if (mNameInput.getText() != null && mNameInput.getText().length() != 0) {
name = mNameInput.getText().toString();
}
// Get device type
String deviceTypeStr = (String) mDeviceTypeSpinner.getSelectedItem();
DeviceType deviceType = DevicePacket.stringToDeviceType(deviceTypeStr);
// Create slave object to send to master
DevicePacket devicePacket = new DevicePacket();
devicePacket.setIdentifier(address);
devicePacket.setName(name);
devicePacket.setLatitude(location.getLatitude());
devicePacket.setLongitude(location.getLongitude());
devicePacket.setDeviceType(deviceType);
devicePacket.setBearing(mBearing);
// Send location to server
new ClientTask().execute(devicePacket);
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {}
// from http://stackoverflow.com/questions/15155985/android-compass-bearing
// Gets bearing in degrees. 0/360 = north
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
// Get gravity
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
mGravity = sensorEvent.values;
// Get magnetic field
if (sensorEvent.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
mGeomagnetic = sensorEvent.values;
// Get bearing
if (mGravity != null && mGeomagnetic != null) {
float R[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, mGravity,
mGeomagnetic);
if (success) {
float orientation[] = new float[3];
SensorManager.getOrientation(R, orientation);
float azimuthInRadians = orientation[0];
float azimuthInDegrees = (float)(Math.toDegrees(azimuthInRadians)+360)%360;
mBearing = azimuthInDegrees;
}
}
}
}
|
76751_8 | /*
Copyright (C) 2012 Haowen Ning
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.liberty.android.fantastischmemo.common;
/*
* Class that defines the contants that is used in AnyMemo.
*/
public class AMPrefKeys {
// Keys for Algorithm customization.
public static final String getInitialGradingIntervalKey(int grade) {
return "initial_grading_interval_" + grade;
}
public static final String getFailedGradingIntervalKey(int grade) {
return "failed_grading_interval_" + grade;
}
public static final String getEasinessIncrementalKey(int grade) {
return "easiness_incremental_" + grade;
}
public static final String ENABLE_NOISE_KEY = "enable_noise";
public static final String MINIMAL_INTERVAL_KEY = "minimal_interval";
public static final String INITIAL_EASINESS_KEY = "initial_easiness";
public static final String MINIMAL_EASINESS_KEY = "minimal_easiness";
public static final String LEARN_QUEUE_SIZE_KEY = "learning_queue_size";
public static final String REVIEW_ORDERING_KEY = "review_ordering";
// Keys for Options
public static final String ENABLE_THIRD_PARTY_ARABIC_KEY = "enable_third_party_arabic";
public static final String BUTTON_STYLE_KEY = "button_style";
public static final String ENABLE_VOLUME_KEY_KEY = "enable_volume_key";
public static final String COPY_CLIPBOARD_KEY = "copy_to_clipboard";
public static final String DICT_APP_KEY = "dict_app";
public static final String SHUFFLING_CARDS_KEY = "shuffling_cards";
public static final String SPEECH_CONTROL_KEY = "speech_ctl";
public static final String RECENT_COUNT_KEY = "recent_count";
public static final String WORKOUT_COUNT_KEY = "workout_count";
public static final String ENABLE_ANIMATION_KEY = "enable_animation";
// Dropbox
public static final String DROPBOX_USERNAME_KEY = "dropbox_username";
public static final String DROPBOX_TOKEN_KEY = "dropbox_token";
public static final String DROPBOX_SECRET_KEY = "dropbox_secret";
public static final String DROPBOX_AUTH_TOKEN="dropbox_auth_token";
public static final String DROPBOX_AUTH_TOKEN_SECRET="dropbox_auth_token_secret";
// FlashcardExchange
public static final String FE_SAVED_USERNAME_KEY = "saved_username";
public static final String FE_SAVED_OAUTH_TOKEN_KEY = "saved_oauth_token";
public static final String FE_SAVED_OAUTH_TOKEN_SECRET_KEY = "saved_oauth_token_secret";
public static final String FE_SAVED_SEARCH_KEY = "fe_saved_search";
public static final String FE_SAVED_USER_KEY = "fe_saved_user";
public static final String QUIZLET_SAVED_SEARCH = "quizlet_saved_search";
public static final String QUIZLET_SAVED_USER = "quizlet_saved_user";
public static final String GOOGLE_AUTH_TOKEN = "google_auth_token";
// AnyMemo main activity
public static final String FIRST_TIME_KEY = "first_time";
public static final String getWorkoutCountKey(int ord) {return "workoutpath"+ord; }
public static final String getRecentPathKey(int ord) {
return "recentdbpath" + ord;
}
public static final String SAVED_VERSION_CODE_KEY = "saved_version_code";
public static final String SAVED_FILEBROWSER_PATH_KEY = "saved_fb_path";
// Quiz
public static final String QUIZ_GROUP_SIZE_KEY = "quiz_group_size";
public static final String QUIZ_GROUP_NUMBER_KEY = "quiz_group_number";
public static final String QUIZ_START_ORDINAL_KEY = "quiz_start_ordinal";
public static final String QUIZ_END_ORDINAL_KEY = "quiz_end_ordinal";
// Card Editor
public static final String ADD_BACK_KEY = "add_back";
// public static final String
// public static final String
// public static final String
// List edit screen
public static final String LIST_EDIT_SCREEN_PREFIX = "CardListActivity";
// BaseActivity
public static final String INTERFACE_LOCALE_KEY = "interface_locale";
public static final String FULLSCREEN_MODE_KEY = "fullscreen_mode";
public static final String ALLOW_ORIENTATION_KEY= "allow_orientation";
// AnyMemoService
public static final String NOTIFICATION_INTERVAL_KEY = "notification_interval";
// Card player
public static final String CARD_PLAYER_QA_SLEEP_INTERVAL_KEY = "card_player_qa_sleep_interval";
public static final String CARD_PLAYER_CARD_SLEEP_INTERVAL_KEY = "card_player_card_sleep_interval";
public static final String CARD_PLAYER_SHUFFLE_ENABLED_KEY = "card_player_shuffle_enabled";
public static final String CARD_PLAYER_REPEAT_ENABLED_KEY = "card_player_repeat_enabled";
// QA Card Activity
public static final String CARD_GESTURE_ENABLED = "card_gesture_enabled";
// The prefix for oauth access token preference
public static final String OAUTH_ACCESS_TOKEN_KEY_PREFIX = "oauth_access_token_";
// The prefix for remembered id for preview edit mode.
public static final String PREVIEW_EDIT_START_ID_PREFIX = "preview_edit_start_id_prefix";
public static final String LIST_SORT_BY_METHOD_PREFIX = "list_sort_by_method_prefix";
public static final String LIST_ANSWER_VISIBLE_PREFIX = "list_answer_visible";
}
| MarcLeclair/Mini-Cap-AnyMemo | app/src/main/java/org/liberty/android/fantastischmemo/common/AMPrefKeys.java | 1,814 | // List edit screen | line_comment | nl | /*
Copyright (C) 2012 Haowen Ning
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.liberty.android.fantastischmemo.common;
/*
* Class that defines the contants that is used in AnyMemo.
*/
public class AMPrefKeys {
// Keys for Algorithm customization.
public static final String getInitialGradingIntervalKey(int grade) {
return "initial_grading_interval_" + grade;
}
public static final String getFailedGradingIntervalKey(int grade) {
return "failed_grading_interval_" + grade;
}
public static final String getEasinessIncrementalKey(int grade) {
return "easiness_incremental_" + grade;
}
public static final String ENABLE_NOISE_KEY = "enable_noise";
public static final String MINIMAL_INTERVAL_KEY = "minimal_interval";
public static final String INITIAL_EASINESS_KEY = "initial_easiness";
public static final String MINIMAL_EASINESS_KEY = "minimal_easiness";
public static final String LEARN_QUEUE_SIZE_KEY = "learning_queue_size";
public static final String REVIEW_ORDERING_KEY = "review_ordering";
// Keys for Options
public static final String ENABLE_THIRD_PARTY_ARABIC_KEY = "enable_third_party_arabic";
public static final String BUTTON_STYLE_KEY = "button_style";
public static final String ENABLE_VOLUME_KEY_KEY = "enable_volume_key";
public static final String COPY_CLIPBOARD_KEY = "copy_to_clipboard";
public static final String DICT_APP_KEY = "dict_app";
public static final String SHUFFLING_CARDS_KEY = "shuffling_cards";
public static final String SPEECH_CONTROL_KEY = "speech_ctl";
public static final String RECENT_COUNT_KEY = "recent_count";
public static final String WORKOUT_COUNT_KEY = "workout_count";
public static final String ENABLE_ANIMATION_KEY = "enable_animation";
// Dropbox
public static final String DROPBOX_USERNAME_KEY = "dropbox_username";
public static final String DROPBOX_TOKEN_KEY = "dropbox_token";
public static final String DROPBOX_SECRET_KEY = "dropbox_secret";
public static final String DROPBOX_AUTH_TOKEN="dropbox_auth_token";
public static final String DROPBOX_AUTH_TOKEN_SECRET="dropbox_auth_token_secret";
// FlashcardExchange
public static final String FE_SAVED_USERNAME_KEY = "saved_username";
public static final String FE_SAVED_OAUTH_TOKEN_KEY = "saved_oauth_token";
public static final String FE_SAVED_OAUTH_TOKEN_SECRET_KEY = "saved_oauth_token_secret";
public static final String FE_SAVED_SEARCH_KEY = "fe_saved_search";
public static final String FE_SAVED_USER_KEY = "fe_saved_user";
public static final String QUIZLET_SAVED_SEARCH = "quizlet_saved_search";
public static final String QUIZLET_SAVED_USER = "quizlet_saved_user";
public static final String GOOGLE_AUTH_TOKEN = "google_auth_token";
// AnyMemo main activity
public static final String FIRST_TIME_KEY = "first_time";
public static final String getWorkoutCountKey(int ord) {return "workoutpath"+ord; }
public static final String getRecentPathKey(int ord) {
return "recentdbpath" + ord;
}
public static final String SAVED_VERSION_CODE_KEY = "saved_version_code";
public static final String SAVED_FILEBROWSER_PATH_KEY = "saved_fb_path";
// Quiz
public static final String QUIZ_GROUP_SIZE_KEY = "quiz_group_size";
public static final String QUIZ_GROUP_NUMBER_KEY = "quiz_group_number";
public static final String QUIZ_START_ORDINAL_KEY = "quiz_start_ordinal";
public static final String QUIZ_END_ORDINAL_KEY = "quiz_end_ordinal";
// Card Editor
public static final String ADD_BACK_KEY = "add_back";
// public static final String
// public static final String
// public static final String
// List edit<SUF>
public static final String LIST_EDIT_SCREEN_PREFIX = "CardListActivity";
// BaseActivity
public static final String INTERFACE_LOCALE_KEY = "interface_locale";
public static final String FULLSCREEN_MODE_KEY = "fullscreen_mode";
public static final String ALLOW_ORIENTATION_KEY= "allow_orientation";
// AnyMemoService
public static final String NOTIFICATION_INTERVAL_KEY = "notification_interval";
// Card player
public static final String CARD_PLAYER_QA_SLEEP_INTERVAL_KEY = "card_player_qa_sleep_interval";
public static final String CARD_PLAYER_CARD_SLEEP_INTERVAL_KEY = "card_player_card_sleep_interval";
public static final String CARD_PLAYER_SHUFFLE_ENABLED_KEY = "card_player_shuffle_enabled";
public static final String CARD_PLAYER_REPEAT_ENABLED_KEY = "card_player_repeat_enabled";
// QA Card Activity
public static final String CARD_GESTURE_ENABLED = "card_gesture_enabled";
// The prefix for oauth access token preference
public static final String OAUTH_ACCESS_TOKEN_KEY_PREFIX = "oauth_access_token_";
// The prefix for remembered id for preview edit mode.
public static final String PREVIEW_EDIT_START_ID_PREFIX = "preview_edit_start_id_prefix";
public static final String LIST_SORT_BY_METHOD_PREFIX = "list_sort_by_method_prefix";
public static final String LIST_ANSWER_VISIBLE_PREFIX = "list_answer_visible";
}
|
83582_1 | package org.tinymediamanager.scraper.xbmc;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class XbmcScraperParser {
private static final Logger LOGGER = LoggerFactory.getLogger(XbmcScraperParser.class);
public XbmcScraper parseScraper(XbmcScraper scraper, List<File> common) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
Document xml = parser.parse(new File(scraper.getFolder(), scraper.getScraperXml()));
// get the first element
Element element = xml.getDocumentElement();
// get all child nodes
NodeList nodes = element.getChildNodes();
// // print the text content of each child
// for (int i = 0; i < nodes.getLength(); i++) {
// System.out.println("<" + nodes.item(i).getNodeName() + "> " + nodes.item(i).getTextContent());
// }
Element docEl = xml.getDocumentElement();
NodeList nl = docEl.getChildNodes();
int len = nl.getLength();
for (int i = 0; i < len; i++) {
Node n = nl.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) n;
ScraperFunction func = new ScraperFunction();
func.setName(el.getNodeName());
func.setClearBuffers(parseBoolean(el.getAttribute("clearbuffers"), true));
func.setAppendBuffer(parseAppendBuffer(el.getAttribute("dest")));
func.setDest(parseInt(el.getAttribute("dest")));
scraper.addFunction(func);
// functions contain regexp expressions, so let's get those.
processRegexps(func, el);
}
}
// get all common scraper functions
readScraperFunctions(scraper, common);
return scraper;
}
private boolean parseAppendBuffer(String attribute) {
if (attribute == null)
return false;
if (attribute.trim().endsWith("+"))
return true;
return false;
}
private void processRegexps(RegExpContainer container, Element el) {
NodeList regEls = el.getChildNodes();
int regElsLen = regEls.getLength();
for (int k = 0; k < regElsLen; k++) {
Node nn = regEls.item(k);
if ("RegExp".equals(nn.getNodeName())) {
Element expEl = (Element) nn;
RegExp regexp = new RegExp();
regexp.setInput(expEl.getAttribute("input"));
regexp.setOutput(expEl.getAttribute("output"));
regexp.setAppendBuffer(parseAppendBuffer(expEl.getAttribute("dest")));
regexp.setDest(parseInt(expEl.getAttribute("dest")));
regexp.setConditional(expEl.getAttribute("conditional"));
container.addRegExp(regexp);
processRegexps(regexp, (Element) nn);
}
else if ("expression".equals(nn.getNodeName())) {
Element expEl = (Element) nn;
try {
RegExp regexp = (RegExp) container; // cannot cast - exception see below
Expression exp = new Expression();
exp.setExpression(nn.getTextContent());
exp.setNoClean(expEl.getAttribute("noclean"));
exp.setRepeat(parseBoolean(expEl.getAttribute("repeat"), false));
exp.setClear(parseBoolean(expEl.getAttribute("clear"), false));
regexp.setExpression(exp);
}
catch (Exception e) {
LOGGER.warn("unparseable expression! " + container);
// happens here (kino.de) - the last empty expression.
// maybe no RegExp around?
//
// <GetTrailer dest="5">
// <RegExp input="$$1" output="<details><trailer urlencoded="yes">\1</trailer></details>" dest="5">
// <expression noclean="1"><url>([^<]*)</url></expression>
// </RegExp>
// <expression noclean="1"/> <------------------
// </GetTrailer>
}
}
else {
// skip nodest that we don't know about
// System.out.println("Skipping Node: " + nn);
}
}
}
private int parseInt(String attribute) {
if (attribute == null || attribute.trim().length() == 0)
return 0;
if (attribute.endsWith("+")) {
attribute = attribute.substring(0, attribute.length() - 1);
}
return Integer.parseInt(attribute);
}
private boolean parseBoolean(String attribute, boolean defaultNull) {
if (attribute == null || attribute.trim().length() == 0)
return defaultNull;
if ("yes".equalsIgnoreCase(attribute))
return true;
if ("no".equalsIgnoreCase(attribute))
return false;
return Boolean.parseBoolean(attribute);
}
private void readScraperFunctions(XbmcScraper scraper, List<File> common) {
for (File file : common) {
// System.out.println("parsing common file: " + file);
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
Document xml = parser.parse(file);
Element docEl = xml.getDocumentElement();
// only process xml files with scraperfunctions
if (docEl.getNodeName() == "scraperfunctions") {
NodeList nl = docEl.getChildNodes();
// extract all scraperfunctions
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) n;
ScraperFunction func = new ScraperFunction();
func.setName(el.getNodeName());
func.setClearBuffers(parseBoolean(el.getAttribute("clearbuffers"), true));
func.setAppendBuffer(parseAppendBuffer(el.getAttribute("dest")));
func.setDest(parseInt(el.getAttribute("dest")));
scraper.addFunction(func);
// functions contain regexp expressions, so let's get those.
processRegexps(func, el);
}
}
}
}
catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
| MarcoFleres/tinyMediaManager | src/org/tinymediamanager/scraper/xbmc/XbmcScraperParser.java | 2,029 | // get all child nodes | line_comment | nl | package org.tinymediamanager.scraper.xbmc;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class XbmcScraperParser {
private static final Logger LOGGER = LoggerFactory.getLogger(XbmcScraperParser.class);
public XbmcScraper parseScraper(XbmcScraper scraper, List<File> common) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
Document xml = parser.parse(new File(scraper.getFolder(), scraper.getScraperXml()));
// get the first element
Element element = xml.getDocumentElement();
// get all<SUF>
NodeList nodes = element.getChildNodes();
// // print the text content of each child
// for (int i = 0; i < nodes.getLength(); i++) {
// System.out.println("<" + nodes.item(i).getNodeName() + "> " + nodes.item(i).getTextContent());
// }
Element docEl = xml.getDocumentElement();
NodeList nl = docEl.getChildNodes();
int len = nl.getLength();
for (int i = 0; i < len; i++) {
Node n = nl.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) n;
ScraperFunction func = new ScraperFunction();
func.setName(el.getNodeName());
func.setClearBuffers(parseBoolean(el.getAttribute("clearbuffers"), true));
func.setAppendBuffer(parseAppendBuffer(el.getAttribute("dest")));
func.setDest(parseInt(el.getAttribute("dest")));
scraper.addFunction(func);
// functions contain regexp expressions, so let's get those.
processRegexps(func, el);
}
}
// get all common scraper functions
readScraperFunctions(scraper, common);
return scraper;
}
private boolean parseAppendBuffer(String attribute) {
if (attribute == null)
return false;
if (attribute.trim().endsWith("+"))
return true;
return false;
}
private void processRegexps(RegExpContainer container, Element el) {
NodeList regEls = el.getChildNodes();
int regElsLen = regEls.getLength();
for (int k = 0; k < regElsLen; k++) {
Node nn = regEls.item(k);
if ("RegExp".equals(nn.getNodeName())) {
Element expEl = (Element) nn;
RegExp regexp = new RegExp();
regexp.setInput(expEl.getAttribute("input"));
regexp.setOutput(expEl.getAttribute("output"));
regexp.setAppendBuffer(parseAppendBuffer(expEl.getAttribute("dest")));
regexp.setDest(parseInt(expEl.getAttribute("dest")));
regexp.setConditional(expEl.getAttribute("conditional"));
container.addRegExp(regexp);
processRegexps(regexp, (Element) nn);
}
else if ("expression".equals(nn.getNodeName())) {
Element expEl = (Element) nn;
try {
RegExp regexp = (RegExp) container; // cannot cast - exception see below
Expression exp = new Expression();
exp.setExpression(nn.getTextContent());
exp.setNoClean(expEl.getAttribute("noclean"));
exp.setRepeat(parseBoolean(expEl.getAttribute("repeat"), false));
exp.setClear(parseBoolean(expEl.getAttribute("clear"), false));
regexp.setExpression(exp);
}
catch (Exception e) {
LOGGER.warn("unparseable expression! " + container);
// happens here (kino.de) - the last empty expression.
// maybe no RegExp around?
//
// <GetTrailer dest="5">
// <RegExp input="$$1" output="<details><trailer urlencoded="yes">\1</trailer></details>" dest="5">
// <expression noclean="1"><url>([^<]*)</url></expression>
// </RegExp>
// <expression noclean="1"/> <------------------
// </GetTrailer>
}
}
else {
// skip nodest that we don't know about
// System.out.println("Skipping Node: " + nn);
}
}
}
private int parseInt(String attribute) {
if (attribute == null || attribute.trim().length() == 0)
return 0;
if (attribute.endsWith("+")) {
attribute = attribute.substring(0, attribute.length() - 1);
}
return Integer.parseInt(attribute);
}
private boolean parseBoolean(String attribute, boolean defaultNull) {
if (attribute == null || attribute.trim().length() == 0)
return defaultNull;
if ("yes".equalsIgnoreCase(attribute))
return true;
if ("no".equalsIgnoreCase(attribute))
return false;
return Boolean.parseBoolean(attribute);
}
private void readScraperFunctions(XbmcScraper scraper, List<File> common) {
for (File file : common) {
// System.out.println("parsing common file: " + file);
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
Document xml = parser.parse(file);
Element docEl = xml.getDocumentElement();
// only process xml files with scraperfunctions
if (docEl.getNodeName() == "scraperfunctions") {
NodeList nl = docEl.getChildNodes();
// extract all scraperfunctions
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) n;
ScraperFunction func = new ScraperFunction();
func.setName(el.getNodeName());
func.setClearBuffers(parseBoolean(el.getAttribute("clearbuffers"), true));
func.setAppendBuffer(parseAppendBuffer(el.getAttribute("dest")));
func.setDest(parseInt(el.getAttribute("dest")));
scraper.addFunction(func);
// functions contain regexp expressions, so let's get those.
processRegexps(func, el);
}
}
}
}
catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
189025_12 | /*
**************************************************************************
* *
* DDDDD iii DDDDD iii *
* DD DD mm mm mmmm DD DD mm mm mmmm *
* DD DD iii mmm mm mm DD DD iii mmm mm mm *
* DD DD iii mmm mm mm DD DD iii mmm mm mm *
* DDDDDD iii mmm mm mm DDDDDD iii mmm mm mm *
* *
**************************************************************************
**************************************************************************
* *
* Part of the DimDim V 1.0 Codebase (http://www.dimdim.com) *
* *
* Copyright (c) 2006 Communiva Inc. All Rights Reserved. *
* *
* *
* This code is licensed under the DimDim License *
* For details please visit http://www.dimdim.com/license *
* *
**************************************************************************
*/
package com.dimdim.conference.ui.layout.client.widget;
//import com.google.gwt.user.client.Command;
//import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.DOM;
//import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.DockPanel;
import org.gwtwidgets.client.ui.PNGImage;
import asquare.gwt.tk.client.ui.ModalDialog;
import com.dimdim.conference.ui.common.client.util.DmGlassPanel;
import com.dimdim.conference.ui.dialogues.client.common.ImageButtonPanel2;
import com.dimdim.conference.ui.json.client.UIResourceObject;
import com.dimdim.conference.ui.model.client.ClientModel;
import com.dimdim.conference.ui.model.client.ConferenceGlobals;
import com.dimdim.conference.ui.model.client.ResourceModel;
/**
* @author Jayant Pandit
* @email [email protected]
*
*/
public class MeetingAssistentDialog extends ModalDialog implements ClickListener
{
protected boolean dialogDrawn = false;
protected DockPanel headerPanel1;
// protected DockPanel headerPanel2;
protected PNGImage closeButton;
// protected ImageButtonPanel desktopButton;
// protected ImageButtonPanel pptButton;
// protected ImageButtonPanel whiteboardButton;
// protected boolean desktopEnabled = false;
// protected boolean whiteboardEnabled = false;
ConsoleMiddleLeftPanel middlePanel = null;
ResourceModel rm = null;
ImageButtonPanel2 desktopButton = null;
ImageButtonPanel2 whiteboardButton = null;
ResourceRoster resRoster = null;
UIResourceObject resource = null;
public MeetingAssistentDialog(ConsoleMiddleLeftPanel middlePanel)
{
// super("Dimdim Meeting Assistent");
// this.desktopEnabled = ConferenceGlobals.publisherEnabled;
// this.whiteboardEnabled = ConferenceGlobals.whiteboardEnabled;
this.middlePanel = middlePanel;
this.resRoster = middlePanel.getResourceRoster();
// Label l = new Label("Assistent");
// l.setStyleName("meeting-assistent-panel");
// add(l);
add(getContent());
// DOM.setAttribute(getElement(), "id", "MeetingAssistentDialog");
}
public void onClick(final Widget sender)
{
if(sender == desktopButton.getLine1() || sender == whiteboardButton.getLine1())
{
rm = ClientModel.getClientModel().getResourceModel();
if(sender == desktopButton.getLine1())
{
resource = rm.findResourceObjectByType(UIResourceObject.RESOURCE_TYPE_DESKTOP);
}
else if(sender == whiteboardButton.getLine1())
{
resource = rm.findResourceObjectByType(UIResourceObject.RESOURCE_TYPE_WHITEBOARD);
}
//now try to share the resource
//Window.alert("the resource "+resource);
if(resource != null)
{
hide();
resRoster.getResourceManager().getSharingController().startSharingIfNotActive(resource);
}
else
{
//here we have to show up a message.
//Window.alert("the resource is null so ignoring it..");
}
}
else
{
hide();
//Window.alert("Did not click on desktop or whiteboard");
}
}
protected Widget getContent()
{
VerticalPanel basePanel = new VerticalPanel();
// VerticalPanel basePanel2 = new VerticalPanel();
basePanel.setStyleName("meeting-assistent-panel");
headerPanel1 = new DockPanel();
headerPanel1.setStyleName("meeting-assistent-header-1");
closeButton = new PNGImage("images/assistent/close.png",16,16);
closeButton.addStyleName("anchor-cursor");
headerPanel1.add(closeButton,DockPanel.EAST);
headerPanel1.setCellHorizontalAlignment(closeButton,HorizontalPanel.ALIGN_RIGHT);
headerPanel1.setCellVerticalAlignment(closeButton,VerticalPanel.ALIGN_TOP);
closeButton.addClickListener(this);
Label filler1 = new Label(" ");
HorizontalPanel filler1Panel = new HorizontalPanel();
filler1Panel.add(filler1);
headerPanel1.add(filler1Panel,DockPanel.CENTER);
headerPanel1.setCellWidth(filler1Panel,"100%");
basePanel.add(headerPanel1);
basePanel.setCellHorizontalAlignment(headerPanel1,HorizontalPanel.ALIGN_RIGHT);
basePanel.setCellVerticalAlignment(headerPanel1,VerticalPanel.ALIGN_TOP);
basePanel.setCellWidth(headerPanel1,"100%");
// headerPanel2 = new DockPanel();
Label label = new Label(ConferenceGlobals.getDisplayString("meeting.assistant.title","What would you like to do with Web Meeting today?"));
label.setStyleName("meeting-assistent-header-2");
// headerPanel2.setStyleName("meeting-assistent-header-2");
// headerPanel2.add(label,DockPanel.CENTER);
// headerPanel2.setCellHorizontalAlignment(label,HorizontalPanel.ALIGN_CENTER);
// headerPanel2.setCellVerticalAlignment(label,VerticalPanel.ALIGN_TOP);
// headerPanel2.setCellWidth(label,"100%");
HorizontalPanel labelPanel = new HorizontalPanel();
labelPanel.add(label);
labelPanel.setCellHorizontalAlignment(label,HorizontalPanel.ALIGN_CENTER);
basePanel.add(labelPanel);
basePanel.setCellHorizontalAlignment(labelPanel,HorizontalPanel.ALIGN_CENTER);
basePanel.setCellVerticalAlignment(labelPanel,VerticalPanel.ALIGN_TOP);
basePanel.setCellWidth(labelPanel,"100%");
// basePanel.add(basePanel2);
// basePanel.setCellHorizontalAlignment(basePanel2,HorizontalPanel.ALIGN_CENTER);
// basePanel.setCellVerticalAlignment(basePanel2,VerticalPanel.ALIGN_TOP);
// basePanel.setCellWidth(basePanel2,"100%");
// ImageButtonPanel desktopButton = new ImageButtonPanel("Share Desktop Screen",null,
// "label-base","red-label-normal","red-label-mouseover");
String desktopButtonColor = "gray";
if (ConferenceGlobals.publisherEnabled)
{
desktopButtonColor = "red";
}
desktopButton = new ImageButtonPanel2(ConferenceGlobals.getDisplayString("meeting.assistant.desktop","Share Desktop Screen"),null,
desktopButtonColor);
basePanel.add(desktopButton);
basePanel.setCellHorizontalAlignment(desktopButton,HorizontalPanel.ALIGN_RIGHT);
basePanel.setCellVerticalAlignment(desktopButton,VerticalPanel.ALIGN_MIDDLE);
desktopButton.addClickListener(this);
String whiteboardButtonColor = "gray";
if (ConferenceGlobals.whiteboardEnabled)
{
whiteboardButtonColor = "green";
}
whiteboardButton = new ImageButtonPanel2(ConferenceGlobals.getDisplayString("meeting.assistant.whiteboard","Share Whiteboard"),null,
whiteboardButtonColor);
basePanel.add(whiteboardButton);
basePanel.setCellHorizontalAlignment(whiteboardButton,HorizontalPanel.ALIGN_RIGHT);
basePanel.setCellVerticalAlignment(whiteboardButton,VerticalPanel.ALIGN_MIDDLE);
whiteboardButton.addClickListener(this);
ImageButtonPanel2 pptButton = new ImageButtonPanel2(ConferenceGlobals.getDisplayString("meeting.assistant.presentation","Share a Presentation"),null,
"blue");
basePanel.add(pptButton);
basePanel.setCellHorizontalAlignment(pptButton,HorizontalPanel.ALIGN_RIGHT);
basePanel.setCellVerticalAlignment(pptButton,VerticalPanel.ALIGN_MIDDLE);
//Window.alert("click lietener = "+middlePanel.getShareButtonListener());
pptButton.addClickListener(this);
pptButton.addClickListener(middlePanel.getShareButtonListener());
Label label2 = new Label(" ");
basePanel.add(label2);
basePanel.setCellHorizontalAlignment(label2,HorizontalPanel.ALIGN_RIGHT);
basePanel.setCellVerticalAlignment(label2,VerticalPanel.ALIGN_MIDDLE);
ScrollPanel sPanel = new ScrollPanel();
sPanel.setSize("550px", "390px");
sPanel.add(basePanel);
return sPanel;
}
// protected Vector getFooterButtons()
// {
// return null;
// }
public void showMeetingAssistent()
{
if (!this.dialogDrawn)
{
// this.drawDialog();
this.dialogDrawn = true;
}
DmGlassPanel dgp = new DmGlassPanel(this);
dgp.show();
// this.show();
}
}
| MarcosBL/DimSim | WebApps/ConsoleII/src/com/dimdim/conference/ui/layout/client/widget/MeetingAssistentDialog.java | 2,917 | // DOM.setAttribute(getElement(), "id", "MeetingAssistentDialog"); | line_comment | nl | /*
**************************************************************************
* *
* DDDDD iii DDDDD iii *
* DD DD mm mm mmmm DD DD mm mm mmmm *
* DD DD iii mmm mm mm DD DD iii mmm mm mm *
* DD DD iii mmm mm mm DD DD iii mmm mm mm *
* DDDDDD iii mmm mm mm DDDDDD iii mmm mm mm *
* *
**************************************************************************
**************************************************************************
* *
* Part of the DimDim V 1.0 Codebase (http://www.dimdim.com) *
* *
* Copyright (c) 2006 Communiva Inc. All Rights Reserved. *
* *
* *
* This code is licensed under the DimDim License *
* For details please visit http://www.dimdim.com/license *
* *
**************************************************************************
*/
package com.dimdim.conference.ui.layout.client.widget;
//import com.google.gwt.user.client.Command;
//import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.DOM;
//import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.DockPanel;
import org.gwtwidgets.client.ui.PNGImage;
import asquare.gwt.tk.client.ui.ModalDialog;
import com.dimdim.conference.ui.common.client.util.DmGlassPanel;
import com.dimdim.conference.ui.dialogues.client.common.ImageButtonPanel2;
import com.dimdim.conference.ui.json.client.UIResourceObject;
import com.dimdim.conference.ui.model.client.ClientModel;
import com.dimdim.conference.ui.model.client.ConferenceGlobals;
import com.dimdim.conference.ui.model.client.ResourceModel;
/**
* @author Jayant Pandit
* @email [email protected]
*
*/
public class MeetingAssistentDialog extends ModalDialog implements ClickListener
{
protected boolean dialogDrawn = false;
protected DockPanel headerPanel1;
// protected DockPanel headerPanel2;
protected PNGImage closeButton;
// protected ImageButtonPanel desktopButton;
// protected ImageButtonPanel pptButton;
// protected ImageButtonPanel whiteboardButton;
// protected boolean desktopEnabled = false;
// protected boolean whiteboardEnabled = false;
ConsoleMiddleLeftPanel middlePanel = null;
ResourceModel rm = null;
ImageButtonPanel2 desktopButton = null;
ImageButtonPanel2 whiteboardButton = null;
ResourceRoster resRoster = null;
UIResourceObject resource = null;
public MeetingAssistentDialog(ConsoleMiddleLeftPanel middlePanel)
{
// super("Dimdim Meeting Assistent");
// this.desktopEnabled = ConferenceGlobals.publisherEnabled;
// this.whiteboardEnabled = ConferenceGlobals.whiteboardEnabled;
this.middlePanel = middlePanel;
this.resRoster = middlePanel.getResourceRoster();
// Label l = new Label("Assistent");
// l.setStyleName("meeting-assistent-panel");
// add(l);
add(getContent());
// DOM.setAttribute(getElement(), "id",<SUF>
}
public void onClick(final Widget sender)
{
if(sender == desktopButton.getLine1() || sender == whiteboardButton.getLine1())
{
rm = ClientModel.getClientModel().getResourceModel();
if(sender == desktopButton.getLine1())
{
resource = rm.findResourceObjectByType(UIResourceObject.RESOURCE_TYPE_DESKTOP);
}
else if(sender == whiteboardButton.getLine1())
{
resource = rm.findResourceObjectByType(UIResourceObject.RESOURCE_TYPE_WHITEBOARD);
}
//now try to share the resource
//Window.alert("the resource "+resource);
if(resource != null)
{
hide();
resRoster.getResourceManager().getSharingController().startSharingIfNotActive(resource);
}
else
{
//here we have to show up a message.
//Window.alert("the resource is null so ignoring it..");
}
}
else
{
hide();
//Window.alert("Did not click on desktop or whiteboard");
}
}
protected Widget getContent()
{
VerticalPanel basePanel = new VerticalPanel();
// VerticalPanel basePanel2 = new VerticalPanel();
basePanel.setStyleName("meeting-assistent-panel");
headerPanel1 = new DockPanel();
headerPanel1.setStyleName("meeting-assistent-header-1");
closeButton = new PNGImage("images/assistent/close.png",16,16);
closeButton.addStyleName("anchor-cursor");
headerPanel1.add(closeButton,DockPanel.EAST);
headerPanel1.setCellHorizontalAlignment(closeButton,HorizontalPanel.ALIGN_RIGHT);
headerPanel1.setCellVerticalAlignment(closeButton,VerticalPanel.ALIGN_TOP);
closeButton.addClickListener(this);
Label filler1 = new Label(" ");
HorizontalPanel filler1Panel = new HorizontalPanel();
filler1Panel.add(filler1);
headerPanel1.add(filler1Panel,DockPanel.CENTER);
headerPanel1.setCellWidth(filler1Panel,"100%");
basePanel.add(headerPanel1);
basePanel.setCellHorizontalAlignment(headerPanel1,HorizontalPanel.ALIGN_RIGHT);
basePanel.setCellVerticalAlignment(headerPanel1,VerticalPanel.ALIGN_TOP);
basePanel.setCellWidth(headerPanel1,"100%");
// headerPanel2 = new DockPanel();
Label label = new Label(ConferenceGlobals.getDisplayString("meeting.assistant.title","What would you like to do with Web Meeting today?"));
label.setStyleName("meeting-assistent-header-2");
// headerPanel2.setStyleName("meeting-assistent-header-2");
// headerPanel2.add(label,DockPanel.CENTER);
// headerPanel2.setCellHorizontalAlignment(label,HorizontalPanel.ALIGN_CENTER);
// headerPanel2.setCellVerticalAlignment(label,VerticalPanel.ALIGN_TOP);
// headerPanel2.setCellWidth(label,"100%");
HorizontalPanel labelPanel = new HorizontalPanel();
labelPanel.add(label);
labelPanel.setCellHorizontalAlignment(label,HorizontalPanel.ALIGN_CENTER);
basePanel.add(labelPanel);
basePanel.setCellHorizontalAlignment(labelPanel,HorizontalPanel.ALIGN_CENTER);
basePanel.setCellVerticalAlignment(labelPanel,VerticalPanel.ALIGN_TOP);
basePanel.setCellWidth(labelPanel,"100%");
// basePanel.add(basePanel2);
// basePanel.setCellHorizontalAlignment(basePanel2,HorizontalPanel.ALIGN_CENTER);
// basePanel.setCellVerticalAlignment(basePanel2,VerticalPanel.ALIGN_TOP);
// basePanel.setCellWidth(basePanel2,"100%");
// ImageButtonPanel desktopButton = new ImageButtonPanel("Share Desktop Screen",null,
// "label-base","red-label-normal","red-label-mouseover");
String desktopButtonColor = "gray";
if (ConferenceGlobals.publisherEnabled)
{
desktopButtonColor = "red";
}
desktopButton = new ImageButtonPanel2(ConferenceGlobals.getDisplayString("meeting.assistant.desktop","Share Desktop Screen"),null,
desktopButtonColor);
basePanel.add(desktopButton);
basePanel.setCellHorizontalAlignment(desktopButton,HorizontalPanel.ALIGN_RIGHT);
basePanel.setCellVerticalAlignment(desktopButton,VerticalPanel.ALIGN_MIDDLE);
desktopButton.addClickListener(this);
String whiteboardButtonColor = "gray";
if (ConferenceGlobals.whiteboardEnabled)
{
whiteboardButtonColor = "green";
}
whiteboardButton = new ImageButtonPanel2(ConferenceGlobals.getDisplayString("meeting.assistant.whiteboard","Share Whiteboard"),null,
whiteboardButtonColor);
basePanel.add(whiteboardButton);
basePanel.setCellHorizontalAlignment(whiteboardButton,HorizontalPanel.ALIGN_RIGHT);
basePanel.setCellVerticalAlignment(whiteboardButton,VerticalPanel.ALIGN_MIDDLE);
whiteboardButton.addClickListener(this);
ImageButtonPanel2 pptButton = new ImageButtonPanel2(ConferenceGlobals.getDisplayString("meeting.assistant.presentation","Share a Presentation"),null,
"blue");
basePanel.add(pptButton);
basePanel.setCellHorizontalAlignment(pptButton,HorizontalPanel.ALIGN_RIGHT);
basePanel.setCellVerticalAlignment(pptButton,VerticalPanel.ALIGN_MIDDLE);
//Window.alert("click lietener = "+middlePanel.getShareButtonListener());
pptButton.addClickListener(this);
pptButton.addClickListener(middlePanel.getShareButtonListener());
Label label2 = new Label(" ");
basePanel.add(label2);
basePanel.setCellHorizontalAlignment(label2,HorizontalPanel.ALIGN_RIGHT);
basePanel.setCellVerticalAlignment(label2,VerticalPanel.ALIGN_MIDDLE);
ScrollPanel sPanel = new ScrollPanel();
sPanel.setSize("550px", "390px");
sPanel.add(basePanel);
return sPanel;
}
// protected Vector getFooterButtons()
// {
// return null;
// }
public void showMeetingAssistent()
{
if (!this.dialogDrawn)
{
// this.drawDialog();
this.dialogDrawn = true;
}
DmGlassPanel dgp = new DmGlassPanel(this);
dgp.show();
// this.show();
}
}
|
111205_9 | package de.blau.android.util.collections;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import android.annotation.SuppressLint;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import de.blau.android.osm.OsmElement;
import de.blau.android.osm.OsmElementFactory;
/**
* long to OsmElement HashMap
*
* This only implements the, roughly equivalent to Map, interfaces that we current (might) need and is rather Vespucci
* specific, however could easily be adopted to different implementations of an OSM element as long as you can easily
* get the element id.
*
* This implementation will only require at most 8*next_power_of_2(capacity/fillfactor) space.
*
* This is based on public domain code see http://unlicense.org from Mikhail Vorontsov, see https://github.com/mikvor
* The original code used a interleaved key/value implementation in one array, however since the stored value already
* contains the key additional copies are not needed.
*
* This code is not thread safe with the exception of iterating over the array when rehashing and requires external
* synchronization if inserts and removals need to be consistent.
*
* @version 0.3
* @author simon
*/
@SuppressLint("UseSparseArrays")
public class LongOsmElementMap<V extends OsmElement> implements Iterable<V>, Serializable {
/**
*
*/
private static final long serialVersionUID = 3L; // NOTE if you change the
// hashing algorithm you
// need to increment
// this
public interface SelectElement<W extends OsmElement> {
/**
* Select an element
*
* @param element an OsmELement of type W
* @return true if the element should be selected
*/
boolean select(@NonNull W element);
}
private static final OsmElement FREE_KEY = null;
private final OsmElement removedKey; // Note see constructor for important note
private static final float DEFAULT_FILLFACTOR = 0.75f;
private static final int DEFAULT_CAPACITY = 16;
/** Keys and values */
private OsmElement[] data;
/** Fill factor, must be between (0 and 1) */
private final float fillFactor;
/** We will resize a map once it reaches this size */
private int threshold;
/** Current map size */
private int size;
/** Mask to calculate the original position */
private long mask;
/**
* Create a new map with default values for capacity and fill factor
*/
public LongOsmElementMap() {
this(DEFAULT_CAPACITY, DEFAULT_FILLFACTOR);
}
/**
* Create a new map with the specified size and the default fill factor
*
* @param size initial size of the map
*/
public LongOsmElementMap(final int size) {
this(size, DEFAULT_FILLFACTOR);
}
/**
* Create a new map with the specified size and fill factor
*
* @param size initial size of the map
* @param fillFactor target fill factor
*/
private LongOsmElementMap(final int size, final float fillFactor) {
if (fillFactor <= 0 || fillFactor >= 1) {
throw new IllegalArgumentException("FillFactor must be in (0, 1)");
}
if (size <= 0) {
throw new IllegalArgumentException("Size must be positive!");
}
final int capacity = Tools.arraySize(size, fillFactor);
this.mask = capacity - 1L;
this.fillFactor = fillFactor;
data = new OsmElement[capacity];
this.threshold = (int) (capacity * fillFactor);
// NOTE can't be static as it has to be serialized and de-serialized
removedKey = OsmElementFactory.createNode(Long.MIN_VALUE, 1, -1, OsmElement.STATE_CREATED, 0, 0);
}
/**
* Create a shallow copy of the specified map
*
* @param map the map to copy
*/
public LongOsmElementMap(@NonNull LongOsmElementMap<? extends V> map) {
mask = map.mask;
fillFactor = map.fillFactor;
threshold = map.threshold;
size = map.size;
removedKey = map.removedKey;
data = Arrays.copyOf(map.data, map.data.length);
}
/**
* Return a single element with the specified key
*
* @param key the key we want to return a value for
* @return the required element or null if it cannot be found
*/
@SuppressWarnings("unchecked")
@Nullable
public V get(final long key) {
int ptr = (int) (Tools.phiMix(key) & mask);
OsmElement e = data[ptr];
if (e == FREE_KEY) {
return null;
}
if (e.getOsmId() == key) {
return (V) e;
}
while (true) {
ptr = (int) ((ptr + 1) & mask); // that's next index
e = data[ptr];
if (e == FREE_KEY) {
return null;
}
if (e.getOsmId() == key) {
return (V) e;
}
}
}
/**
* Add a single element to the map
*
* @param key the key
* @param value the value
* @return the previous value if one existed
*/
@SuppressWarnings("unchecked")
@Nullable
public V put(final long key, @Nullable final V value) {
int ptr = (int) (Tools.phiMix(key) & mask);
OsmElement e = data[ptr];
if (e == FREE_KEY) { // end of chain already
data[ptr] = value;
if (size >= threshold) {
rehash(data.length * 2); // size is set inside
} else {
++size;
}
return null;
} else if (e.getOsmId() == key) { // we check FREE and REMOVED prior to this call
data[ptr] = value;
return (V) e;
}
int firstRemoved = -1;
if (e == removedKey) {
firstRemoved = ptr; // we may find a key later
}
while (true) {
ptr = (int) ((ptr + 1) & mask); // the next index calculation
e = data[ptr];
if (e == FREE_KEY) {
if (firstRemoved != -1) {
ptr = firstRemoved;
}
data[ptr] = value;
if (size >= threshold) {
rehash(data.length * 2); // size is set inside
} else {
++size;
}
return null;
} else if (e.getOsmId() == key) {
data[ptr] = value;
return (V) e;
} else if (e == removedKey && firstRemoved == -1) {
firstRemoved = ptr;
}
}
}
/**
* Add all elements from map
*
* @param map the Map to add
*/
public void putAll(@NonNull LongOsmElementMap<V> map) {
ensureCapacity(data.length + map.size());
for (V e : map) { // trivial implementation for now
put(e.getOsmId(), e);
}
}
/**
* Add all elements from c
*
* @param c the Collection to add
*/
public void putAll(@NonNull Collection<V> c) {
ensureCapacity(data.length + c.size());
for (V e : c) { // trivial implementation for now
put(e.getOsmId(), e);
}
}
/**
* Remove element with the specified key from the map, does not shrink the underlying array
*
* @param key the key we want to remove
* @return the removed value or null if it didn't exist
*/
@Nullable
public OsmElement remove(final long key) {
int ptr = (int) (Tools.phiMix(key) & mask);
OsmElement e = data[ptr];
if (e == FREE_KEY) {
return null; // end of chain already
} else if (e.getOsmId() == key) { // we check FREE and REMOVED prior to this call
--size;
if (data[(int) ((ptr + 1) & mask)] == FREE_KEY) { // this shortens the chain
data[ptr] = FREE_KEY;
} else {
data[ptr] = removedKey;
}
return e;
}
while (true) {
ptr = (int) ((ptr + 1) & mask); // that's next index calculation
e = data[ptr];
if (e == FREE_KEY) {
return null;
} else if (e.getOsmId() == key) {
--size;
if (data[(int) ((ptr + 1) & mask)] == FREE_KEY) { // this shortens the chain
data[ptr] = FREE_KEY;
} else {
data[ptr] = removedKey;
}
return e;
}
}
}
/**
* Return true if the map contains an object with the specified key
*
* @param key the key to check
* @return true if an entry for key could be found
*/
public boolean containsKey(long key) {
int ptr = (int) (Tools.phiMix(key) & mask);
OsmElement e = data[ptr];
if (e == FREE_KEY) {
return false;
}
if (e.getOsmId() == key) { // note this assumes REMOVED_KEY doesn't match
return true;
}
while (true) {
ptr = (int) ((ptr + 1) & mask); // the next index
e = data[ptr];
if (e == FREE_KEY) {
return false;
}
if (e.getOsmId() == key) {
return true;
}
}
}
/**
* Return all values in the map. Note: they are returned unordered
*
* @return a List of the values
*/
@SuppressWarnings("unchecked")
@NonNull
public List<V> values() {
int found = 0;
List<V> result = new ArrayList<>(size);
for (OsmElement v : data) {
if (v != FREE_KEY && v != removedKey) {
result.add((V) v);
found++;
if (found >= size) { // found all
break;
}
}
}
return result;
}
/**
* Return specific values
*
* @param result pre-allocated List
* @param s function for selecting the element
* @return a List of the values
*/
@SuppressWarnings("unchecked")
@NonNull
public List<V> values(@NonNull List<V> result, @NonNull SelectElement<V> s) {
int found = 0;
for (OsmElement v : data) {
if (v != FREE_KEY && v != removedKey) {
if (s.select((V) v)) {
result.add((V) v);
}
found++;
if (found >= size) { // found all
break;
}
}
}
return result;
}
/**
* Return the number of elements in the map
*
* @return the number of elements in the map
*/
public int size() {
return size;
}
/**
* Return true if the map is empty
*
* @return true if the map is empty
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Provide capacity for minimumCapacity elements without need for growing the underlying array and rehashing.
*
* @param minimumCapacity the capacity to ensure
*/
private void ensureCapacity(int minimumCapacity) {
int newCapacity = Tools.arraySize(minimumCapacity, fillFactor);
if (newCapacity > data.length) {
rehash(newCapacity);
}
}
/**
* Rehash the map
*
* @param newCapacity new size
*/
@SuppressWarnings("unchecked")
private void rehash(final int newCapacity) {
synchronized (this) {
threshold = (int) (newCapacity * fillFactor);
mask = newCapacity - 1L;
final int oldCapacity = data.length;
final OsmElement[] oldData = data;
data = new OsmElement[newCapacity];
size = 0;
for (int i = 0; i < oldCapacity; i++) {
final OsmElement e = oldData[i];
if (e != FREE_KEY && e != removedKey) {
put(e.getOsmId(), (V) e);
}
}
}
}
/**
* Rehash the map - needed when id's have changed etc.
*/
@SuppressWarnings("unchecked")
public void rehash() {
synchronized (this) {
final OsmElement[] oldData = data;
data = new OsmElement[data.length];
size = 0;
for (int i = 0; i < data.length; i++) {
final OsmElement e = oldData[i];
if (e != FREE_KEY && e != removedKey) {
put(e.getOsmId(), (V) e);
}
}
}
}
/**
* Iterator that skips FREE_KEY and REMOVED_KEY values
*/
@NonNull
@Override
public Iterator<V> iterator() {
return new SafeIterator();
}
class SafeIterator implements Iterator<V> {
int index = 0;
int found = 0;
int sizeTemp = 0;
OsmElement[] dataTemp = null;
OsmElement cachedNext = null;
/**
* Construct a new iterator
*/
SafeIterator() {
synchronized (LongOsmElementMap.this) {
sizeTemp = size;
dataTemp = data;
}
}
@Override
public boolean hasNext() {
cachedNext = null;
while (true) {
if (found >= sizeTemp || index >= dataTemp.length) { // already returned all elements
return false;
} else {
OsmElement e = dataTemp[index];
if (e != FREE_KEY && e != removedKey) {
found++;
cachedNext = e;
return true;
} else {
index++;
}
}
}
}
@SuppressWarnings("unchecked")
@Override
public V next() {
if (cachedNext != null) {
index++;
return (V) cachedNext;
}
while (true) {
if (index >= dataTemp.length) { // already returned all elements
throw new NoSuchElementException();
} else {
OsmElement e = dataTemp[index];
if (e != FREE_KEY && e != removedKey) {
index++;
return (V) e;
} else {
index++;
}
}
}
}
@Override
public void remove() {
throw new UnsupportedOperationException(); // could be implemented
}
}
/**
* for stats and debugging
*
* @return a Map containing some statistics
*/
@NonNull
public Map<Integer, Integer> getChainStats() {
Map<Integer, Integer> result = new HashMap<>();
for (V v : values()) {
int len = 0;
long key = v.getOsmId();
int ptr = (int) (Tools.phiMix(key) & mask);
OsmElement e = data[ptr];
if (e.getOsmId() == key) { // note this assumes REMOVED_KEY doesn't match
if (result.containsKey(len)) {
result.put(len, result.get(len) + 1);
} else {
result.put(len, 1);
}
continue;
}
while (true) {
len++;
ptr = (int) ((ptr + 1) & mask); // the next index
e = data[ptr];
if (e.getOsmId() == key) {
if (result.containsKey(len)) {
result.put(len, result.get(len) + 1);
} else {
result.put(len, 1);
}
break;
}
}
}
return result;
}
}
| MarcusWolschon/osmeditor4android | src/main/java/de/blau/android/util/collections/LongOsmElementMap.java | 4,588 | /** Current map size */ | block_comment | nl | package de.blau.android.util.collections;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import android.annotation.SuppressLint;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import de.blau.android.osm.OsmElement;
import de.blau.android.osm.OsmElementFactory;
/**
* long to OsmElement HashMap
*
* This only implements the, roughly equivalent to Map, interfaces that we current (might) need and is rather Vespucci
* specific, however could easily be adopted to different implementations of an OSM element as long as you can easily
* get the element id.
*
* This implementation will only require at most 8*next_power_of_2(capacity/fillfactor) space.
*
* This is based on public domain code see http://unlicense.org from Mikhail Vorontsov, see https://github.com/mikvor
* The original code used a interleaved key/value implementation in one array, however since the stored value already
* contains the key additional copies are not needed.
*
* This code is not thread safe with the exception of iterating over the array when rehashing and requires external
* synchronization if inserts and removals need to be consistent.
*
* @version 0.3
* @author simon
*/
@SuppressLint("UseSparseArrays")
public class LongOsmElementMap<V extends OsmElement> implements Iterable<V>, Serializable {
/**
*
*/
private static final long serialVersionUID = 3L; // NOTE if you change the
// hashing algorithm you
// need to increment
// this
public interface SelectElement<W extends OsmElement> {
/**
* Select an element
*
* @param element an OsmELement of type W
* @return true if the element should be selected
*/
boolean select(@NonNull W element);
}
private static final OsmElement FREE_KEY = null;
private final OsmElement removedKey; // Note see constructor for important note
private static final float DEFAULT_FILLFACTOR = 0.75f;
private static final int DEFAULT_CAPACITY = 16;
/** Keys and values */
private OsmElement[] data;
/** Fill factor, must be between (0 and 1) */
private final float fillFactor;
/** We will resize a map once it reaches this size */
private int threshold;
/** Current map size<SUF>*/
private int size;
/** Mask to calculate the original position */
private long mask;
/**
* Create a new map with default values for capacity and fill factor
*/
public LongOsmElementMap() {
this(DEFAULT_CAPACITY, DEFAULT_FILLFACTOR);
}
/**
* Create a new map with the specified size and the default fill factor
*
* @param size initial size of the map
*/
public LongOsmElementMap(final int size) {
this(size, DEFAULT_FILLFACTOR);
}
/**
* Create a new map with the specified size and fill factor
*
* @param size initial size of the map
* @param fillFactor target fill factor
*/
private LongOsmElementMap(final int size, final float fillFactor) {
if (fillFactor <= 0 || fillFactor >= 1) {
throw new IllegalArgumentException("FillFactor must be in (0, 1)");
}
if (size <= 0) {
throw new IllegalArgumentException("Size must be positive!");
}
final int capacity = Tools.arraySize(size, fillFactor);
this.mask = capacity - 1L;
this.fillFactor = fillFactor;
data = new OsmElement[capacity];
this.threshold = (int) (capacity * fillFactor);
// NOTE can't be static as it has to be serialized and de-serialized
removedKey = OsmElementFactory.createNode(Long.MIN_VALUE, 1, -1, OsmElement.STATE_CREATED, 0, 0);
}
/**
* Create a shallow copy of the specified map
*
* @param map the map to copy
*/
public LongOsmElementMap(@NonNull LongOsmElementMap<? extends V> map) {
mask = map.mask;
fillFactor = map.fillFactor;
threshold = map.threshold;
size = map.size;
removedKey = map.removedKey;
data = Arrays.copyOf(map.data, map.data.length);
}
/**
* Return a single element with the specified key
*
* @param key the key we want to return a value for
* @return the required element or null if it cannot be found
*/
@SuppressWarnings("unchecked")
@Nullable
public V get(final long key) {
int ptr = (int) (Tools.phiMix(key) & mask);
OsmElement e = data[ptr];
if (e == FREE_KEY) {
return null;
}
if (e.getOsmId() == key) {
return (V) e;
}
while (true) {
ptr = (int) ((ptr + 1) & mask); // that's next index
e = data[ptr];
if (e == FREE_KEY) {
return null;
}
if (e.getOsmId() == key) {
return (V) e;
}
}
}
/**
* Add a single element to the map
*
* @param key the key
* @param value the value
* @return the previous value if one existed
*/
@SuppressWarnings("unchecked")
@Nullable
public V put(final long key, @Nullable final V value) {
int ptr = (int) (Tools.phiMix(key) & mask);
OsmElement e = data[ptr];
if (e == FREE_KEY) { // end of chain already
data[ptr] = value;
if (size >= threshold) {
rehash(data.length * 2); // size is set inside
} else {
++size;
}
return null;
} else if (e.getOsmId() == key) { // we check FREE and REMOVED prior to this call
data[ptr] = value;
return (V) e;
}
int firstRemoved = -1;
if (e == removedKey) {
firstRemoved = ptr; // we may find a key later
}
while (true) {
ptr = (int) ((ptr + 1) & mask); // the next index calculation
e = data[ptr];
if (e == FREE_KEY) {
if (firstRemoved != -1) {
ptr = firstRemoved;
}
data[ptr] = value;
if (size >= threshold) {
rehash(data.length * 2); // size is set inside
} else {
++size;
}
return null;
} else if (e.getOsmId() == key) {
data[ptr] = value;
return (V) e;
} else if (e == removedKey && firstRemoved == -1) {
firstRemoved = ptr;
}
}
}
/**
* Add all elements from map
*
* @param map the Map to add
*/
public void putAll(@NonNull LongOsmElementMap<V> map) {
ensureCapacity(data.length + map.size());
for (V e : map) { // trivial implementation for now
put(e.getOsmId(), e);
}
}
/**
* Add all elements from c
*
* @param c the Collection to add
*/
public void putAll(@NonNull Collection<V> c) {
ensureCapacity(data.length + c.size());
for (V e : c) { // trivial implementation for now
put(e.getOsmId(), e);
}
}
/**
* Remove element with the specified key from the map, does not shrink the underlying array
*
* @param key the key we want to remove
* @return the removed value or null if it didn't exist
*/
@Nullable
public OsmElement remove(final long key) {
int ptr = (int) (Tools.phiMix(key) & mask);
OsmElement e = data[ptr];
if (e == FREE_KEY) {
return null; // end of chain already
} else if (e.getOsmId() == key) { // we check FREE and REMOVED prior to this call
--size;
if (data[(int) ((ptr + 1) & mask)] == FREE_KEY) { // this shortens the chain
data[ptr] = FREE_KEY;
} else {
data[ptr] = removedKey;
}
return e;
}
while (true) {
ptr = (int) ((ptr + 1) & mask); // that's next index calculation
e = data[ptr];
if (e == FREE_KEY) {
return null;
} else if (e.getOsmId() == key) {
--size;
if (data[(int) ((ptr + 1) & mask)] == FREE_KEY) { // this shortens the chain
data[ptr] = FREE_KEY;
} else {
data[ptr] = removedKey;
}
return e;
}
}
}
/**
* Return true if the map contains an object with the specified key
*
* @param key the key to check
* @return true if an entry for key could be found
*/
public boolean containsKey(long key) {
int ptr = (int) (Tools.phiMix(key) & mask);
OsmElement e = data[ptr];
if (e == FREE_KEY) {
return false;
}
if (e.getOsmId() == key) { // note this assumes REMOVED_KEY doesn't match
return true;
}
while (true) {
ptr = (int) ((ptr + 1) & mask); // the next index
e = data[ptr];
if (e == FREE_KEY) {
return false;
}
if (e.getOsmId() == key) {
return true;
}
}
}
/**
* Return all values in the map. Note: they are returned unordered
*
* @return a List of the values
*/
@SuppressWarnings("unchecked")
@NonNull
public List<V> values() {
int found = 0;
List<V> result = new ArrayList<>(size);
for (OsmElement v : data) {
if (v != FREE_KEY && v != removedKey) {
result.add((V) v);
found++;
if (found >= size) { // found all
break;
}
}
}
return result;
}
/**
* Return specific values
*
* @param result pre-allocated List
* @param s function for selecting the element
* @return a List of the values
*/
@SuppressWarnings("unchecked")
@NonNull
public List<V> values(@NonNull List<V> result, @NonNull SelectElement<V> s) {
int found = 0;
for (OsmElement v : data) {
if (v != FREE_KEY && v != removedKey) {
if (s.select((V) v)) {
result.add((V) v);
}
found++;
if (found >= size) { // found all
break;
}
}
}
return result;
}
/**
* Return the number of elements in the map
*
* @return the number of elements in the map
*/
public int size() {
return size;
}
/**
* Return true if the map is empty
*
* @return true if the map is empty
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Provide capacity for minimumCapacity elements without need for growing the underlying array and rehashing.
*
* @param minimumCapacity the capacity to ensure
*/
private void ensureCapacity(int minimumCapacity) {
int newCapacity = Tools.arraySize(minimumCapacity, fillFactor);
if (newCapacity > data.length) {
rehash(newCapacity);
}
}
/**
* Rehash the map
*
* @param newCapacity new size
*/
@SuppressWarnings("unchecked")
private void rehash(final int newCapacity) {
synchronized (this) {
threshold = (int) (newCapacity * fillFactor);
mask = newCapacity - 1L;
final int oldCapacity = data.length;
final OsmElement[] oldData = data;
data = new OsmElement[newCapacity];
size = 0;
for (int i = 0; i < oldCapacity; i++) {
final OsmElement e = oldData[i];
if (e != FREE_KEY && e != removedKey) {
put(e.getOsmId(), (V) e);
}
}
}
}
/**
* Rehash the map - needed when id's have changed etc.
*/
@SuppressWarnings("unchecked")
public void rehash() {
synchronized (this) {
final OsmElement[] oldData = data;
data = new OsmElement[data.length];
size = 0;
for (int i = 0; i < data.length; i++) {
final OsmElement e = oldData[i];
if (e != FREE_KEY && e != removedKey) {
put(e.getOsmId(), (V) e);
}
}
}
}
/**
* Iterator that skips FREE_KEY and REMOVED_KEY values
*/
@NonNull
@Override
public Iterator<V> iterator() {
return new SafeIterator();
}
class SafeIterator implements Iterator<V> {
int index = 0;
int found = 0;
int sizeTemp = 0;
OsmElement[] dataTemp = null;
OsmElement cachedNext = null;
/**
* Construct a new iterator
*/
SafeIterator() {
synchronized (LongOsmElementMap.this) {
sizeTemp = size;
dataTemp = data;
}
}
@Override
public boolean hasNext() {
cachedNext = null;
while (true) {
if (found >= sizeTemp || index >= dataTemp.length) { // already returned all elements
return false;
} else {
OsmElement e = dataTemp[index];
if (e != FREE_KEY && e != removedKey) {
found++;
cachedNext = e;
return true;
} else {
index++;
}
}
}
}
@SuppressWarnings("unchecked")
@Override
public V next() {
if (cachedNext != null) {
index++;
return (V) cachedNext;
}
while (true) {
if (index >= dataTemp.length) { // already returned all elements
throw new NoSuchElementException();
} else {
OsmElement e = dataTemp[index];
if (e != FREE_KEY && e != removedKey) {
index++;
return (V) e;
} else {
index++;
}
}
}
}
@Override
public void remove() {
throw new UnsupportedOperationException(); // could be implemented
}
}
/**
* for stats and debugging
*
* @return a Map containing some statistics
*/
@NonNull
public Map<Integer, Integer> getChainStats() {
Map<Integer, Integer> result = new HashMap<>();
for (V v : values()) {
int len = 0;
long key = v.getOsmId();
int ptr = (int) (Tools.phiMix(key) & mask);
OsmElement e = data[ptr];
if (e.getOsmId() == key) { // note this assumes REMOVED_KEY doesn't match
if (result.containsKey(len)) {
result.put(len, result.get(len) + 1);
} else {
result.put(len, 1);
}
continue;
}
while (true) {
len++;
ptr = (int) ((ptr + 1) & mask); // the next index
e = data[ptr];
if (e.getOsmId() == key) {
if (result.containsKey(len)) {
result.put(len, result.get(len) + 1);
} else {
result.put(len, 1);
}
break;
}
}
}
return result;
}
}
|
27630_2 | package model;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
/**
*
* @author Dries Janse, Marie Verdonck, Bram Van Asschodt
*
*/
public class HumanPlayer extends Observable {
private String naam;
private ArrayList<Ship> schepen = new ArrayList<Ship>();
public static final int MAX_SCHEPEN = 5;
public HumanPlayer() {
this("defaultName");
}
public HumanPlayer(String naam) {
this.setNaam(naam);
}
public String getNaam() {
return naam;
}
public void setNaam(String naam) {
if (naam == null || naam.trim().isEmpty()) {
this.naam = "Player1";
} else {
this.naam = naam;
}
}
public Ship getShipContainsNumber(int nummer) {
for (Ship ship : this.getSchepen()) {
if (ship.getSchipNummers().contains(nummer)) {
return ship;
}
}
return null;
}
public boolean addHitToShip(int nummer) {
// returns if ship was destroyed
Ship ship = this.getShipContainsNumber(nummer);
if (ship == null) {
throw new DomainException("Schip werd niet gevonden!");
}
ship.addNummerHit(nummer);
boolean destroyed = false;
if (ship.getSchipNummershit().containsAll(ship.getSchipNummers())) {
destroyed = true;
}
this.setChanged();
this.notifyObservers();
return destroyed;
}
public ArrayList<Ship> getAllDestroyedShips() {
ArrayList<Ship> destroyedShips = new ArrayList<Ship>();
for (Ship ship : this.getSchepen()) {
if (ship.getSchipNummershit().containsAll(ship.getSchipNummers())) {
destroyedShips.add(ship);
}
}
return destroyedShips;
}
public boolean isGameOver() {
boolean gameOver = false;
if (this.getAllDestroyedShips().containsAll(this.getSchepen())) {
gameOver = true;
}
return gameOver;
}
public ArrayList<Integer> allNumbersOfDestroyedShips() {
ArrayList<Integer> destroyedNumbers = new ArrayList<Integer>();
for (Ship s : this.getAllDestroyedShips()) {
destroyedNumbers.addAll(s.getSchipNummers());
}
return destroyedNumbers;
}
public void addHitToShip(int nummer, Ship schiep) {
Ship ship = schiep;
if (ship == null) {
throw new DomainException("Schip werd niet gevonden!");
}
ship.addNummerHit(nummer);
}
public ArrayList<Ship> getSchepen() {
return schepen;
}
public int getAantalSchepen() {
return this.getSchepen().size();
}
public List<Integer> getAllShipNumbers() {
List<Integer> schipnummers = new ArrayList<Integer>();
for (Ship ship : schepen) {
schipnummers.addAll(ship.getSchipNummers());
}
return schipnummers;
}
public void addShip(Ship ship) {
if (maxAantalSchepen()) {
throw new DomainException("Je kan niet meer dan 5 schepen plaatsen!");
}
if (!this.maxAantalSchepenType(ship)) {
throw new DomainException("Van dit type kan men niet meer schepen plaatsen!");
}
if (!this.overlaptNietMetAnderSchip(ship)) {
throw new DomainException("Dit schipt is te dicht bij een ander schip geplaatst!");
}
this.schepen.add(ship);
}
public void addShip(ShipType schipType, Direction richting, int beginVakje) {
Ship ship = new Ship(schipType, richting, beginVakje);
this.addShip(ship);
}
public Ship getlastAddedShip() {
return schepen.get(schepen.size() - 1);
}
private boolean maxAantalSchepen() {
return schepen.size() == MAX_SCHEPEN;
}
private boolean maxAantalSchepenType(Ship ship) {
int aantal = 0;
for (Ship s : this.getSchepen()) {
if (s.getSchipType().equals(ship.getSchipType())) {
aantal++;
}
}
// true als schip mag toevoegen
return ship.getSchipType().getAantalToegelatenSchepen() > aantal;
}
private boolean overlaptNietMetAnderSchip(Ship ship) {
for (Ship s : this.getSchepen()) {
for (Integer i : ship.getSchipNummers()) {
if (s.getNummersRondomSchip().contains(i) || s.getSchipNummers().contains(i)) {
return false;
}
}
}
return true;
}
}
| MarieVerdonck/BattleShip---Project-OO | src/model/HumanPlayer.java | 1,384 | // true als schip mag toevoegen | line_comment | nl | package model;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
/**
*
* @author Dries Janse, Marie Verdonck, Bram Van Asschodt
*
*/
public class HumanPlayer extends Observable {
private String naam;
private ArrayList<Ship> schepen = new ArrayList<Ship>();
public static final int MAX_SCHEPEN = 5;
public HumanPlayer() {
this("defaultName");
}
public HumanPlayer(String naam) {
this.setNaam(naam);
}
public String getNaam() {
return naam;
}
public void setNaam(String naam) {
if (naam == null || naam.trim().isEmpty()) {
this.naam = "Player1";
} else {
this.naam = naam;
}
}
public Ship getShipContainsNumber(int nummer) {
for (Ship ship : this.getSchepen()) {
if (ship.getSchipNummers().contains(nummer)) {
return ship;
}
}
return null;
}
public boolean addHitToShip(int nummer) {
// returns if ship was destroyed
Ship ship = this.getShipContainsNumber(nummer);
if (ship == null) {
throw new DomainException("Schip werd niet gevonden!");
}
ship.addNummerHit(nummer);
boolean destroyed = false;
if (ship.getSchipNummershit().containsAll(ship.getSchipNummers())) {
destroyed = true;
}
this.setChanged();
this.notifyObservers();
return destroyed;
}
public ArrayList<Ship> getAllDestroyedShips() {
ArrayList<Ship> destroyedShips = new ArrayList<Ship>();
for (Ship ship : this.getSchepen()) {
if (ship.getSchipNummershit().containsAll(ship.getSchipNummers())) {
destroyedShips.add(ship);
}
}
return destroyedShips;
}
public boolean isGameOver() {
boolean gameOver = false;
if (this.getAllDestroyedShips().containsAll(this.getSchepen())) {
gameOver = true;
}
return gameOver;
}
public ArrayList<Integer> allNumbersOfDestroyedShips() {
ArrayList<Integer> destroyedNumbers = new ArrayList<Integer>();
for (Ship s : this.getAllDestroyedShips()) {
destroyedNumbers.addAll(s.getSchipNummers());
}
return destroyedNumbers;
}
public void addHitToShip(int nummer, Ship schiep) {
Ship ship = schiep;
if (ship == null) {
throw new DomainException("Schip werd niet gevonden!");
}
ship.addNummerHit(nummer);
}
public ArrayList<Ship> getSchepen() {
return schepen;
}
public int getAantalSchepen() {
return this.getSchepen().size();
}
public List<Integer> getAllShipNumbers() {
List<Integer> schipnummers = new ArrayList<Integer>();
for (Ship ship : schepen) {
schipnummers.addAll(ship.getSchipNummers());
}
return schipnummers;
}
public void addShip(Ship ship) {
if (maxAantalSchepen()) {
throw new DomainException("Je kan niet meer dan 5 schepen plaatsen!");
}
if (!this.maxAantalSchepenType(ship)) {
throw new DomainException("Van dit type kan men niet meer schepen plaatsen!");
}
if (!this.overlaptNietMetAnderSchip(ship)) {
throw new DomainException("Dit schipt is te dicht bij een ander schip geplaatst!");
}
this.schepen.add(ship);
}
public void addShip(ShipType schipType, Direction richting, int beginVakje) {
Ship ship = new Ship(schipType, richting, beginVakje);
this.addShip(ship);
}
public Ship getlastAddedShip() {
return schepen.get(schepen.size() - 1);
}
private boolean maxAantalSchepen() {
return schepen.size() == MAX_SCHEPEN;
}
private boolean maxAantalSchepenType(Ship ship) {
int aantal = 0;
for (Ship s : this.getSchepen()) {
if (s.getSchipType().equals(ship.getSchipType())) {
aantal++;
}
}
// true als<SUF>
return ship.getSchipType().getAantalToegelatenSchepen() > aantal;
}
private boolean overlaptNietMetAnderSchip(Ship ship) {
for (Ship s : this.getSchepen()) {
for (Integer i : ship.getSchipNummers()) {
if (s.getNummersRondomSchip().contains(i) || s.getSchipNummers().contains(i)) {
return false;
}
}
}
return true;
}
}
|
103280_9 | //Opg. 10
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Monitor2 {
private Lock laas = new ReentrantLock();
private SubsekvensRegister reg;
//Ha condition for når det er mer eller lik to, altså der jeg skal hente to hashmapper
//Hvis det er mindre enn to hashmapper så må den vente!!!!!!!
private Condition merEnnEn = laas.newCondition();
//Når det bare er en hashmap igjen i ordboka
private Condition bareEn = laas.newCondition();
public Monitor2(SubsekvensRegister reg) {
this.reg = reg;
}
//Skal ha de samme metodene some subsekvensregister
public void settInn (HashMap<String, Subsekvens> nyHashMap) {
laas.lock();
try {
reg.settInn(nyHashMap);
//Signaliserer til alle tråder som venter på "merEnnEn" condition
if (reg.storrelse() >= 1) {
merEnnEn.signalAll();
}
} finally { laas.unlock();
}
}
public HashMap<String, Subsekvens> taUt() throws InterruptedException {
laas.lock();
try {
while (reg.storrelse() == 1) {
bareEn.await();
}
return reg.taUt();
} finally { laas.unlock();
}
}
public int storrelse() {
laas.lock();
try {
return reg.storrelse();
} finally { laas.unlock();
}
}
//Her må de ikke være statiske
public HashMap<String, Subsekvens> lesFil (String fil) throws FileNotFoundException {
laas.lock();
try {
return SubsekvensRegister.lesFil(fil); //pga. den er statisk
} finally { laas.unlock();}
}
public HashMap<String, Subsekvens> slaaSammen(HashMap<String,Subsekvens> hash1, HashMap<String, Subsekvens> hash2) {
laas.lock();
try {
return SubsekvensRegister.slaaSammen(hash1, hash2);
} finally { laas.unlock();}
}
/*
Du må lage én metode som henter ut to HashMap-er som skal flettes. Det vil
si at metoden må vente inne i monitoren hvis den ikke inneholder to HashMap-er som kan hentes
ut. Til slutt vil det bare være én HashMap igjen i beholderen – den HashMap-en som er
resultatet av all flettingen. Å identifisere når det bare er én igjen og flettetrådene ikke har mer å
gjøre er en fin utfordring for dine logiske evner.
*/
//Skal hente to hashmapper, men den må vente når det er mindre enn to hashmapper -> Her må jeg ha conditions
public ArrayList<HashMap<String, Subsekvens>> hentToHashmapper() throws InterruptedException{
laas.lock();
//Hent to med hente metoden
try {
//Må ha 0, for jeg må sjekke om størrelsen er 0, for da må jeg vente på nye elementer i lista
while (reg.storrelse() == 0) {
merEnnEn.await();
}
ArrayList<HashMap<String, Subsekvens>> toHashMaps = new ArrayList<>();
if (reg.storrelse() > 1) { //Må sjekke at det er mer enn 1, hvis ikke får vi out of bounce
HashMap<String, Subsekvens> tempHash0;
HashMap<String, Subsekvens> tempHash1;
tempHash0 = reg.taUt();
tempHash1 = reg.taUt();
toHashMaps.add(tempHash0);
toHashMaps.add(tempHash1);
}
//Skjer hvis det bare er en
if (reg.storrelse() == 1) {
bareEn.signalAll();
}
return toHashMaps;
}
finally{ laas.unlock(); }
}
}
| Mariisno/Oppgaver-UIO | IN1010/Oblig 5/Oblig5Hele/Monitor2.java | 1,191 | //Hent to med hente metoden | line_comment | nl | //Opg. 10
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Monitor2 {
private Lock laas = new ReentrantLock();
private SubsekvensRegister reg;
//Ha condition for når det er mer eller lik to, altså der jeg skal hente to hashmapper
//Hvis det er mindre enn to hashmapper så må den vente!!!!!!!
private Condition merEnnEn = laas.newCondition();
//Når det bare er en hashmap igjen i ordboka
private Condition bareEn = laas.newCondition();
public Monitor2(SubsekvensRegister reg) {
this.reg = reg;
}
//Skal ha de samme metodene some subsekvensregister
public void settInn (HashMap<String, Subsekvens> nyHashMap) {
laas.lock();
try {
reg.settInn(nyHashMap);
//Signaliserer til alle tråder som venter på "merEnnEn" condition
if (reg.storrelse() >= 1) {
merEnnEn.signalAll();
}
} finally { laas.unlock();
}
}
public HashMap<String, Subsekvens> taUt() throws InterruptedException {
laas.lock();
try {
while (reg.storrelse() == 1) {
bareEn.await();
}
return reg.taUt();
} finally { laas.unlock();
}
}
public int storrelse() {
laas.lock();
try {
return reg.storrelse();
} finally { laas.unlock();
}
}
//Her må de ikke være statiske
public HashMap<String, Subsekvens> lesFil (String fil) throws FileNotFoundException {
laas.lock();
try {
return SubsekvensRegister.lesFil(fil); //pga. den er statisk
} finally { laas.unlock();}
}
public HashMap<String, Subsekvens> slaaSammen(HashMap<String,Subsekvens> hash1, HashMap<String, Subsekvens> hash2) {
laas.lock();
try {
return SubsekvensRegister.slaaSammen(hash1, hash2);
} finally { laas.unlock();}
}
/*
Du må lage én metode som henter ut to HashMap-er som skal flettes. Det vil
si at metoden må vente inne i monitoren hvis den ikke inneholder to HashMap-er som kan hentes
ut. Til slutt vil det bare være én HashMap igjen i beholderen – den HashMap-en som er
resultatet av all flettingen. Å identifisere når det bare er én igjen og flettetrådene ikke har mer å
gjøre er en fin utfordring for dine logiske evner.
*/
//Skal hente to hashmapper, men den må vente når det er mindre enn to hashmapper -> Her må jeg ha conditions
public ArrayList<HashMap<String, Subsekvens>> hentToHashmapper() throws InterruptedException{
laas.lock();
//Hent to<SUF>
try {
//Må ha 0, for jeg må sjekke om størrelsen er 0, for da må jeg vente på nye elementer i lista
while (reg.storrelse() == 0) {
merEnnEn.await();
}
ArrayList<HashMap<String, Subsekvens>> toHashMaps = new ArrayList<>();
if (reg.storrelse() > 1) { //Må sjekke at det er mer enn 1, hvis ikke får vi out of bounce
HashMap<String, Subsekvens> tempHash0;
HashMap<String, Subsekvens> tempHash1;
tempHash0 = reg.taUt();
tempHash1 = reg.taUt();
toHashMaps.add(tempHash0);
toHashMaps.add(tempHash1);
}
//Skjer hvis det bare er en
if (reg.storrelse() == 1) {
bareEn.signalAll();
}
return toHashMaps;
}
finally{ laas.unlock(); }
}
}
|
14080_21 | package Week2;
import java.util.Arrays;
class Colorspace {
static float[] RGBtoCMY(float r, float g, float b) {
//als je van rgb naar cmy wilt moet je eerst van 255 naar 0/1 berekenen omdat rgb meestal werkt van 0 tot 255 dus als we met een voorbeeld blauw op 200 zetten
// moeten we 1 - (200/255)
// vandaar de cormule y= 1-b ( het is niet delen door 255 aangezien in de vraag staat dat onze rgb waarden zoizo al van 0 tot 1 gaan)
//berekeningen
float c = (1 - r);
float m = (1 - g);
float y = (1 - b);
//returnt de waardes die net zijn berekend
return new float[] {c, m, y};
}
static float[] CMYtoRGB(float c, float m, float y) {
//als je van rgb naar cmy gaat deet je 1-r maar nu wil je van cmy naar rgb dus doe je r= 1 - c
//berekeningen
float r = (1 - c);
float g = (1 - m);
float b = (1 - y);
//returned de berekende waardes
return new float[] {r, g, b};
}
static float[] RGBtoHSL(float r, float g, float b) {
//voor meer informatie over de formule gebruikt https://www.niwa.nu/2013/05/math-behind-colorspace-conversions-rgb-hsl/
//pakt van de waardes gegeven het hoogste en laagste nummer bij math.max bijvoorbeeld waardes 8 9 4 dan word bij max nummer 9 gebruikt
float M = Math.max(r, Math.max(g, b));
float m = Math.min(r, Math.min(g, b));
//initialiseerd floats s en H
float s = 0;
float H = 0;
//berekend gemiddelde van de waardes
float l = ((M + m)/2);
//beijkt of het gemiddelde lager of gelijk is aan 0.5 als dat zo is voerd hij de formule uit
if(l <= 0.5 ) {
float S = (M - m ) / (M + m);
s=S;
}
//bekijkt of het gemiddelde groter is dan 0.5 en voerd dan de forume uit
if(l > 0.5 ) {
float S = (M - m ) / (2 - M + m);
s=S;
}
// If Red is max, then Hue = (G-B)/(max-min)
// If Green is max, then Hue = 2.0 + (B-R)/(max-min)
// If Blue is max, then Hue = 4.0 + (R-G)/(max-min)
//als rood het hoogste is dan word het g-b / max - min
//als groen het hoogste is dan word het 2 + b - r / max - min
//als blouw het hooste is word het 4 + r-g / max - min
if ( r == M) {
H = (g-b)/(M-m);
}
if ( g == M) {
H = 2 + (b - r)/(M - m);
}
if ( b == M) {
H = 4 + (r - g) / (M - m);
}
float h = H * 60;
return new float[] {h, s, l};
}
//forumle van b
static float B(float h, float cmin, float cmax){
//voor meer informatie berekend het documentje in de vraag
//als h kleiner dan 0 is telt hij er 360 bij op (zodat er geen fouten in het programma kan ontstaan)
while (h < 0){
h += 360.0f;
}
//berekend de modulo door h % 360 te doen he tis
float modulo = h % 360 ;
//controleerd hoe groot de modulo is als
if (modulo < 120) {
return cmin;
//returned cmin
}
else if (modulo >= 120 && modulo < 180 ) {
return cmin + (cmax - cmin) * (modulo - 120) / 60;
//returned getal berekend in formule
}
else if (modulo >= 180 && modulo < 300 ) {
return cmax;
//returned cmin
}
else {
return cmax -(cmax-cmin) * (modulo - 300) / 60 ;
//returned getal berekend in formule
}
}
static float[] HSLtoRGB(float h, float s, float l) {
//berekend cmin formule staat in bestandje in vraag
float cmin = l + s * Math.abs(l - 0.5f) + (-0.5f*s);
float cmax = l - s * Math.abs(l - 0.5f) + (0.5f*s);
//roept functie B aan en vult daar parameters in
float b = B(h, cmin, cmax);
float g = B(h + 120, cmin, cmax);
float r = B(h - 120, cmin, cmax);
return new float[] {r, g, b};
}
static float[] transparency(float r1, float g1, float b1, float alpha, float r2, float g2, float b2) {
// hier word de transparency berekend formule staat in de slides
float r = r1 * alpha + r2*(1-alpha);
float g = g1 * alpha + g2*(1-alpha);
float b = b1 * alpha + b2*(1-alpha);
//returned r g en b
return new float[] {r, g, b};
}
public static void main(String[] args) {
// testcode
// let op: de beoordeling wordt gedaan op basis van andere waarden
System.out.println(Arrays.toString(RGBtoCMY(0.4f, 0.5f, 0.6f))); // (0.6, 0.5, 0.4)
System.out.println(Arrays.toString(CMYtoRGB(0.4f, 0.5f, 0.6f))); // (0.6, 0.5, 0.4)
System.out.println(Arrays.toString(RGBtoHSL(0.4f, 0.5f, 0.6f))); // (210.0, 0.2, 0.5)
System.out.println(Arrays.toString(HSLtoRGB(100f, 0.5f, 0.6f))); // (0.533, 0.8, 0.4)
System.out.println(Arrays.toString(transparency(0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 1.0f))); // (0.52, 0.62, 0.72)
}
} | MarijnSopers/ComputerGraphics | Week2/Colorspace.java | 1,931 | //berekend de modulo door h % 360 te doen he tis | line_comment | nl | package Week2;
import java.util.Arrays;
class Colorspace {
static float[] RGBtoCMY(float r, float g, float b) {
//als je van rgb naar cmy wilt moet je eerst van 255 naar 0/1 berekenen omdat rgb meestal werkt van 0 tot 255 dus als we met een voorbeeld blauw op 200 zetten
// moeten we 1 - (200/255)
// vandaar de cormule y= 1-b ( het is niet delen door 255 aangezien in de vraag staat dat onze rgb waarden zoizo al van 0 tot 1 gaan)
//berekeningen
float c = (1 - r);
float m = (1 - g);
float y = (1 - b);
//returnt de waardes die net zijn berekend
return new float[] {c, m, y};
}
static float[] CMYtoRGB(float c, float m, float y) {
//als je van rgb naar cmy gaat deet je 1-r maar nu wil je van cmy naar rgb dus doe je r= 1 - c
//berekeningen
float r = (1 - c);
float g = (1 - m);
float b = (1 - y);
//returned de berekende waardes
return new float[] {r, g, b};
}
static float[] RGBtoHSL(float r, float g, float b) {
//voor meer informatie over de formule gebruikt https://www.niwa.nu/2013/05/math-behind-colorspace-conversions-rgb-hsl/
//pakt van de waardes gegeven het hoogste en laagste nummer bij math.max bijvoorbeeld waardes 8 9 4 dan word bij max nummer 9 gebruikt
float M = Math.max(r, Math.max(g, b));
float m = Math.min(r, Math.min(g, b));
//initialiseerd floats s en H
float s = 0;
float H = 0;
//berekend gemiddelde van de waardes
float l = ((M + m)/2);
//beijkt of het gemiddelde lager of gelijk is aan 0.5 als dat zo is voerd hij de formule uit
if(l <= 0.5 ) {
float S = (M - m ) / (M + m);
s=S;
}
//bekijkt of het gemiddelde groter is dan 0.5 en voerd dan de forume uit
if(l > 0.5 ) {
float S = (M - m ) / (2 - M + m);
s=S;
}
// If Red is max, then Hue = (G-B)/(max-min)
// If Green is max, then Hue = 2.0 + (B-R)/(max-min)
// If Blue is max, then Hue = 4.0 + (R-G)/(max-min)
//als rood het hoogste is dan word het g-b / max - min
//als groen het hoogste is dan word het 2 + b - r / max - min
//als blouw het hooste is word het 4 + r-g / max - min
if ( r == M) {
H = (g-b)/(M-m);
}
if ( g == M) {
H = 2 + (b - r)/(M - m);
}
if ( b == M) {
H = 4 + (r - g) / (M - m);
}
float h = H * 60;
return new float[] {h, s, l};
}
//forumle van b
static float B(float h, float cmin, float cmax){
//voor meer informatie berekend het documentje in de vraag
//als h kleiner dan 0 is telt hij er 360 bij op (zodat er geen fouten in het programma kan ontstaan)
while (h < 0){
h += 360.0f;
}
//berekend de<SUF>
float modulo = h % 360 ;
//controleerd hoe groot de modulo is als
if (modulo < 120) {
return cmin;
//returned cmin
}
else if (modulo >= 120 && modulo < 180 ) {
return cmin + (cmax - cmin) * (modulo - 120) / 60;
//returned getal berekend in formule
}
else if (modulo >= 180 && modulo < 300 ) {
return cmax;
//returned cmin
}
else {
return cmax -(cmax-cmin) * (modulo - 300) / 60 ;
//returned getal berekend in formule
}
}
static float[] HSLtoRGB(float h, float s, float l) {
//berekend cmin formule staat in bestandje in vraag
float cmin = l + s * Math.abs(l - 0.5f) + (-0.5f*s);
float cmax = l - s * Math.abs(l - 0.5f) + (0.5f*s);
//roept functie B aan en vult daar parameters in
float b = B(h, cmin, cmax);
float g = B(h + 120, cmin, cmax);
float r = B(h - 120, cmin, cmax);
return new float[] {r, g, b};
}
static float[] transparency(float r1, float g1, float b1, float alpha, float r2, float g2, float b2) {
// hier word de transparency berekend formule staat in de slides
float r = r1 * alpha + r2*(1-alpha);
float g = g1 * alpha + g2*(1-alpha);
float b = b1 * alpha + b2*(1-alpha);
//returned r g en b
return new float[] {r, g, b};
}
public static void main(String[] args) {
// testcode
// let op: de beoordeling wordt gedaan op basis van andere waarden
System.out.println(Arrays.toString(RGBtoCMY(0.4f, 0.5f, 0.6f))); // (0.6, 0.5, 0.4)
System.out.println(Arrays.toString(CMYtoRGB(0.4f, 0.5f, 0.6f))); // (0.6, 0.5, 0.4)
System.out.println(Arrays.toString(RGBtoHSL(0.4f, 0.5f, 0.6f))); // (210.0, 0.2, 0.5)
System.out.println(Arrays.toString(HSLtoRGB(100f, 0.5f, 0.6f))); // (0.533, 0.8, 0.4)
System.out.println(Arrays.toString(transparency(0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 1.0f))); // (0.52, 0.62, 0.72)
}
} |
109965_9 | package nl.novi.techiteasy.controllers;
import nl.novi.techiteasy.dtos.user.UserDto;
import nl.novi.techiteasy.dtos.user.UserResponseDto;
import nl.novi.techiteasy.exceptions.BadRequestException;
import nl.novi.techiteasy.dtos.authority.AuthorityDto;
import nl.novi.techiteasy.services.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
import java.util.List;
@CrossOrigin
@RestController
@RequestMapping(value = "/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping(value = "")
public ResponseEntity<List<UserDto>> getUsers() {
List<UserDto> userDtos = userService.getUsers();
return ResponseEntity.ok().body(userDtos);
}
@GetMapping(value = "/{username}")
public ResponseEntity<UserDto> getUser(@PathVariable("username") String username) {
UserDto optionalUser = userService.getUser(username);
return ResponseEntity.ok().body(optionalUser);
}
@PostMapping(value = "")
public ResponseEntity<UserDto> createKlant(@RequestBody UserDto dto) {;
String newUsername = userService.createUser(dto);
userService.addAuthority(newUsername, "ROLE_USER");
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{username}")
.buildAndExpand(newUsername).toUri();
return ResponseEntity.created(location).build();
}
@PutMapping(value = "/{username}")
public ResponseEntity<UserDto> updateKlant(@PathVariable("username") String username, @RequestBody UserDto dto) {
userService.updateUser(username, dto);
return ResponseEntity.noContent().build();
}
@DeleteMapping(value = "/{username}")
public ResponseEntity<Object> deleteKlant(@PathVariable("username") String username) {
userService.deleteUser(username);
return ResponseEntity.noContent().build();
}
@GetMapping(value = "/{username}/authorities")
public ResponseEntity<Object> getUserAuthorities(@PathVariable("username") String username) {
return ResponseEntity.ok().body(userService.getAuthorities(username));
}
// Vraag in to do: Als Requestbody wordt hier een Map<String, Object> gebruikt om de "authorityName" binnen te halen, dat werkt, maar kun je een betere oplossing bedenken?
// Antwoord: Ja, met een DTO. Ik heb deze class AuthorityDto genoemd en ondergebracht in het mapje dtos/authority,
@PostMapping(value = "/{username}/authorities")
public ResponseEntity<Object> addUserAuthority(
@PathVariable("username") String username,
@RequestBody AuthorityDto authorityDto) {
try {
String authorityName = authorityDto.authority;
userService.addAuthority(username, authorityName);
return ResponseEntity.noContent().build();
} catch (Exception ex) {
throw new BadRequestException();
}
}
// Oude versie:
// @PostMapping(value = "/{username}/authorities")
// public ResponseEntity<Object> addUserAuthority(@PathVariable("username") String username, @RequestBody Map<String, Object> fields) {
// try {
// String authorityName = (String) fields.get("authority");
// userService.addAuthority(username, authorityName);
// return ResponseEntity.noContent().build();
// }
// catch (Exception ex) {
// throw new BadRequestException();
// }
// }
@DeleteMapping(value = "/{username}/authorities/{authority}")
public ResponseEntity<Object> deleteUserAuthority(@PathVariable("username") String username, @PathVariable("authority") String authority) {
userService.removeAuthority(username, authority);
return ResponseEntity.noContent().build();
}
// Bonusopdracht
// Toepassen van SecurityContextHolder en Authentication classes (zie imports), en methode getUserById toegevoegd.
// Ik heb een aparte ResponseDto gemaakt, die een beperkt aantal velden teruggeeft aan de gebruiker.
// Ben er niet meer aan toegekomen om dit uit te testen in Postman voor de deadline, maar dit wil ik nog wel gaan doen. Ben wel benieuwd of ik op de goede weg zit.
@GetMapping("/{id}")
public ResponseEntity<Object> getUserById(@PathVariable("id") String id) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String username = authentication.getName();
if (username.equals(id)) {
UserDto userDto = userService.getUser(id);
UserResponseDto responseDto = new UserResponseDto(userDto.getUsername(), userDto.getEmail(), userDto.getAuthorities());
return ResponseEntity.ok(userDto);
} else {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Access denied");
}
}
}
| MarjetBosma/NOVI-backend-springboot-techiteasy | src/main/java/nl/novi/techiteasy/controllers/UserController.java | 1,422 | // Ben er niet meer aan toegekomen om dit uit te testen in Postman voor de deadline, maar dit wil ik nog wel gaan doen. Ben wel benieuwd of ik op de goede weg zit. | line_comment | nl | package nl.novi.techiteasy.controllers;
import nl.novi.techiteasy.dtos.user.UserDto;
import nl.novi.techiteasy.dtos.user.UserResponseDto;
import nl.novi.techiteasy.exceptions.BadRequestException;
import nl.novi.techiteasy.dtos.authority.AuthorityDto;
import nl.novi.techiteasy.services.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
import java.util.List;
@CrossOrigin
@RestController
@RequestMapping(value = "/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping(value = "")
public ResponseEntity<List<UserDto>> getUsers() {
List<UserDto> userDtos = userService.getUsers();
return ResponseEntity.ok().body(userDtos);
}
@GetMapping(value = "/{username}")
public ResponseEntity<UserDto> getUser(@PathVariable("username") String username) {
UserDto optionalUser = userService.getUser(username);
return ResponseEntity.ok().body(optionalUser);
}
@PostMapping(value = "")
public ResponseEntity<UserDto> createKlant(@RequestBody UserDto dto) {;
String newUsername = userService.createUser(dto);
userService.addAuthority(newUsername, "ROLE_USER");
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{username}")
.buildAndExpand(newUsername).toUri();
return ResponseEntity.created(location).build();
}
@PutMapping(value = "/{username}")
public ResponseEntity<UserDto> updateKlant(@PathVariable("username") String username, @RequestBody UserDto dto) {
userService.updateUser(username, dto);
return ResponseEntity.noContent().build();
}
@DeleteMapping(value = "/{username}")
public ResponseEntity<Object> deleteKlant(@PathVariable("username") String username) {
userService.deleteUser(username);
return ResponseEntity.noContent().build();
}
@GetMapping(value = "/{username}/authorities")
public ResponseEntity<Object> getUserAuthorities(@PathVariable("username") String username) {
return ResponseEntity.ok().body(userService.getAuthorities(username));
}
// Vraag in to do: Als Requestbody wordt hier een Map<String, Object> gebruikt om de "authorityName" binnen te halen, dat werkt, maar kun je een betere oplossing bedenken?
// Antwoord: Ja, met een DTO. Ik heb deze class AuthorityDto genoemd en ondergebracht in het mapje dtos/authority,
@PostMapping(value = "/{username}/authorities")
public ResponseEntity<Object> addUserAuthority(
@PathVariable("username") String username,
@RequestBody AuthorityDto authorityDto) {
try {
String authorityName = authorityDto.authority;
userService.addAuthority(username, authorityName);
return ResponseEntity.noContent().build();
} catch (Exception ex) {
throw new BadRequestException();
}
}
// Oude versie:
// @PostMapping(value = "/{username}/authorities")
// public ResponseEntity<Object> addUserAuthority(@PathVariable("username") String username, @RequestBody Map<String, Object> fields) {
// try {
// String authorityName = (String) fields.get("authority");
// userService.addAuthority(username, authorityName);
// return ResponseEntity.noContent().build();
// }
// catch (Exception ex) {
// throw new BadRequestException();
// }
// }
@DeleteMapping(value = "/{username}/authorities/{authority}")
public ResponseEntity<Object> deleteUserAuthority(@PathVariable("username") String username, @PathVariable("authority") String authority) {
userService.removeAuthority(username, authority);
return ResponseEntity.noContent().build();
}
// Bonusopdracht
// Toepassen van SecurityContextHolder en Authentication classes (zie imports), en methode getUserById toegevoegd.
// Ik heb een aparte ResponseDto gemaakt, die een beperkt aantal velden teruggeeft aan de gebruiker.
// Ben er<SUF>
@GetMapping("/{id}")
public ResponseEntity<Object> getUserById(@PathVariable("id") String id) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String username = authentication.getName();
if (username.equals(id)) {
UserDto userDto = userService.getUser(id);
UserResponseDto responseDto = new UserResponseDto(userDto.getUsername(), userDto.getEmail(), userDto.getAuthorities());
return ResponseEntity.ok(userDto);
} else {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Access denied");
}
}
}
|
144585_21 | //package nl.novi.catsittermanager.config;
//
//import nl.novi.catsittermanager.filter.JwtRequestFilter;
//import nl.novi.catsittermanager.services.CustomUserDetailsService;
//import nl.novi.catsittermanager.utils.JwtUtil;
//
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.http.HttpMethod;
//import org.springframework.security.authentication.AuthenticationManager;
//import org.springframework.security.authentication.ProviderManager;
//import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
//import org.springframework.security.config.Customizer;
//import org.springframework.security.config.annotation.web.builders.HttpSecurity;
//import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
//import org.springframework.security.config.http.SessionCreationPolicy;
//import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
//import org.springframework.security.crypto.password.PasswordEncoder;
//import org.springframework.security.web.SecurityFilterChain;
//import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
//
//@Configuration
//@EnableWebSecurity
//public class SpringSecurityConfig {
//
// private final CustomUserDetailsService customUserDetailsService;
//
// private final JwtRequestFilter jwtRequestFilter;
//
// public SpringSecurityConfig(CustomUserDetailsService userDetailsService, JwtRequestFilter jwtRequestFilter) {
// this.customUserDetailsService = userDetailsService;
// this.jwtRequestFilter = jwtRequestFilter;
// }
//
//
// // PasswordEncoderBean. Deze kun je overal in je applicatie injecteren waar nodig.
// // Je kunt dit ook in een aparte configuratie klasse zetten.
// @Bean
// public PasswordEncoder passwordEncoder() {
// return new BCryptPasswordEncoder();
// }
//
//
// // Authenticatie met customUserDetailsService en passwordEncoder
// @Bean
// public AuthenticationManager authenticationManager(HttpSecurity http, PasswordEncoder passwordEncoder) throws Exception {
// var auth = new DaoAuthenticationProvider();
// auth.setPasswordEncoder(passwordEncoder);
// auth.setUserDetailsService(customUserDetailsService);
// return new ProviderManager(auth);
// }
//
// // Authorizatie met jwt
// @Bean
// protected SecurityFilterChain filter (HttpSecurity http) throws Exception {
//
// //JWT token authentication
// http
// .csrf(csrf -> csrf.disable())
// .httpBasic(basic -> basic.disable())
// .cors(Customizer.withDefaults())
// .authorizeHttpRequests(auth ->
// auth
// // Wanneer je deze uncomments, staat je hele security open. Je hebt dan alleen nog een jwt nodig.
//// .requestMatchers("/**").permitAll()
// .requestMatchers(HttpMethod.POST, "/users").hasRole("ADMIN")
// .requestMatchers(HttpMethod.GET,"/users").hasRole("ADMIN")
// .requestMatchers(HttpMethod.POST,"/users/**").hasRole("ADMIN")
// .requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN")
// .requestMatchers("/authenticated").authenticated()
// .requestMatchers("/authenticate").permitAll()/*alleen dit punt mag toegankelijk zijn voor niet ingelogde gebruikers*/
// .requestMatchers("/authenticated").authenticated()
// .requestMatchers("/authenticate").permitAll()
// .anyRequest().denyAll() /*Deze voeg je altijd als laatste toe, om een default beveiliging te hebben voor eventuele vergeten endpoints of endpoints die je later toevoegd. */
// )
// .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
// http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
// return http.build();
// }
//
//}
| MarjetBosma/catsitter-manager | src/main/java/nl/novi/catsittermanager/config/SpringSecurityConfig.java | 1,105 | // .anyRequest().denyAll() /*Deze voeg je altijd als laatste toe, om een default beveiliging te hebben voor eventuele vergeten endpoints of endpoints die je later toevoegd. */ | line_comment | nl | //package nl.novi.catsittermanager.config;
//
//import nl.novi.catsittermanager.filter.JwtRequestFilter;
//import nl.novi.catsittermanager.services.CustomUserDetailsService;
//import nl.novi.catsittermanager.utils.JwtUtil;
//
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.http.HttpMethod;
//import org.springframework.security.authentication.AuthenticationManager;
//import org.springframework.security.authentication.ProviderManager;
//import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
//import org.springframework.security.config.Customizer;
//import org.springframework.security.config.annotation.web.builders.HttpSecurity;
//import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
//import org.springframework.security.config.http.SessionCreationPolicy;
//import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
//import org.springframework.security.crypto.password.PasswordEncoder;
//import org.springframework.security.web.SecurityFilterChain;
//import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
//
//@Configuration
//@EnableWebSecurity
//public class SpringSecurityConfig {
//
// private final CustomUserDetailsService customUserDetailsService;
//
// private final JwtRequestFilter jwtRequestFilter;
//
// public SpringSecurityConfig(CustomUserDetailsService userDetailsService, JwtRequestFilter jwtRequestFilter) {
// this.customUserDetailsService = userDetailsService;
// this.jwtRequestFilter = jwtRequestFilter;
// }
//
//
// // PasswordEncoderBean. Deze kun je overal in je applicatie injecteren waar nodig.
// // Je kunt dit ook in een aparte configuratie klasse zetten.
// @Bean
// public PasswordEncoder passwordEncoder() {
// return new BCryptPasswordEncoder();
// }
//
//
// // Authenticatie met customUserDetailsService en passwordEncoder
// @Bean
// public AuthenticationManager authenticationManager(HttpSecurity http, PasswordEncoder passwordEncoder) throws Exception {
// var auth = new DaoAuthenticationProvider();
// auth.setPasswordEncoder(passwordEncoder);
// auth.setUserDetailsService(customUserDetailsService);
// return new ProviderManager(auth);
// }
//
// // Authorizatie met jwt
// @Bean
// protected SecurityFilterChain filter (HttpSecurity http) throws Exception {
//
// //JWT token authentication
// http
// .csrf(csrf -> csrf.disable())
// .httpBasic(basic -> basic.disable())
// .cors(Customizer.withDefaults())
// .authorizeHttpRequests(auth ->
// auth
// // Wanneer je deze uncomments, staat je hele security open. Je hebt dan alleen nog een jwt nodig.
//// .requestMatchers("/**").permitAll()
// .requestMatchers(HttpMethod.POST, "/users").hasRole("ADMIN")
// .requestMatchers(HttpMethod.GET,"/users").hasRole("ADMIN")
// .requestMatchers(HttpMethod.POST,"/users/**").hasRole("ADMIN")
// .requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN")
// .requestMatchers("/authenticated").authenticated()
// .requestMatchers("/authenticate").permitAll()/*alleen dit punt mag toegankelijk zijn voor niet ingelogde gebruikers*/
// .requestMatchers("/authenticated").authenticated()
// .requestMatchers("/authenticate").permitAll()
// .anyRequest().denyAll() /*Deze<SUF>
// )
// .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
// http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
// return http.build();
// }
//
//}
|
8369_0 | package be.jpendel.application;
import be.jpendel.domain.person.Person;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/* TODO : mark: PersonMapper en PersonDTO moeten volgens mij in de domain layer
*/
class PersonMapper {
private PersonMapper() {
}
static List<PersonDTO> map(Collection<Person> persons) {
return persons.stream().map(PersonMapper::map).collect(Collectors.toList());
}
static PersonDTO map(Person person) {
return PersonDTO.newBuilder()
.withUuid(person.getId())
.withFirstName(person.getFirstName())
.withLastName(person.getLastName())
.withBirthDate(person.getBirthDate())
.withPhone(person.getPhone())
.build();
}
}
| MarkDechamps/jpendel | application/src/main/java/be/jpendel/application/PersonMapper.java | 233 | /* TODO : mark: PersonMapper en PersonDTO moeten volgens mij in de domain layer
*/ | block_comment | nl | package be.jpendel.application;
import be.jpendel.domain.person.Person;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/* TODO : mark:<SUF>*/
class PersonMapper {
private PersonMapper() {
}
static List<PersonDTO> map(Collection<Person> persons) {
return persons.stream().map(PersonMapper::map).collect(Collectors.toList());
}
static PersonDTO map(Person person) {
return PersonDTO.newBuilder()
.withUuid(person.getId())
.withFirstName(person.getFirstName())
.withLastName(person.getLastName())
.withBirthDate(person.getBirthDate())
.withPhone(person.getPhone())
.build();
}
}
|
18648_3 | /*******************************************************************************
* Copyright (c) 2000, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* QNX Software System
* Anton Leherbauer (Wind River Systems)
* Sergey Prigogin (Google)
* James Blackburn (Broadcom Corp.)
*******************************************************************************/
package org.eclipse.cdt.internal.ui.build;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.cdt.core.resources.ACBuilder;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.ICHelpContextIds;
import org.eclipse.cdt.internal.ui.preferences.PreferencesMessages;
/**
* The page for top-level build preferences
*/
public class BuildPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private static final int GROUP_VINDENT = 5;
private static final int GROUP_HINDENT = 20;
private Button buildActive, buildAll, buildOnlyOnRefChange;
public BuildPreferencePage() {
super();
setPreferenceStore(CUIPlugin.getDefault().getPreferenceStore());
setDescription(PreferencesMessages.CBuildPreferencePage_description);
}
@Override
public void createControl(Composite parent) {
super.createControl(parent);
PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), ICHelpContextIds.C_PREF_PAGE);
}
@Override
protected Control createContents(Composite parent) {
initializeDialogUnits(parent);
Composite container= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth= 0;
layout.verticalSpacing= convertVerticalDLUsToPixels(10);
layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
container.setLayout(layout);
// Build either default configuration or all.
Group gr = addGroup(container, PreferencesMessages.CPluginPreferencePage_build_scope);
Label l1 = new Label(gr, SWT.NONE);
l1.setText(PreferencesMessages.CPluginPreferencePage_1);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.verticalIndent = GROUP_VINDENT;
l1.setLayoutData(gd);
boolean needAllConfigBuild = ACBuilder.needAllConfigBuild();
buildActive = new Button(gr, SWT.RADIO);
buildActive.setText(PreferencesMessages.CPluginPreferencePage_2);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.verticalIndent = GROUP_VINDENT;
gd.horizontalIndent = GROUP_HINDENT;
buildActive.setLayoutData(gd);
buildActive.setSelection(!needAllConfigBuild);
buildAll = new Button(gr, SWT.RADIO);
buildAll.setText(PreferencesMessages.CPluginPreferencePage_3);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalIndent = GROUP_HINDENT;
buildAll.setLayoutData(gd);
buildAll.setSelection(needAllConfigBuild);
addNote(gr, PreferencesMessages.CPluginPreferencePage_4);
// Building project dependencies.
Group gr2 = addGroup(container, PreferencesMessages.CPluginPreferencePage_building_configurations);
buildOnlyOnRefChange = new Button(gr2, SWT.CHECK);
buildOnlyOnRefChange.setText(PreferencesMessages.CPluginPreferencePage_7);
GridData gd2 = new GridData(GridData.FILL_HORIZONTAL);
gd2.verticalIndent = GROUP_VINDENT;
buildOnlyOnRefChange.setLayoutData(gd2);
buildOnlyOnRefChange.setSelection(ACBuilder.buildConfigResourceChanges());
Dialog.applyDialogFont(container);
return container;
}
private void addNote(Group parent, String noteMessage) {
Composite noteControl= createNoteComposite(JFaceResources.getDialogFont(), parent,
PreferencesMessages.CPluginPreferencePage_note, noteMessage);
GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.verticalIndent = GROUP_VINDENT;
noteControl.setLayoutData(gd);
}
@Override
protected Composite createNoteComposite(Font font, Composite composite, String title, String message) {
Composite messageComposite = super.createNoteComposite(font, composite, title, message);
Control[] children = messageComposite.getChildren();
if (children.length == 2 && (children[1] instanceof Label)) {
// this is temporary fix for problem that 3 line note does not displayed properly within the group
Label messageLabel = (Label) children[1];
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.widthHint=500;
messageLabel.setLayoutData(gd);
}
return messageComposite;
}
private Group addGroup(Composite parent, String label) {
return addGroup(parent, label, 1);
}
private Group addGroup(Composite parent, String label, int numColumns) {
Group group = new Group(parent, SWT.NONE);
group.setText(label);
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
group.setLayout(new GridLayout(numColumns, false));
return group;
}
/**
* @see IWorkbenchPreferencePage#init
*/
@Override
public void init(IWorkbench workbench) {
}
/* (non-Javadoc)
* @see org.eclipse.jface.preference.IPreferencePage#performOk()
*/
@Override
public boolean performOk() {
if (!super.performOk())
return false;
// tell the Core Plugin about this preference
ACBuilder.setAllConfigBuild(buildAll.getSelection());
ACBuilder.setBuildConfigResourceChanges(buildOnlyOnRefChange.getSelection());
return true;
}
@Override
protected void performDefaults() {
ACBuilder.setAllConfigBuild(false);
ACBuilder.setBuildConfigResourceChanges(false);
buildActive.setSelection(true);
buildAll.setSelection(false);
buildOnlyOnRefChange.setSelection(false);
super.performDefaults();
}
}
| MarkZ3/Eclipse-CDT-WIP | core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/build/BuildPreferencePage.java | 2,033 | // Building project dependencies. | line_comment | nl | /*******************************************************************************
* Copyright (c) 2000, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* QNX Software System
* Anton Leherbauer (Wind River Systems)
* Sergey Prigogin (Google)
* James Blackburn (Broadcom Corp.)
*******************************************************************************/
package org.eclipse.cdt.internal.ui.build;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.cdt.core.resources.ACBuilder;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.internal.ui.ICHelpContextIds;
import org.eclipse.cdt.internal.ui.preferences.PreferencesMessages;
/**
* The page for top-level build preferences
*/
public class BuildPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private static final int GROUP_VINDENT = 5;
private static final int GROUP_HINDENT = 20;
private Button buildActive, buildAll, buildOnlyOnRefChange;
public BuildPreferencePage() {
super();
setPreferenceStore(CUIPlugin.getDefault().getPreferenceStore());
setDescription(PreferencesMessages.CBuildPreferencePage_description);
}
@Override
public void createControl(Composite parent) {
super.createControl(parent);
PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), ICHelpContextIds.C_PREF_PAGE);
}
@Override
protected Control createContents(Composite parent) {
initializeDialogUnits(parent);
Composite container= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth= 0;
layout.verticalSpacing= convertVerticalDLUsToPixels(10);
layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
container.setLayout(layout);
// Build either default configuration or all.
Group gr = addGroup(container, PreferencesMessages.CPluginPreferencePage_build_scope);
Label l1 = new Label(gr, SWT.NONE);
l1.setText(PreferencesMessages.CPluginPreferencePage_1);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.verticalIndent = GROUP_VINDENT;
l1.setLayoutData(gd);
boolean needAllConfigBuild = ACBuilder.needAllConfigBuild();
buildActive = new Button(gr, SWT.RADIO);
buildActive.setText(PreferencesMessages.CPluginPreferencePage_2);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.verticalIndent = GROUP_VINDENT;
gd.horizontalIndent = GROUP_HINDENT;
buildActive.setLayoutData(gd);
buildActive.setSelection(!needAllConfigBuild);
buildAll = new Button(gr, SWT.RADIO);
buildAll.setText(PreferencesMessages.CPluginPreferencePage_3);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalIndent = GROUP_HINDENT;
buildAll.setLayoutData(gd);
buildAll.setSelection(needAllConfigBuild);
addNote(gr, PreferencesMessages.CPluginPreferencePage_4);
// Building project<SUF>
Group gr2 = addGroup(container, PreferencesMessages.CPluginPreferencePage_building_configurations);
buildOnlyOnRefChange = new Button(gr2, SWT.CHECK);
buildOnlyOnRefChange.setText(PreferencesMessages.CPluginPreferencePage_7);
GridData gd2 = new GridData(GridData.FILL_HORIZONTAL);
gd2.verticalIndent = GROUP_VINDENT;
buildOnlyOnRefChange.setLayoutData(gd2);
buildOnlyOnRefChange.setSelection(ACBuilder.buildConfigResourceChanges());
Dialog.applyDialogFont(container);
return container;
}
private void addNote(Group parent, String noteMessage) {
Composite noteControl= createNoteComposite(JFaceResources.getDialogFont(), parent,
PreferencesMessages.CPluginPreferencePage_note, noteMessage);
GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.verticalIndent = GROUP_VINDENT;
noteControl.setLayoutData(gd);
}
@Override
protected Composite createNoteComposite(Font font, Composite composite, String title, String message) {
Composite messageComposite = super.createNoteComposite(font, composite, title, message);
Control[] children = messageComposite.getChildren();
if (children.length == 2 && (children[1] instanceof Label)) {
// this is temporary fix for problem that 3 line note does not displayed properly within the group
Label messageLabel = (Label) children[1];
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.widthHint=500;
messageLabel.setLayoutData(gd);
}
return messageComposite;
}
private Group addGroup(Composite parent, String label) {
return addGroup(parent, label, 1);
}
private Group addGroup(Composite parent, String label, int numColumns) {
Group group = new Group(parent, SWT.NONE);
group.setText(label);
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
group.setLayout(new GridLayout(numColumns, false));
return group;
}
/**
* @see IWorkbenchPreferencePage#init
*/
@Override
public void init(IWorkbench workbench) {
}
/* (non-Javadoc)
* @see org.eclipse.jface.preference.IPreferencePage#performOk()
*/
@Override
public boolean performOk() {
if (!super.performOk())
return false;
// tell the Core Plugin about this preference
ACBuilder.setAllConfigBuild(buildAll.getSelection());
ACBuilder.setBuildConfigResourceChanges(buildOnlyOnRefChange.getSelection());
return true;
}
@Override
protected void performDefaults() {
ACBuilder.setAllConfigBuild(false);
ACBuilder.setBuildConfigResourceChanges(false);
buildActive.setSelection(true);
buildAll.setSelection(false);
buildOnlyOnRefChange.setSelection(false);
super.performDefaults();
}
}
|
7315_0 | package nl.stagesync.stagesync.repository;
import nl.stagesync.stagesync.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
/**
* De JpaRepositories die jullie al kennen. Hier wordt gebruik gemaakt van Query Creation. Op basis van de methode naam
* weten Spring en JPA welke query op de database uitgevoerd moet worden.
* Hier kan meer informatie over gevonden worden:
* https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation
*/
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
Boolean existsByUsername(String username);
Boolean existsByEmail(String email);
}
| MartijnD92/stage-sync-backend | src/main/java/nl/stagesync/stagesync/repository/UserRepository.java | 218 | /**
* De JpaRepositories die jullie al kennen. Hier wordt gebruik gemaakt van Query Creation. Op basis van de methode naam
* weten Spring en JPA welke query op de database uitgevoerd moet worden.
* Hier kan meer informatie over gevonden worden:
* https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation
*/ | block_comment | nl | package nl.stagesync.stagesync.repository;
import nl.stagesync.stagesync.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
/**
* De JpaRepositories die<SUF>*/
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
Boolean existsByUsername(String username);
Boolean existsByEmail(String email);
}
|
202196_3 | package week6.voteMachine.gui;
import java.awt.Container;
import java.awt.FlowLayout;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import week6.voteMachine.VoteList;
/**
* 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");
}
}
}
| MartijnSlot/Eclipse-workspace-Nedap-University | ss/week6/voteMachine/gui/ResultJFrame.java | 453 | /** Zet de uitslag op het tekstveld, met 1 regel per partij. */ | block_comment | nl | package week6.voteMachine.gui;
import java.awt.Container;
import java.awt.FlowLayout;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import week6.voteMachine.VoteList;
/**
* 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<SUF>*/
public void update(Map<String,Integer> votes) {
resultField.setText("");
for(Map.Entry<String,Integer> entry: votes.entrySet()){
resultField.append(entry.getKey() + ": " + entry.getValue() + "\n");
}
}
}
|
46809_4 | package User;
import MixingProxy.MixingProxy;
import Registrar.Registrar;
import javafx.scene.paint.Color;
import javax.xml.bind.DatatypeConverter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.rmi.RemoteException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;
import java.util.Scanner;
public class UserImpl extends UnicastRemoteObject implements User {
private Registrar registrar;
private MixingProxy mixingProxy;
private Color colorAfterQrScan;
private String phone;
private String name;
private String QRCode;
private String metInfectedPerson;
private ArrayList<byte[]> userTokens;
private ArrayList<String> userLogs = new ArrayList<>();
private byte[] currentToken;
public UserImpl(String name, String phone, Registrar registrar, MixingProxy mixingProxy) throws RemoteException {
this.name = name;
this.phone = phone;
this.registrar = registrar;
this.userTokens = new ArrayList<>();
this.mixingProxy = mixingProxy;
}
// Interface methods
@Override
public String getPhone() throws RemoteException {
return phone;
}
@Override
public String getName() throws RemoteException {
return name;
}
@Override
public void newDay(List<byte[]> newUserTokens, List<String[]> criticalTokens, LocalDate date) throws RemoteException {
// New daily tokens
this.userTokens.clear();
this.userTokens.addAll(newUserTokens);
// Check if critical tokens are in logs
ArrayList<String> logs = readLogs();
ArrayList<String> informedUserTokens = new ArrayList<>();
if(!criticalTokens.isEmpty()){
boolean informed = false;
for(String[] sCt: criticalTokens ){
String criticalUserToken = sCt[0];
LocalDateTime timeFrom = LocalDateTime.parse(sCt[1]);
LocalDateTime timeUntil = LocalDateTime.parse(sCt[2]);
for(int i=0; i<logs.size(); i++) {
String logFromString = logs.get(i).split("\\^")[0];
LocalDateTime logFrom = LocalDateTime.parse(logFromString);
String QR = logs.get(i).split("\\^")[1];
String userToken = logs.get(i).split("\\^")[2];
i++;
String logUntilString = logs.get(i).split("\\^")[0];
LocalDateTime logUntil = LocalDateTime.parse(logUntilString);
if (criticalUserToken.equals(userToken) &&
!logUntil.isBefore(timeFrom) &&
!logFrom.isAfter(timeUntil)) {
System.out.println("Je bent in contact gekomen met een positief getest persoon");
informedUserTokens.add(userToken);
informed = true;
break;
}
}
if(informed){
break;
}
}
mixingProxy.informedTokens(informedUserTokens);
}
}
@Override
public String scanQR(String qr) throws RemoteException, NoSuchAlgorithmException, SignatureException, InvalidKeyException {
// User Token
this.currentToken = userTokens.get(0);
//tijd
LocalDate ld = registrar.getDate();
LocalDateTime ldt = registrar.getDate().atTime(LocalTime.now());
//qr code loggen
this.QRCode = qr;
userLogs.add(ldt + "^" + qr + "^" + currentToken);
System.out.println("Following log is added to user logs: " + ldt + "|" + qr + "|" + currentToken);
writeToLogFile(ldt, qr, currentToken);
//h value van qr code splitten om door te sturen in capsule
String h = qr.substring(qr.lastIndexOf("|") + 1);
boolean validityToken = mixingProxy.retrieveCapsule(phone, ld, h, currentToken);
// Gebruikte token verwijderen
userTokens.remove(0);
//symbool toekennen indien jusite qr code scan
//op basis van business nummer een kleur toekennen
String businessNumber = qr.substring(qr.indexOf('|') + 1, qr.lastIndexOf('|'));
generateColor(businessNumber);
if(validityToken){
return "ok | " + ldt;
}
else return "not ok" + ldt;
}
@Override
public String leaveCatering(UserImpl user, String qr) throws RemoteException {
LocalDate ld = registrar.getDate();
LocalDateTime ldt = registrar.getDate().atTime(LocalTime.now());
userLogs.add(ldt + "^" + qr);
writeToLogFile(ldt, qr, currentToken);
String h = qr.substring(qr.lastIndexOf("|") + 1);
mixingProxy.retrieveExitCapsule(ld, h, currentToken);
return "Successfully left catering";
}
public void writeToLogFile(LocalDateTime ldt, String qr, byte[] currentToken){
String phoneForLog = phone.replace(" ", "_");
try {
File logFile = new File("logs/log_" + phoneForLog + ".txt");
if (!logFile.exists()){
logFile.createNewFile();
}
FileWriter logFW = new FileWriter("logs/log_" + phoneForLog + ".txt", true);
logFW.write(ldt + "^" + qr + "^" + DatatypeConverter.printHexBinary(currentToken));
logFW.write("\n");
logFW.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
public void generateColor(String b){
switch (b) {
case "1":
this.colorAfterQrScan = Color.BLUE;
break;
case "2":
this.colorAfterQrScan = Color.GREEN;
break;
case "3":
this.colorAfterQrScan = Color.RED;
break;
case "4":
this.colorAfterQrScan = Color.ORANGE;
break;
default: this.colorAfterQrScan = Color.BLACK;
}
}
public Color getColorAfterQrScan() {
return colorAfterQrScan;
}
public ArrayList<String> readLogs(){
String phoneForLog = phone.replace(" ", "_");
ArrayList<String> logs = new ArrayList<>();
try {
File userLog = new File("logs/log_" + phoneForLog + ".txt");
if (!userLog.exists()){
userLog.createNewFile();
}
Scanner userLogReader = new Scanner(userLog);
while (userLogReader.hasNextLine()) {
logs.add(userLogReader.nextLine());
}
userLogReader.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
return logs;
}
//Setters en getters
public ArrayList<byte[]> getUserTokens() {
return userTokens;
}
}
| MartijnVanderschelden/ProjectDistributedSystems2 | src/User/UserImpl.java | 2,053 | // Gebruikte token verwijderen | line_comment | nl | package User;
import MixingProxy.MixingProxy;
import Registrar.Registrar;
import javafx.scene.paint.Color;
import javax.xml.bind.DatatypeConverter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.rmi.RemoteException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;
import java.util.Scanner;
public class UserImpl extends UnicastRemoteObject implements User {
private Registrar registrar;
private MixingProxy mixingProxy;
private Color colorAfterQrScan;
private String phone;
private String name;
private String QRCode;
private String metInfectedPerson;
private ArrayList<byte[]> userTokens;
private ArrayList<String> userLogs = new ArrayList<>();
private byte[] currentToken;
public UserImpl(String name, String phone, Registrar registrar, MixingProxy mixingProxy) throws RemoteException {
this.name = name;
this.phone = phone;
this.registrar = registrar;
this.userTokens = new ArrayList<>();
this.mixingProxy = mixingProxy;
}
// Interface methods
@Override
public String getPhone() throws RemoteException {
return phone;
}
@Override
public String getName() throws RemoteException {
return name;
}
@Override
public void newDay(List<byte[]> newUserTokens, List<String[]> criticalTokens, LocalDate date) throws RemoteException {
// New daily tokens
this.userTokens.clear();
this.userTokens.addAll(newUserTokens);
// Check if critical tokens are in logs
ArrayList<String> logs = readLogs();
ArrayList<String> informedUserTokens = new ArrayList<>();
if(!criticalTokens.isEmpty()){
boolean informed = false;
for(String[] sCt: criticalTokens ){
String criticalUserToken = sCt[0];
LocalDateTime timeFrom = LocalDateTime.parse(sCt[1]);
LocalDateTime timeUntil = LocalDateTime.parse(sCt[2]);
for(int i=0; i<logs.size(); i++) {
String logFromString = logs.get(i).split("\\^")[0];
LocalDateTime logFrom = LocalDateTime.parse(logFromString);
String QR = logs.get(i).split("\\^")[1];
String userToken = logs.get(i).split("\\^")[2];
i++;
String logUntilString = logs.get(i).split("\\^")[0];
LocalDateTime logUntil = LocalDateTime.parse(logUntilString);
if (criticalUserToken.equals(userToken) &&
!logUntil.isBefore(timeFrom) &&
!logFrom.isAfter(timeUntil)) {
System.out.println("Je bent in contact gekomen met een positief getest persoon");
informedUserTokens.add(userToken);
informed = true;
break;
}
}
if(informed){
break;
}
}
mixingProxy.informedTokens(informedUserTokens);
}
}
@Override
public String scanQR(String qr) throws RemoteException, NoSuchAlgorithmException, SignatureException, InvalidKeyException {
// User Token
this.currentToken = userTokens.get(0);
//tijd
LocalDate ld = registrar.getDate();
LocalDateTime ldt = registrar.getDate().atTime(LocalTime.now());
//qr code loggen
this.QRCode = qr;
userLogs.add(ldt + "^" + qr + "^" + currentToken);
System.out.println("Following log is added to user logs: " + ldt + "|" + qr + "|" + currentToken);
writeToLogFile(ldt, qr, currentToken);
//h value van qr code splitten om door te sturen in capsule
String h = qr.substring(qr.lastIndexOf("|") + 1);
boolean validityToken = mixingProxy.retrieveCapsule(phone, ld, h, currentToken);
// Gebruikte token<SUF>
userTokens.remove(0);
//symbool toekennen indien jusite qr code scan
//op basis van business nummer een kleur toekennen
String businessNumber = qr.substring(qr.indexOf('|') + 1, qr.lastIndexOf('|'));
generateColor(businessNumber);
if(validityToken){
return "ok | " + ldt;
}
else return "not ok" + ldt;
}
@Override
public String leaveCatering(UserImpl user, String qr) throws RemoteException {
LocalDate ld = registrar.getDate();
LocalDateTime ldt = registrar.getDate().atTime(LocalTime.now());
userLogs.add(ldt + "^" + qr);
writeToLogFile(ldt, qr, currentToken);
String h = qr.substring(qr.lastIndexOf("|") + 1);
mixingProxy.retrieveExitCapsule(ld, h, currentToken);
return "Successfully left catering";
}
public void writeToLogFile(LocalDateTime ldt, String qr, byte[] currentToken){
String phoneForLog = phone.replace(" ", "_");
try {
File logFile = new File("logs/log_" + phoneForLog + ".txt");
if (!logFile.exists()){
logFile.createNewFile();
}
FileWriter logFW = new FileWriter("logs/log_" + phoneForLog + ".txt", true);
logFW.write(ldt + "^" + qr + "^" + DatatypeConverter.printHexBinary(currentToken));
logFW.write("\n");
logFW.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
public void generateColor(String b){
switch (b) {
case "1":
this.colorAfterQrScan = Color.BLUE;
break;
case "2":
this.colorAfterQrScan = Color.GREEN;
break;
case "3":
this.colorAfterQrScan = Color.RED;
break;
case "4":
this.colorAfterQrScan = Color.ORANGE;
break;
default: this.colorAfterQrScan = Color.BLACK;
}
}
public Color getColorAfterQrScan() {
return colorAfterQrScan;
}
public ArrayList<String> readLogs(){
String phoneForLog = phone.replace(" ", "_");
ArrayList<String> logs = new ArrayList<>();
try {
File userLog = new File("logs/log_" + phoneForLog + ".txt");
if (!userLog.exists()){
userLog.createNewFile();
}
Scanner userLogReader = new Scanner(userLog);
while (userLogReader.hasNextLine()) {
logs.add(userLogReader.nextLine());
}
userLogReader.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
return logs;
}
//Setters en getters
public ArrayList<byte[]> getUserTokens() {
return userTokens;
}
}
|
145235_18 | package tesc1;
import java.io.*;
import java.lang.String;
import java.util.Vector;
import absyn.*;
import util.*;
/**
* Label-Parser fuer den Editor.
* <p>
* @author Michael Suelzer, Christoph Schuette.
* @version $Id: TESCLabelParser.java,v 1.5 1999-02-07 11:58:30 swtech20 Exp $
*/
class TESCLabelParser extends TESCParser {
protected Statechart statechart;
// Der Standard-Ktor muss verborgen werden, da
// das Parsen eines Labels ohne Statechart
// keinen Sinn macht.
private TESCLabelParser() {};
/**
* Constructor.
*/
public TESCLabelParser (Statechart sc) {
statechart = sc;
eventlist = sc.events;
bvarlist = sc.bvars;
pathlist = sc.cnames;
}
/**
* Startet den Parsevorgang fuer ein Label.
*/
public TLabel readLabel (BufferedReader br) throws IOException {
warningText = new Vector ();
warningCount = 0 ;
errorText = new Vector ();
errorCount = 0;
lexer = new TESCTokenizer (br);
token = lexer.getNextToken ();
debug ("parseLabel");
TLabel label = parseLabel ();
// Die geaenderten Listen nach aussen geben
statechart.bvars = bvarlist;
statechart.events = eventlist;
statechart.cnames = pathlist;
return label;
}
/**
* LABEL ::= {GUARD} {"/" ACTION}
*/
public TLabel parseLabel () throws IOException {
//debug ("Enter parseLabel");
Guard guard = parseGuardSTMStyle ();
Action action = null;
if (token.getId () == Token.TOK_SLASH) {
matchToken (Token.Slash);
action = parseActions ();
}
else
action = new ActionEmpty (new Dummy ());
// Caption fuer TLabel aufbauen.
TLabel label = new TLabel (guard, action);
TESCSaver saver = new TESCSaver (null);
saver.setCaption (label);
// Sollte wider Erwarten ein Fehler auftreten, dann merken
errorCount += saver.getErrorCount ();
for (int i=0; i < saver.getErrorCount (); i++)
Error (saver.getErrorText (i));
//debug ("Leave parseLabel");
return label;
}
}
//----------------------------------------------------------------------
// Label-Parser
// ------------
//
// $Log: not supported by cvs2svn $
// Revision 1.4 1999/02/01 11:52:58 swtech20
// - globaler Debug-Schalter
//
// Revision 1.3 1999/01/20 17:32:10 swtech20
// - Status und Doku aktualisiert
// - Fehler, dass Anderungen an Bvarlisten ... nicht nach aussen-
// gegeben werden behoben.
//
// Revision 1.2 1999/01/18 17:08:52 swtech20
// - okDialog -> userMessage
// - Pruefung auf gui==null
// - package visibility fuer Nicht-Schnittstellenklassen
//
// Revision 1.1 1999/01/17 17:16:41 swtech20
// Umstellung der Guard-Syntax auf Statemate-Style, Implementierung des
// LabelParsers fuer den Editor. Anpassung der Schnittstelle.
//
//
//
//
//----------------------------------------------------------------------
| MartinSteffen/pest | src/Pest2/TESC1/TESCLabelParser.java | 1,009 | // gegeben werden behoben. | line_comment | nl | package tesc1;
import java.io.*;
import java.lang.String;
import java.util.Vector;
import absyn.*;
import util.*;
/**
* Label-Parser fuer den Editor.
* <p>
* @author Michael Suelzer, Christoph Schuette.
* @version $Id: TESCLabelParser.java,v 1.5 1999-02-07 11:58:30 swtech20 Exp $
*/
class TESCLabelParser extends TESCParser {
protected Statechart statechart;
// Der Standard-Ktor muss verborgen werden, da
// das Parsen eines Labels ohne Statechart
// keinen Sinn macht.
private TESCLabelParser() {};
/**
* Constructor.
*/
public TESCLabelParser (Statechart sc) {
statechart = sc;
eventlist = sc.events;
bvarlist = sc.bvars;
pathlist = sc.cnames;
}
/**
* Startet den Parsevorgang fuer ein Label.
*/
public TLabel readLabel (BufferedReader br) throws IOException {
warningText = new Vector ();
warningCount = 0 ;
errorText = new Vector ();
errorCount = 0;
lexer = new TESCTokenizer (br);
token = lexer.getNextToken ();
debug ("parseLabel");
TLabel label = parseLabel ();
// Die geaenderten Listen nach aussen geben
statechart.bvars = bvarlist;
statechart.events = eventlist;
statechart.cnames = pathlist;
return label;
}
/**
* LABEL ::= {GUARD} {"/" ACTION}
*/
public TLabel parseLabel () throws IOException {
//debug ("Enter parseLabel");
Guard guard = parseGuardSTMStyle ();
Action action = null;
if (token.getId () == Token.TOK_SLASH) {
matchToken (Token.Slash);
action = parseActions ();
}
else
action = new ActionEmpty (new Dummy ());
// Caption fuer TLabel aufbauen.
TLabel label = new TLabel (guard, action);
TESCSaver saver = new TESCSaver (null);
saver.setCaption (label);
// Sollte wider Erwarten ein Fehler auftreten, dann merken
errorCount += saver.getErrorCount ();
for (int i=0; i < saver.getErrorCount (); i++)
Error (saver.getErrorText (i));
//debug ("Leave parseLabel");
return label;
}
}
//----------------------------------------------------------------------
// Label-Parser
// ------------
//
// $Log: not supported by cvs2svn $
// Revision 1.4 1999/02/01 11:52:58 swtech20
// - globaler Debug-Schalter
//
// Revision 1.3 1999/01/20 17:32:10 swtech20
// - Status und Doku aktualisiert
// - Fehler, dass Anderungen an Bvarlisten ... nicht nach aussen-
// gegeben werden<SUF>
//
// Revision 1.2 1999/01/18 17:08:52 swtech20
// - okDialog -> userMessage
// - Pruefung auf gui==null
// - package visibility fuer Nicht-Schnittstellenklassen
//
// Revision 1.1 1999/01/17 17:16:41 swtech20
// Umstellung der Guard-Syntax auf Statemate-Style, Implementierung des
// LabelParsers fuer den Editor. Anpassung der Schnittstelle.
//
//
//
//
//----------------------------------------------------------------------
|
99415_6 | package be.ugent.devops.services.logic;
import be.ugent.devops.commons.model.*;
import be.ugent.devops.services.logic.utils.BonusCode;
import be.ugent.devops.services.logic.utils.POIsHint;
import io.prometheus.client.Counter;
import io.prometheus.client.Gauge;
import io.prometheus.client.exporter.HTTPServer;
import io.vertx.core.json.Json;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Collectors;
import static be.ugent.devops.services.logic.utils.Constants.GAMESTATE_PATH;
public class FactionLogicImpl implements FactionLogic {
private static final Logger logger = LoggerFactory.getLogger(FactionLogicImpl.class);
private static final Random rg = new Random();
private static final double PIONEER_GENERATE_GOLD_CHANCE = 0.15;
String bonuscode;
private final HTTPServer prometheusServer;
static final Gauge territory = Gauge.build()
.name("faction_territory")
.help("Amount of territory hold by the Faction.")
.register();
static final Gauge population = Gauge.build()
.name("faction_population")
.help("Population of the Faction.")
.register();
static final Gauge score = Gauge.build()
.name("faction_score")
.help("Score of the Faction.")
.register();
static final Gauge kills = Gauge.build()
.name("faction_kills")
.help("Kills of the Faction.")
.register();
static final Gauge gold = Gauge.build()
.name("faction_gold")
.help("Gold of the Faction.")
.register();
static final Counter heals = Counter.build()
.name("cleric_heals")
.help("How much units have been healed by the cleric")
.register();
static final Counter fortifications = Counter.build()
.name("worker_fortifications")
.help("How much tiles have the workers fortified")
.register();
private final JsonObject config;
private String currentGameId;
private List<POI> pointsOfInterest;
private static Path statePath = Path.of(GAMESTATE_PATH); // Define a path for your state here. Make it configurable!
GameState gameState;
private void saveState() {
// Only try to save the state if it has changed!
if (gameState.isChanged()) {
logger.info("Creating state snapshot!");
try {
if ((statePath).toFile().exists()) {
if (statePath.toFile().delete()) {
logger.info("verwijderd");
}
}
Files.createFile(statePath);
Files.writeString(statePath, Json.encode(gameState), StandardCharsets.UTF_8);
} catch (IOException e) {
logger.warn("Could not write state!", e);
}
}
}
private void restoreState() {
// Only try to restore the state if a state file exists!
if (statePath.toFile().exists()) {
try {
gameState = Json.decodeValue(Files.readString(statePath, StandardCharsets.UTF_8), GameState.class);
pointsOfInterest = gameState.getPointsOfInterest();
} catch (Exception e) {
logger.warn("Could not restore state!", e);
}
}
// If this line is reached and gameState is still 'null', initialize a new instance
if (gameState == null) {
logger.info("Initialized new gamestate");
gameState = new GameState();
}
}
public FactionLogicImpl() {
this(new JsonObject());
}
public FactionLogicImpl(JsonObject config) {
this.config = config;
pointsOfInterest = new ArrayList<>();
logger.info("New FactionLogicImplementation created");
try {
prometheusServer = new HTTPServer(1234);
} catch (IOException ex) {
// Wrap the IO Exception as a Runtime Exception so HttpBinding can remain unchanged.
throw new RuntimeException("The HTTPServer required for Prometheus could not be created!", ex);
}
//Restore from state if needed
restoreState();
}
@Override
public BaseMove nextBaseMove(BaseMoveInput input) {
if (!input.context().gameId().equals(currentGameId)) {
currentGameId = input.context().gameId();
gameState = new GameState();
logger.info("Start running game with id {}...", currentGameId);
logger.info("Reset gamestate");
}
territory.set(input.faction().territorySize()); //aanpassing van tuto --> hier : .getFaction().getTerritorySize() --> .faction().territorySize()
population.set(input.faction().territorySize());
score.set(input.faction().score());
kills.set(input.faction().kills());
gold.set(input.faction().gold());
saveState();
//Check if we need to redeem a bonus code
if (bonuscode != null) {
String kopie = new String(bonuscode);
bonuscode = null;
logger.info("Redeeming this bonuscode: {}", kopie);
return MoveFactory.redeemBonusCode(kopie);
}
return nextUnit(input.faction())
.filter(type -> input.faction().gold() >= input.context().unitCost().get(type) && input.buildSlotState().isEmpty())
.map(MoveFactory::baseBuildUnit)
.orElseGet(() -> input.buildSlotState()
.map(it -> MoveFactory.baseContinueBuilding())
.orElseGet(MoveFactory::baseReceiveIncome)
);
}
@Override
public UnitMove nextUnitMove(UnitMoveInput input) {
return switch (input.unit().type()) {
case PIONEER -> pioneerLogic(input);
case SOLDIER -> soldierLogic(input);
case WORKER -> workerLogic(input);
case CLERIC -> clericLogic(input);
};
}
private Optional<UnitType> nextUnit(Faction faction) {
if (faction.population() < faction.populationCap()) {
return Optional.of(randomListItem(List.of(UnitType.PIONEER, UnitType.WORKER, UnitType.SOLDIER, UnitType.CLERIC)));
} else {
return Optional.empty();
}
}
private UnitMove workerLogic(UnitMoveInput input) {
var worker = input.unit();
var workerLocation = input.unitLocation();
// Always try to move away from our own base location and enemy locations
if (workerLocation.isBase() || isHostileLocation(workerLocation, worker.owner())) {
return travel(input).orElse(MoveFactory.unitIdle()); // 0G
}
// If not on resource, try moving to a resource (that is not in enemy territory)
var resourceLocation = input.neighbouringLocations().stream()
.filter(loc -> loc.isResource() && !isHostileLocation(loc, worker.owner()))
.findAny();
if (!workerLocation.isResource() && resourceLocation.isPresent() && resourceLocation.get().getOccupyingUnit().isEmpty()) {
return MoveFactory.unitTravelTo(resourceLocation.get()); // 0G
}
// If on a neutral or owned resource
if (workerLocation.isResource() && !isHostileLocation(workerLocation, worker.owner())) {
// First capture if neutral
if (workerLocation.getOwner().isEmpty()) {
return MoveFactory.unitConquerLocation(); //75G
} else if (!workerLocation.isFortified()) {
// Fortify this strategic location
fortifications.inc();
return MoveFactory.unitFortifyLocation(); // 150G
} else {
// Profit!
return MoveFactory.unitGenerateGold(); // 0G
}
}
for (POI p : pointsOfInterest) {
if (p.getResource()) {
if (Math.abs(p.getX() - workerLocation.getX()) <= 15) {
if (p.getX() > workerLocation.getX()) {
return MoveFactory.unitTravelTo(new Coordinate(workerLocation.getX() + 1, workerLocation.getY()));
} else {
return MoveFactory.unitTravelTo(new Coordinate(workerLocation.getX() - 1, workerLocation.getY()));
}
}
if (Math.abs(p.getY() - workerLocation.getY()) <= 15) {
if (p.getY() > workerLocation.getY()) {
return MoveFactory.unitTravelTo(new Coordinate(workerLocation.getX(), workerLocation.getY() + 1));
} else {
return MoveFactory.unitTravelTo(new Coordinate(workerLocation.getX(), workerLocation.getY() - 1));
}
}
}
}
// Otherwise: do random action and hope for the best!
//var action = randomListItem(List.of(UnitMoveType.TRAVEL, UnitMoveType.FORTIFY, UnitMoveType.CONQUER_NEUTRAL_TILE, UnitMoveType.GENERATE_GOLD));
if (/*action.equals(UnitMoveType.FORTIFY) &&*/ workerLocation.getOwner().equals(Optional.of(worker.owner())) && input.faction().gold() > 1000L) {
return MoveFactory.unitFortifyLocation(); // 150G
} else if (/*action.equals(UnitMoveType.CONQUER_NEUTRAL_TILE) &&*/ workerLocation.getOwner().isEmpty() && input.faction().gold() > 500L) {
return MoveFactory.unitConquerLocation(); // 75G
} else if (/*action.equals(UnitMoveType.GENERATE_GOLD) &&*/ Optional.of(worker.owner()).equals(workerLocation.getOwner())) {
return MoveFactory.unitGenerateGold(); // 0G
} else {
// Travel
return travel(input).orElse(MoveFactory.unitIdle()); // 2x 0G
}
}
private UnitMove pioneerLogic(UnitMoveInput input) {
//logger.info("Pioneer executing a move");
var pioneer = input.unit();
var pioneerLocation = input.unitLocation();
// If possible, conquer territory
if (!Optional.of(pioneer.owner()).equals(pioneerLocation.getOwner())) {
if (pioneerLocation.getOwner().isEmpty()) {
//logger.info("Pioneer with id {} conquered territory",pioneer.id());
return MoveFactory.unitConquerLocation(); // 75G
} else {
//logger.info("Pioneer with id {} neutralized territory",pioneer.id());
return MoveFactory.unitNeutralizeLocation(); // 25G
}
}
// Attack enemies in range
var enemyInRange = input.neighbouringLocations().stream()
.flatMap(loc -> loc.getOccupyingUnit().stream())
.filter(occupyingUnit -> occupyingUnit.owner() != pioneer.owner())
.findAny();
if (enemyInRange.isPresent()) {
//logger.info("Pioneer with id {} attacked an enemy in range",pioneer.id());
return MoveFactory.unitAttack(enemyInRange.get()); // 25G
}
// Otherwise, generate income a percentage of the time, else travel around
if (rg.nextDouble() <= PIONEER_GENERATE_GOLD_CHANCE) {
//logger.info("Pioneer with id {} generated gold",pioneer.id());
return MoveFactory.unitGenerateGold(); // 0G
} else {
//logger.info("Pioneer with id {} travelled",pioneer.id());
return travel(input).orElse(MoveFactory.unitGenerateGold()); // 2x 0G
}
}
private UnitMove soldierLogic(UnitMoveInput input) {
var soldier = input.unit();
var soldierLocation = input.unitLocation();
// Attack if enemy unit is near (should have priority as the soldier is the strongest unit)
var enemyInRange = input.neighbouringLocations().stream()
.flatMap(loc -> loc.getOccupyingUnit().stream())
.filter(occupyingUnit -> occupyingUnit.owner() != soldier.owner())
.findAny();
if (enemyInRange.isPresent()) {
return MoveFactory.unitAttack(enemyInRange.get()); // 25G
}
for (POI p : pointsOfInterest) {
if (p.getUnit() != null) {
if (Math.abs(p.getX() - soldierLocation.getX()) <= 15) {
if (p.getX() > soldierLocation.getX()) {
return MoveFactory.unitTravelTo(new Coordinate(soldierLocation.getX() + 1, soldierLocation.getY()));
} else {
return MoveFactory.unitTravelTo(new Coordinate(soldierLocation.getX() - 1, soldierLocation.getY()));
}
}
if (Math.abs(p.getY() - soldierLocation.getY()) <= 15) {
if (p.getY() > soldierLocation.getY()) {
return MoveFactory.unitTravelTo(new Coordinate(soldierLocation.getX(), soldierLocation.getY() + 1));
} else {
return MoveFactory.unitTravelTo(new Coordinate(soldierLocation.getX(), soldierLocation.getY() - 1));
}
}
}
}
// Prepare defences for next encounter
if (!soldier.defenseBonus()) {
return MoveFactory.unitPrepareDefense(); // 15G
}
// If possible, conquer territory
if (!Optional.of(soldier.owner()).equals(soldierLocation.getOwner())) {
if (soldierLocation.getOwner().isEmpty()) {
return MoveFactory.unitConquerLocation(); // 75G
} else {
return MoveFactory.unitNeutralizeLocation(); // 25G
}
}
// Else try to travel
return travel(input).orElse(MoveFactory.unitPrepareDefense()); // 0G of 15G
}
/* Moves cleric
* TRAVEL
* ATTACK
* HEAL
* CONVERT
* PREPARE_DEFENSE
* CONVERT
* IDLE
* */
private UnitMove clericLogic(UnitMoveInput input) {
var cleric = input.unit();
var clericLocation = input.unitLocation();
logger.info("Cleric with id {} is making a move", cleric.id());
logger.info("This cleric has his defensebonus on {}", cleric.defenseBonus());
//Voor aanvallen
var enemyInRange = input.neighbouringLocations().stream()
.flatMap(loc -> loc.getOccupyingUnit().stream())
.filter(occupyingUnit -> occupyingUnit.owner() != cleric.owner())
.findAny();
logger.info("Cleric with id {} has an enemy in range", cleric.id());
//Voor healen
var woundedAllyInRange = input.neighbouringLocations().stream()
.flatMap(loc -> loc.getOccupyingUnit().stream())
.filter(occupyingUnit -> occupyingUnit.owner() == cleric.owner() && isWounded(occupyingUnit))
.findAny();
logger.info("Cleric with id {} has an ally in range", cleric.id());
//focus op healing van allies
if (woundedAllyInRange.isPresent()) {
logger.info("Cleric with id {} chose to heal an ally\n", cleric.id());
heals.inc();
return MoveFactory.unitHeal(woundedAllyInRange.get()); // 25G
}
//Converteer enemy unit
if (enemyInRange.isPresent() && cleric.defenseBonus()) {
logger.info("Cleric with id {} chose to convert an enemy\n", cleric.id());
return MoveFactory.unitConvert(enemyInRange.get()); // 150G
}
if (enemyInRange.isPresent()) {
logger.info("Cleric with id {} chose attack an enemy\n", cleric.id());
return MoveFactory.unitAttack(enemyInRange.get()); // 25G
}
logger.info("Cleric with id {} will travel or prepare defense", cleric.id());
return travel(input).orElse(MoveFactory.unitPrepareDefense()); // 0 of 15G
}
private <T> T randomListItem(List<T> input) {
return input.get(rg.nextInt(input.size()));
}
private boolean isHostileLocation(Location location, Integer faction) {
return location.getOwner().map(owner -> !owner.equals(faction)).orElse(false);
}
private Optional<UnitMove> travel(UnitMoveInput input) {
var possibleMoves = input.neighbouringLocations().stream()
.filter(loc -> !loc.isBase() || !loc.getOwner().equals(Optional.of(input.unit().owner()))) // Don't go back to own base.
.filter(loc -> loc.getOccupyingUnit().isEmpty()) // The target location should not be occupied.
.collect(Collectors.toList());
return possibleMoves.isEmpty() ? Optional.empty() : Optional.of(MoveFactory.unitTravelTo(randomListItem(possibleMoves)));
}
private boolean isWounded(Unit unit) {
return
switch (unit.type()) {
case PIONEER -> unit.health() < 3;
case WORKER -> unit.health() < 5;
case SOLDIER -> unit.health() < 6;
case CLERIC -> unit.health() < 4;
};
}
public Object registerPOIs(POIsHint input) {
logger.info("Received POI list for game: {}", input.gameId());
logger.info("Old POI list was {} long", pointsOfInterest.size());
for (Location l : input.locations()) {
logger.info("Location: [{},{}] is a {}", l.getX(), l.getY(), l.isResource() ? "Resource" : "Enemy base");
pointsOfInterest.add(new POI(l.getX(), l.getY(), l.isResource(), l.getOccupyingUnit().isEmpty() ? null : l.getOccupyingUnit().get()));
}
logger.info("New POI list is {} long", pointsOfInterest.size());
gameState.setPointsOfInterest(pointsOfInterest);
return "POI list received";
}
public Object registerBonusCodes(BonusCode input) {
logger.info("Received BonusCode: {}, expires on: {}", input.type(), input.validUntil());
bonuscode = input.code();
return "Bonuscode received";
}
}
| MateoVanDamme/virtual-army | logic-service/src/main/java/be/ugent/devops/services/logic/FactionLogicImpl.java | 5,358 | //aanpassing van tuto --> hier : .getFaction().getTerritorySize() --> .faction().territorySize()
| line_comment | nl | package be.ugent.devops.services.logic;
import be.ugent.devops.commons.model.*;
import be.ugent.devops.services.logic.utils.BonusCode;
import be.ugent.devops.services.logic.utils.POIsHint;
import io.prometheus.client.Counter;
import io.prometheus.client.Gauge;
import io.prometheus.client.exporter.HTTPServer;
import io.vertx.core.json.Json;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Collectors;
import static be.ugent.devops.services.logic.utils.Constants.GAMESTATE_PATH;
public class FactionLogicImpl implements FactionLogic {
private static final Logger logger = LoggerFactory.getLogger(FactionLogicImpl.class);
private static final Random rg = new Random();
private static final double PIONEER_GENERATE_GOLD_CHANCE = 0.15;
String bonuscode;
private final HTTPServer prometheusServer;
static final Gauge territory = Gauge.build()
.name("faction_territory")
.help("Amount of territory hold by the Faction.")
.register();
static final Gauge population = Gauge.build()
.name("faction_population")
.help("Population of the Faction.")
.register();
static final Gauge score = Gauge.build()
.name("faction_score")
.help("Score of the Faction.")
.register();
static final Gauge kills = Gauge.build()
.name("faction_kills")
.help("Kills of the Faction.")
.register();
static final Gauge gold = Gauge.build()
.name("faction_gold")
.help("Gold of the Faction.")
.register();
static final Counter heals = Counter.build()
.name("cleric_heals")
.help("How much units have been healed by the cleric")
.register();
static final Counter fortifications = Counter.build()
.name("worker_fortifications")
.help("How much tiles have the workers fortified")
.register();
private final JsonObject config;
private String currentGameId;
private List<POI> pointsOfInterest;
private static Path statePath = Path.of(GAMESTATE_PATH); // Define a path for your state here. Make it configurable!
GameState gameState;
private void saveState() {
// Only try to save the state if it has changed!
if (gameState.isChanged()) {
logger.info("Creating state snapshot!");
try {
if ((statePath).toFile().exists()) {
if (statePath.toFile().delete()) {
logger.info("verwijderd");
}
}
Files.createFile(statePath);
Files.writeString(statePath, Json.encode(gameState), StandardCharsets.UTF_8);
} catch (IOException e) {
logger.warn("Could not write state!", e);
}
}
}
private void restoreState() {
// Only try to restore the state if a state file exists!
if (statePath.toFile().exists()) {
try {
gameState = Json.decodeValue(Files.readString(statePath, StandardCharsets.UTF_8), GameState.class);
pointsOfInterest = gameState.getPointsOfInterest();
} catch (Exception e) {
logger.warn("Could not restore state!", e);
}
}
// If this line is reached and gameState is still 'null', initialize a new instance
if (gameState == null) {
logger.info("Initialized new gamestate");
gameState = new GameState();
}
}
public FactionLogicImpl() {
this(new JsonObject());
}
public FactionLogicImpl(JsonObject config) {
this.config = config;
pointsOfInterest = new ArrayList<>();
logger.info("New FactionLogicImplementation created");
try {
prometheusServer = new HTTPServer(1234);
} catch (IOException ex) {
// Wrap the IO Exception as a Runtime Exception so HttpBinding can remain unchanged.
throw new RuntimeException("The HTTPServer required for Prometheus could not be created!", ex);
}
//Restore from state if needed
restoreState();
}
@Override
public BaseMove nextBaseMove(BaseMoveInput input) {
if (!input.context().gameId().equals(currentGameId)) {
currentGameId = input.context().gameId();
gameState = new GameState();
logger.info("Start running game with id {}...", currentGameId);
logger.info("Reset gamestate");
}
territory.set(input.faction().territorySize()); //aanpassing van<SUF>
population.set(input.faction().territorySize());
score.set(input.faction().score());
kills.set(input.faction().kills());
gold.set(input.faction().gold());
saveState();
//Check if we need to redeem a bonus code
if (bonuscode != null) {
String kopie = new String(bonuscode);
bonuscode = null;
logger.info("Redeeming this bonuscode: {}", kopie);
return MoveFactory.redeemBonusCode(kopie);
}
return nextUnit(input.faction())
.filter(type -> input.faction().gold() >= input.context().unitCost().get(type) && input.buildSlotState().isEmpty())
.map(MoveFactory::baseBuildUnit)
.orElseGet(() -> input.buildSlotState()
.map(it -> MoveFactory.baseContinueBuilding())
.orElseGet(MoveFactory::baseReceiveIncome)
);
}
@Override
public UnitMove nextUnitMove(UnitMoveInput input) {
return switch (input.unit().type()) {
case PIONEER -> pioneerLogic(input);
case SOLDIER -> soldierLogic(input);
case WORKER -> workerLogic(input);
case CLERIC -> clericLogic(input);
};
}
private Optional<UnitType> nextUnit(Faction faction) {
if (faction.population() < faction.populationCap()) {
return Optional.of(randomListItem(List.of(UnitType.PIONEER, UnitType.WORKER, UnitType.SOLDIER, UnitType.CLERIC)));
} else {
return Optional.empty();
}
}
private UnitMove workerLogic(UnitMoveInput input) {
var worker = input.unit();
var workerLocation = input.unitLocation();
// Always try to move away from our own base location and enemy locations
if (workerLocation.isBase() || isHostileLocation(workerLocation, worker.owner())) {
return travel(input).orElse(MoveFactory.unitIdle()); // 0G
}
// If not on resource, try moving to a resource (that is not in enemy territory)
var resourceLocation = input.neighbouringLocations().stream()
.filter(loc -> loc.isResource() && !isHostileLocation(loc, worker.owner()))
.findAny();
if (!workerLocation.isResource() && resourceLocation.isPresent() && resourceLocation.get().getOccupyingUnit().isEmpty()) {
return MoveFactory.unitTravelTo(resourceLocation.get()); // 0G
}
// If on a neutral or owned resource
if (workerLocation.isResource() && !isHostileLocation(workerLocation, worker.owner())) {
// First capture if neutral
if (workerLocation.getOwner().isEmpty()) {
return MoveFactory.unitConquerLocation(); //75G
} else if (!workerLocation.isFortified()) {
// Fortify this strategic location
fortifications.inc();
return MoveFactory.unitFortifyLocation(); // 150G
} else {
// Profit!
return MoveFactory.unitGenerateGold(); // 0G
}
}
for (POI p : pointsOfInterest) {
if (p.getResource()) {
if (Math.abs(p.getX() - workerLocation.getX()) <= 15) {
if (p.getX() > workerLocation.getX()) {
return MoveFactory.unitTravelTo(new Coordinate(workerLocation.getX() + 1, workerLocation.getY()));
} else {
return MoveFactory.unitTravelTo(new Coordinate(workerLocation.getX() - 1, workerLocation.getY()));
}
}
if (Math.abs(p.getY() - workerLocation.getY()) <= 15) {
if (p.getY() > workerLocation.getY()) {
return MoveFactory.unitTravelTo(new Coordinate(workerLocation.getX(), workerLocation.getY() + 1));
} else {
return MoveFactory.unitTravelTo(new Coordinate(workerLocation.getX(), workerLocation.getY() - 1));
}
}
}
}
// Otherwise: do random action and hope for the best!
//var action = randomListItem(List.of(UnitMoveType.TRAVEL, UnitMoveType.FORTIFY, UnitMoveType.CONQUER_NEUTRAL_TILE, UnitMoveType.GENERATE_GOLD));
if (/*action.equals(UnitMoveType.FORTIFY) &&*/ workerLocation.getOwner().equals(Optional.of(worker.owner())) && input.faction().gold() > 1000L) {
return MoveFactory.unitFortifyLocation(); // 150G
} else if (/*action.equals(UnitMoveType.CONQUER_NEUTRAL_TILE) &&*/ workerLocation.getOwner().isEmpty() && input.faction().gold() > 500L) {
return MoveFactory.unitConquerLocation(); // 75G
} else if (/*action.equals(UnitMoveType.GENERATE_GOLD) &&*/ Optional.of(worker.owner()).equals(workerLocation.getOwner())) {
return MoveFactory.unitGenerateGold(); // 0G
} else {
// Travel
return travel(input).orElse(MoveFactory.unitIdle()); // 2x 0G
}
}
private UnitMove pioneerLogic(UnitMoveInput input) {
//logger.info("Pioneer executing a move");
var pioneer = input.unit();
var pioneerLocation = input.unitLocation();
// If possible, conquer territory
if (!Optional.of(pioneer.owner()).equals(pioneerLocation.getOwner())) {
if (pioneerLocation.getOwner().isEmpty()) {
//logger.info("Pioneer with id {} conquered territory",pioneer.id());
return MoveFactory.unitConquerLocation(); // 75G
} else {
//logger.info("Pioneer with id {} neutralized territory",pioneer.id());
return MoveFactory.unitNeutralizeLocation(); // 25G
}
}
// Attack enemies in range
var enemyInRange = input.neighbouringLocations().stream()
.flatMap(loc -> loc.getOccupyingUnit().stream())
.filter(occupyingUnit -> occupyingUnit.owner() != pioneer.owner())
.findAny();
if (enemyInRange.isPresent()) {
//logger.info("Pioneer with id {} attacked an enemy in range",pioneer.id());
return MoveFactory.unitAttack(enemyInRange.get()); // 25G
}
// Otherwise, generate income a percentage of the time, else travel around
if (rg.nextDouble() <= PIONEER_GENERATE_GOLD_CHANCE) {
//logger.info("Pioneer with id {} generated gold",pioneer.id());
return MoveFactory.unitGenerateGold(); // 0G
} else {
//logger.info("Pioneer with id {} travelled",pioneer.id());
return travel(input).orElse(MoveFactory.unitGenerateGold()); // 2x 0G
}
}
private UnitMove soldierLogic(UnitMoveInput input) {
var soldier = input.unit();
var soldierLocation = input.unitLocation();
// Attack if enemy unit is near (should have priority as the soldier is the strongest unit)
var enemyInRange = input.neighbouringLocations().stream()
.flatMap(loc -> loc.getOccupyingUnit().stream())
.filter(occupyingUnit -> occupyingUnit.owner() != soldier.owner())
.findAny();
if (enemyInRange.isPresent()) {
return MoveFactory.unitAttack(enemyInRange.get()); // 25G
}
for (POI p : pointsOfInterest) {
if (p.getUnit() != null) {
if (Math.abs(p.getX() - soldierLocation.getX()) <= 15) {
if (p.getX() > soldierLocation.getX()) {
return MoveFactory.unitTravelTo(new Coordinate(soldierLocation.getX() + 1, soldierLocation.getY()));
} else {
return MoveFactory.unitTravelTo(new Coordinate(soldierLocation.getX() - 1, soldierLocation.getY()));
}
}
if (Math.abs(p.getY() - soldierLocation.getY()) <= 15) {
if (p.getY() > soldierLocation.getY()) {
return MoveFactory.unitTravelTo(new Coordinate(soldierLocation.getX(), soldierLocation.getY() + 1));
} else {
return MoveFactory.unitTravelTo(new Coordinate(soldierLocation.getX(), soldierLocation.getY() - 1));
}
}
}
}
// Prepare defences for next encounter
if (!soldier.defenseBonus()) {
return MoveFactory.unitPrepareDefense(); // 15G
}
// If possible, conquer territory
if (!Optional.of(soldier.owner()).equals(soldierLocation.getOwner())) {
if (soldierLocation.getOwner().isEmpty()) {
return MoveFactory.unitConquerLocation(); // 75G
} else {
return MoveFactory.unitNeutralizeLocation(); // 25G
}
}
// Else try to travel
return travel(input).orElse(MoveFactory.unitPrepareDefense()); // 0G of 15G
}
/* Moves cleric
* TRAVEL
* ATTACK
* HEAL
* CONVERT
* PREPARE_DEFENSE
* CONVERT
* IDLE
* */
private UnitMove clericLogic(UnitMoveInput input) {
var cleric = input.unit();
var clericLocation = input.unitLocation();
logger.info("Cleric with id {} is making a move", cleric.id());
logger.info("This cleric has his defensebonus on {}", cleric.defenseBonus());
//Voor aanvallen
var enemyInRange = input.neighbouringLocations().stream()
.flatMap(loc -> loc.getOccupyingUnit().stream())
.filter(occupyingUnit -> occupyingUnit.owner() != cleric.owner())
.findAny();
logger.info("Cleric with id {} has an enemy in range", cleric.id());
//Voor healen
var woundedAllyInRange = input.neighbouringLocations().stream()
.flatMap(loc -> loc.getOccupyingUnit().stream())
.filter(occupyingUnit -> occupyingUnit.owner() == cleric.owner() && isWounded(occupyingUnit))
.findAny();
logger.info("Cleric with id {} has an ally in range", cleric.id());
//focus op healing van allies
if (woundedAllyInRange.isPresent()) {
logger.info("Cleric with id {} chose to heal an ally\n", cleric.id());
heals.inc();
return MoveFactory.unitHeal(woundedAllyInRange.get()); // 25G
}
//Converteer enemy unit
if (enemyInRange.isPresent() && cleric.defenseBonus()) {
logger.info("Cleric with id {} chose to convert an enemy\n", cleric.id());
return MoveFactory.unitConvert(enemyInRange.get()); // 150G
}
if (enemyInRange.isPresent()) {
logger.info("Cleric with id {} chose attack an enemy\n", cleric.id());
return MoveFactory.unitAttack(enemyInRange.get()); // 25G
}
logger.info("Cleric with id {} will travel or prepare defense", cleric.id());
return travel(input).orElse(MoveFactory.unitPrepareDefense()); // 0 of 15G
}
private <T> T randomListItem(List<T> input) {
return input.get(rg.nextInt(input.size()));
}
private boolean isHostileLocation(Location location, Integer faction) {
return location.getOwner().map(owner -> !owner.equals(faction)).orElse(false);
}
private Optional<UnitMove> travel(UnitMoveInput input) {
var possibleMoves = input.neighbouringLocations().stream()
.filter(loc -> !loc.isBase() || !loc.getOwner().equals(Optional.of(input.unit().owner()))) // Don't go back to own base.
.filter(loc -> loc.getOccupyingUnit().isEmpty()) // The target location should not be occupied.
.collect(Collectors.toList());
return possibleMoves.isEmpty() ? Optional.empty() : Optional.of(MoveFactory.unitTravelTo(randomListItem(possibleMoves)));
}
private boolean isWounded(Unit unit) {
return
switch (unit.type()) {
case PIONEER -> unit.health() < 3;
case WORKER -> unit.health() < 5;
case SOLDIER -> unit.health() < 6;
case CLERIC -> unit.health() < 4;
};
}
public Object registerPOIs(POIsHint input) {
logger.info("Received POI list for game: {}", input.gameId());
logger.info("Old POI list was {} long", pointsOfInterest.size());
for (Location l : input.locations()) {
logger.info("Location: [{},{}] is a {}", l.getX(), l.getY(), l.isResource() ? "Resource" : "Enemy base");
pointsOfInterest.add(new POI(l.getX(), l.getY(), l.isResource(), l.getOccupyingUnit().isEmpty() ? null : l.getOccupyingUnit().get()));
}
logger.info("New POI list is {} long", pointsOfInterest.size());
gameState.setPointsOfInterest(pointsOfInterest);
return "POI list received";
}
public Object registerBonusCodes(BonusCode input) {
logger.info("Received BonusCode: {}, expires on: {}", input.type(), input.validUntil());
bonuscode = input.code();
return "Bonuscode received";
}
}
|
150386_2 | package be.kuleuven.candycrush;
import javafx.util.Pair;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CandycrushModel {
private String speler;
private Board<Candy> candyBoard;
private int score;
private boolean gestart;
private BoardSize boardSize;
public CandycrushModel(String speler, int width, int height){
this.speler = speler;
boardSize = new BoardSize(height, width);
candyBoard = new Board<>(boardSize);
score = 0;
gestart = false;
Function<Position, Candy> candyCreator = position -> randomCandy();
candyBoard.fill(candyCreator);
}
public CandycrushModel(String speler) {
this(speler, 10, 10);
}
public String getSpeler() {
return speler;
}
public BoardSize getBoardSize(){
return boardSize;
}
public Board<Candy> getSpeelbord() {
return candyBoard;
}
public void setCandyBoard(Board<Candy> board){
candyBoard = board;
}
public int getWidth() {
return boardSize.kolommen();
}
public int getHeight() {
return boardSize.rijen();
}
public int getScore(){
return this.score;
}
public boolean isGestart(){
return this.gestart;
}
public void start(){
this.gestart = true;
}
public void reset(){
this.score =0;
this.gestart = false;
Function<Position, Candy> candyCreator = position -> randomCandy();
candyBoard.fill(candyCreator);
}
public Candy randomCandy(){
Random random = new Random();
int randomGetal = random.nextInt(8);
return switch (randomGetal) {
case 4 -> new Erwt();
case 5 -> new Kropsla();
case 6 -> new Lente_ui();
case 7 -> new Tomaat();
default -> new NormalCandy(randomGetal);
};
}
public void candyWithIndexSelected(Position position){
Iterable<Position> Neighbours = getSameNeighbourPositions(position);
/*for(Position Neighbour : Neighbours){
candyBoard.replaceCellAt(Neighbour, randomCandy());
score = score + 2;
}
candyBoard.replaceCellAt(position, randomCandy());
score++;*/
candyBoard.replaceCellAt(position, new noCandy());
score++;
fallDownTo(position, candyBoard);
updateBoard(candyBoard);
System.out.println(getAllSwaps(candyBoard));
}
Iterable<Position> getSameNeighbourPositions(Position position){
Iterable<Position> neighbors = position.neighborPositions();
ArrayList<Position> result = new ArrayList<>();
for(Position neighbor : neighbors){
Candy candy = candyBoard.getCellAt(position);
Candy neighborCandy = candyBoard.getCellAt(neighbor);
if(candy.equals(neighborCandy)){
result.add(neighbor);
}
}
return result;
}
public boolean firstTwoHaveCandy(Candy candy, Stream<Position> positions, Board<Candy> board){
return positions
.limit(2)
.allMatch(p -> board.getCellAt(p).equals(candy));
}
public Stream<Position> horizontalStartingPositions(Board<Candy> board){
return boardSize.positions().stream()
.filter(p -> {
Stream<Position> buren = p.walkLeft();
return !firstTwoHaveCandy(board.getCellAt(p), buren, board);
});
}
public Stream<Position> verticalStartingPositions(Board<Candy> board){
return boardSize.positions().stream()
.filter(p -> {
Stream<Position> buren = p.walkUp();
return !firstTwoHaveCandy(board.getCellAt(p), buren, board);
});
}
public List<Position> longestMatchToRight(Position pos, Board<Candy> board){
Stream<Position> walked = pos.walkRight();
return walked
.takeWhile(p -> board.getCellAt(p).equals(board.getCellAt(pos))
&& !(board.getCellAt(p) instanceof noCandy) && !(board.getCellAt(pos) instanceof noCandy))
.toList();
}
public List<Position> longestMatchDown(Position pos, Board<Candy> board){
Stream<Position> walked = pos.walkDown();
return walked
.takeWhile(p -> board.getCellAt(p).equals(board.getCellAt(pos))
&& !(board.getCellAt(p) instanceof noCandy) && !(board.getCellAt(pos) instanceof noCandy))
.toList();
}
public Set<List<Position>> findAllMatches(Board<Candy> board){
List<List<Position>> allMatches = Stream.concat(horizontalStartingPositions(board), verticalStartingPositions(board))
.flatMap(p -> {
List<Position> horizontalMatch = longestMatchToRight(p, board);
List<Position> verticalMatch = longestMatchDown(p, board);
return Stream.of(horizontalMatch, verticalMatch);
})
.filter(m -> m.size() > 2)
.sorted((match1, match2) -> match2.size() - match1.size())
.toList();
return allMatches.stream()
.filter(match -> allMatches.stream()
.noneMatch(longerMatch -> longerMatch.size() > match.size() && new HashSet<>(longerMatch).containsAll(match)))
.collect(Collectors.toSet());
}
public void clearMatch(List<Position> match, Board<Candy> board){
List<Position> copy = new ArrayList<>(match); // Match is immutable dus maak een copy
if(copy.isEmpty()) return;
Position first = copy.getFirst();
board.replaceCellAt(first, new noCandy());
copy.removeFirst();
score++;
clearMatch(copy, board);
}
public void fallDownTo(List<Position> match, Board<Candy> board){
if(horizontalMatch(match)){
match.forEach(position -> fallDownTo(position, board));
} else {
match.stream()
.max(Comparator.comparingInt(Position::rij)).ifPresent(position -> fallDownTo(position, board));
}
}
public void fallDownTo(Position pos, Board<Candy> board){
try{
Position boven = new Position(pos.rij() - 1, pos.kolom(), boardSize);
if(board.getCellAt(pos) instanceof noCandy){
while (board.getCellAt(boven) instanceof noCandy){
boven = new Position(boven.rij() - 1, boven.kolom(), boardSize);
}
board.replaceCellAt(pos, board.getCellAt(boven));
board.replaceCellAt(boven, new noCandy());
fallDownTo(pos, board);
} else{
fallDownTo(boven, board);
}
} catch (IllegalArgumentException ignored){return;}
}
public boolean horizontalMatch(List<Position> match){
return match.getFirst().rij() == match.getLast().rij();
}
public boolean updateBoard(Board<Candy> board){
Set<List<Position>> matches = findAllMatches(board);
if (matches.isEmpty()) return false;
for(List<Position> match : matches){
clearMatch(match, board);
fallDownTo(match, board);
}
updateBoard(board);
return true;
}
public void swapCandies(Position pos1, Position pos2, Board<Candy> board){
if(!pos1.isNeighbor(pos2) || !matchAfterSwitch(pos1, pos2, board)){
return;
}
if(board.getCellAt(pos1) instanceof noCandy || board.getCellAt(pos2) instanceof noCandy){
return;
}
unsafeSwap(pos1, pos2, board);
updateBoard(board);
}
private void unsafeSwap(Position pos1, Position pos2, Board<Candy> board){
Candy candy1 = board.getCellAt(pos1);
Candy candy2 = board.getCellAt(pos2);
board.replaceCellAt(pos1, candy2);
board.replaceCellAt(pos2, candy1);
}
public boolean matchAfterSwitch(Position pos1, Position pos2, Board<Candy> board){
unsafeSwap(pos1, pos2, board);
Set<List<Position>> matches = findAllMatches(board);
unsafeSwap(pos1, pos2, board);
return !matches.isEmpty();
}
private Set<List<Position>> getAllSwaps(Board<Candy> board){
Set<List<Position>> swaps = new HashSet<>();
for (Position position : board.getBoardSize().positions()){
Iterable<Position> neighbours = position.neighborPositions();
for(Position neighbour : neighbours){
if(!matchAfterSwitch(neighbour, position, board)){
continue;
}
if(board.getCellAt(position) instanceof noCandy || board.getCellAt(neighbour) instanceof noCandy){
continue;
}
List<Position> swap = Arrays.asList(position, neighbour);
// Verwijderd duplicaten in de lijst, want
// r1c2-r1c3 == r1c3-r1c2
List<Position> reverseSwap = Arrays.asList(neighbour, position);
if(swaps.contains(swap) || swaps.contains(reverseSwap)){
continue;
}
swaps.add(swap);
}
}
return swaps;
}
public Solution maximizeScore(){
List<List<Position>> moves = new ArrayList<>();
Solution intialSolution = new Solution(0,candyBoard, moves);
return findOptimalSolution(intialSolution, null);
}
private Solution findOptimalSolution(Solution partialSolution, Solution bestSoFar){
Set<List<Position>> swaps = getAllSwaps(partialSolution.board());
if(swaps.isEmpty()){
System.out.println(partialSolution.score());
System.out.println(partialSolution.calculateScore());
System.out.println("*-*");
if (bestSoFar == null || partialSolution.isBetterThan(bestSoFar)) {
return partialSolution;
} else {
return bestSoFar;
}
}
if(bestSoFar != null && partialSolution.canImproveUpon(bestSoFar)){
return bestSoFar;
}
for(List<Position> swap : swaps){
Board<Candy> mutableBoard = new Board<>(partialSolution.board().getBoardSize());
partialSolution.board().copyTo(mutableBoard);
swapCandies(swap.getFirst(), swap.getLast(), mutableBoard);
List<List<Position>> newMoves = new ArrayList<>(partialSolution.moves());
newMoves.add(swap);
Solution solution = new Solution(0, mutableBoard, newMoves);
int score = solution.calculateScore();
bestSoFar = findOptimalSolution(new Solution(score, mutableBoard, newMoves), bestSoFar);
}
return bestSoFar;
}
public Collection<Solution> solveAll(){
List<List<Position>> moves = new ArrayList<>();
Solution intialSolution = new Solution(0,candyBoard, moves);
ArrayList<Solution> collection = new ArrayList<>();
return findAllSolutions(intialSolution, collection);
}
private Collection<Solution> findAllSolutions(Solution partialSolution, Collection<Solution> solutionsSoFar){
Set<List<Position>> swaps = getAllSwaps(partialSolution.board());
if(swaps.isEmpty()){
System.out.println("Oplossing gevonden B)");
int score = partialSolution.calculateScore();
Solution solution = new Solution(score, partialSolution.board(), partialSolution.moves());
solution.printSolution();
solutionsSoFar.add(solution);
return solutionsSoFar;
}
for(List<Position> swap : swaps){
Board<Candy> mutableBoard = new Board<>(partialSolution.board().getBoardSize());
partialSolution.board().copyTo(mutableBoard);
swapCandies(swap.getFirst(), swap.getLast(), mutableBoard);
List<List<Position>> newMoves = new ArrayList<>(partialSolution.moves());
newMoves.add(swap);
findAllSolutions(new Solution(0, mutableBoard, newMoves), solutionsSoFar);
}
return solutionsSoFar;
}
public Solution solveAny(){
Solution intialSolution = new Solution(0,candyBoard, null);
return findAnySolution(intialSolution);
}
private Solution findAnySolution(Solution partialSolution){
Set<List<Position>> swaps = getAllSwaps(partialSolution.board());
if(swaps.isEmpty()) return partialSolution; // Current.isComplete()
for (List<Position> swap : swaps){
// SWAP
// 1. copy board vanuit record
// 2. swapcandies en update
// 3. maak partialSolution
// 4. recursie
Board<Candy> mutableBoard = new Board<>(partialSolution.board().getBoardSize());
partialSolution.board().copyTo(mutableBoard);
swapCandies(swap.getFirst(), swap.getLast(), mutableBoard);
int score = this.getScore();
return findAnySolution(new Solution(score, mutableBoard, null));
}
return null;
}
} | MathiasHouwen/SES_CandyCrush | candycrush/src/main/java/be/kuleuven/candycrush/CandycrushModel.java | 3,789 | // Verwijderd duplicaten in de lijst, want | line_comment | nl | package be.kuleuven.candycrush;
import javafx.util.Pair;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CandycrushModel {
private String speler;
private Board<Candy> candyBoard;
private int score;
private boolean gestart;
private BoardSize boardSize;
public CandycrushModel(String speler, int width, int height){
this.speler = speler;
boardSize = new BoardSize(height, width);
candyBoard = new Board<>(boardSize);
score = 0;
gestart = false;
Function<Position, Candy> candyCreator = position -> randomCandy();
candyBoard.fill(candyCreator);
}
public CandycrushModel(String speler) {
this(speler, 10, 10);
}
public String getSpeler() {
return speler;
}
public BoardSize getBoardSize(){
return boardSize;
}
public Board<Candy> getSpeelbord() {
return candyBoard;
}
public void setCandyBoard(Board<Candy> board){
candyBoard = board;
}
public int getWidth() {
return boardSize.kolommen();
}
public int getHeight() {
return boardSize.rijen();
}
public int getScore(){
return this.score;
}
public boolean isGestart(){
return this.gestart;
}
public void start(){
this.gestart = true;
}
public void reset(){
this.score =0;
this.gestart = false;
Function<Position, Candy> candyCreator = position -> randomCandy();
candyBoard.fill(candyCreator);
}
public Candy randomCandy(){
Random random = new Random();
int randomGetal = random.nextInt(8);
return switch (randomGetal) {
case 4 -> new Erwt();
case 5 -> new Kropsla();
case 6 -> new Lente_ui();
case 7 -> new Tomaat();
default -> new NormalCandy(randomGetal);
};
}
public void candyWithIndexSelected(Position position){
Iterable<Position> Neighbours = getSameNeighbourPositions(position);
/*for(Position Neighbour : Neighbours){
candyBoard.replaceCellAt(Neighbour, randomCandy());
score = score + 2;
}
candyBoard.replaceCellAt(position, randomCandy());
score++;*/
candyBoard.replaceCellAt(position, new noCandy());
score++;
fallDownTo(position, candyBoard);
updateBoard(candyBoard);
System.out.println(getAllSwaps(candyBoard));
}
Iterable<Position> getSameNeighbourPositions(Position position){
Iterable<Position> neighbors = position.neighborPositions();
ArrayList<Position> result = new ArrayList<>();
for(Position neighbor : neighbors){
Candy candy = candyBoard.getCellAt(position);
Candy neighborCandy = candyBoard.getCellAt(neighbor);
if(candy.equals(neighborCandy)){
result.add(neighbor);
}
}
return result;
}
public boolean firstTwoHaveCandy(Candy candy, Stream<Position> positions, Board<Candy> board){
return positions
.limit(2)
.allMatch(p -> board.getCellAt(p).equals(candy));
}
public Stream<Position> horizontalStartingPositions(Board<Candy> board){
return boardSize.positions().stream()
.filter(p -> {
Stream<Position> buren = p.walkLeft();
return !firstTwoHaveCandy(board.getCellAt(p), buren, board);
});
}
public Stream<Position> verticalStartingPositions(Board<Candy> board){
return boardSize.positions().stream()
.filter(p -> {
Stream<Position> buren = p.walkUp();
return !firstTwoHaveCandy(board.getCellAt(p), buren, board);
});
}
public List<Position> longestMatchToRight(Position pos, Board<Candy> board){
Stream<Position> walked = pos.walkRight();
return walked
.takeWhile(p -> board.getCellAt(p).equals(board.getCellAt(pos))
&& !(board.getCellAt(p) instanceof noCandy) && !(board.getCellAt(pos) instanceof noCandy))
.toList();
}
public List<Position> longestMatchDown(Position pos, Board<Candy> board){
Stream<Position> walked = pos.walkDown();
return walked
.takeWhile(p -> board.getCellAt(p).equals(board.getCellAt(pos))
&& !(board.getCellAt(p) instanceof noCandy) && !(board.getCellAt(pos) instanceof noCandy))
.toList();
}
public Set<List<Position>> findAllMatches(Board<Candy> board){
List<List<Position>> allMatches = Stream.concat(horizontalStartingPositions(board), verticalStartingPositions(board))
.flatMap(p -> {
List<Position> horizontalMatch = longestMatchToRight(p, board);
List<Position> verticalMatch = longestMatchDown(p, board);
return Stream.of(horizontalMatch, verticalMatch);
})
.filter(m -> m.size() > 2)
.sorted((match1, match2) -> match2.size() - match1.size())
.toList();
return allMatches.stream()
.filter(match -> allMatches.stream()
.noneMatch(longerMatch -> longerMatch.size() > match.size() && new HashSet<>(longerMatch).containsAll(match)))
.collect(Collectors.toSet());
}
public void clearMatch(List<Position> match, Board<Candy> board){
List<Position> copy = new ArrayList<>(match); // Match is immutable dus maak een copy
if(copy.isEmpty()) return;
Position first = copy.getFirst();
board.replaceCellAt(first, new noCandy());
copy.removeFirst();
score++;
clearMatch(copy, board);
}
public void fallDownTo(List<Position> match, Board<Candy> board){
if(horizontalMatch(match)){
match.forEach(position -> fallDownTo(position, board));
} else {
match.stream()
.max(Comparator.comparingInt(Position::rij)).ifPresent(position -> fallDownTo(position, board));
}
}
public void fallDownTo(Position pos, Board<Candy> board){
try{
Position boven = new Position(pos.rij() - 1, pos.kolom(), boardSize);
if(board.getCellAt(pos) instanceof noCandy){
while (board.getCellAt(boven) instanceof noCandy){
boven = new Position(boven.rij() - 1, boven.kolom(), boardSize);
}
board.replaceCellAt(pos, board.getCellAt(boven));
board.replaceCellAt(boven, new noCandy());
fallDownTo(pos, board);
} else{
fallDownTo(boven, board);
}
} catch (IllegalArgumentException ignored){return;}
}
public boolean horizontalMatch(List<Position> match){
return match.getFirst().rij() == match.getLast().rij();
}
public boolean updateBoard(Board<Candy> board){
Set<List<Position>> matches = findAllMatches(board);
if (matches.isEmpty()) return false;
for(List<Position> match : matches){
clearMatch(match, board);
fallDownTo(match, board);
}
updateBoard(board);
return true;
}
public void swapCandies(Position pos1, Position pos2, Board<Candy> board){
if(!pos1.isNeighbor(pos2) || !matchAfterSwitch(pos1, pos2, board)){
return;
}
if(board.getCellAt(pos1) instanceof noCandy || board.getCellAt(pos2) instanceof noCandy){
return;
}
unsafeSwap(pos1, pos2, board);
updateBoard(board);
}
private void unsafeSwap(Position pos1, Position pos2, Board<Candy> board){
Candy candy1 = board.getCellAt(pos1);
Candy candy2 = board.getCellAt(pos2);
board.replaceCellAt(pos1, candy2);
board.replaceCellAt(pos2, candy1);
}
public boolean matchAfterSwitch(Position pos1, Position pos2, Board<Candy> board){
unsafeSwap(pos1, pos2, board);
Set<List<Position>> matches = findAllMatches(board);
unsafeSwap(pos1, pos2, board);
return !matches.isEmpty();
}
private Set<List<Position>> getAllSwaps(Board<Candy> board){
Set<List<Position>> swaps = new HashSet<>();
for (Position position : board.getBoardSize().positions()){
Iterable<Position> neighbours = position.neighborPositions();
for(Position neighbour : neighbours){
if(!matchAfterSwitch(neighbour, position, board)){
continue;
}
if(board.getCellAt(position) instanceof noCandy || board.getCellAt(neighbour) instanceof noCandy){
continue;
}
List<Position> swap = Arrays.asList(position, neighbour);
// Verwijderd duplicaten<SUF>
// r1c2-r1c3 == r1c3-r1c2
List<Position> reverseSwap = Arrays.asList(neighbour, position);
if(swaps.contains(swap) || swaps.contains(reverseSwap)){
continue;
}
swaps.add(swap);
}
}
return swaps;
}
public Solution maximizeScore(){
List<List<Position>> moves = new ArrayList<>();
Solution intialSolution = new Solution(0,candyBoard, moves);
return findOptimalSolution(intialSolution, null);
}
private Solution findOptimalSolution(Solution partialSolution, Solution bestSoFar){
Set<List<Position>> swaps = getAllSwaps(partialSolution.board());
if(swaps.isEmpty()){
System.out.println(partialSolution.score());
System.out.println(partialSolution.calculateScore());
System.out.println("*-*");
if (bestSoFar == null || partialSolution.isBetterThan(bestSoFar)) {
return partialSolution;
} else {
return bestSoFar;
}
}
if(bestSoFar != null && partialSolution.canImproveUpon(bestSoFar)){
return bestSoFar;
}
for(List<Position> swap : swaps){
Board<Candy> mutableBoard = new Board<>(partialSolution.board().getBoardSize());
partialSolution.board().copyTo(mutableBoard);
swapCandies(swap.getFirst(), swap.getLast(), mutableBoard);
List<List<Position>> newMoves = new ArrayList<>(partialSolution.moves());
newMoves.add(swap);
Solution solution = new Solution(0, mutableBoard, newMoves);
int score = solution.calculateScore();
bestSoFar = findOptimalSolution(new Solution(score, mutableBoard, newMoves), bestSoFar);
}
return bestSoFar;
}
public Collection<Solution> solveAll(){
List<List<Position>> moves = new ArrayList<>();
Solution intialSolution = new Solution(0,candyBoard, moves);
ArrayList<Solution> collection = new ArrayList<>();
return findAllSolutions(intialSolution, collection);
}
private Collection<Solution> findAllSolutions(Solution partialSolution, Collection<Solution> solutionsSoFar){
Set<List<Position>> swaps = getAllSwaps(partialSolution.board());
if(swaps.isEmpty()){
System.out.println("Oplossing gevonden B)");
int score = partialSolution.calculateScore();
Solution solution = new Solution(score, partialSolution.board(), partialSolution.moves());
solution.printSolution();
solutionsSoFar.add(solution);
return solutionsSoFar;
}
for(List<Position> swap : swaps){
Board<Candy> mutableBoard = new Board<>(partialSolution.board().getBoardSize());
partialSolution.board().copyTo(mutableBoard);
swapCandies(swap.getFirst(), swap.getLast(), mutableBoard);
List<List<Position>> newMoves = new ArrayList<>(partialSolution.moves());
newMoves.add(swap);
findAllSolutions(new Solution(0, mutableBoard, newMoves), solutionsSoFar);
}
return solutionsSoFar;
}
public Solution solveAny(){
Solution intialSolution = new Solution(0,candyBoard, null);
return findAnySolution(intialSolution);
}
private Solution findAnySolution(Solution partialSolution){
Set<List<Position>> swaps = getAllSwaps(partialSolution.board());
if(swaps.isEmpty()) return partialSolution; // Current.isComplete()
for (List<Position> swap : swaps){
// SWAP
// 1. copy board vanuit record
// 2. swapcandies en update
// 3. maak partialSolution
// 4. recursie
Board<Candy> mutableBoard = new Board<>(partialSolution.board().getBoardSize());
partialSolution.board().copyTo(mutableBoard);
swapCandies(swap.getFirst(), swap.getLast(), mutableBoard);
int score = this.getScore();
return findAnySolution(new Solution(score, mutableBoard, null));
}
return null;
}
} |
33045_5 | package data;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Random;
import model.lessenrooster.Dag;
import model.lessenrooster.Student;
import model.locatie.Locatie;
public class DataGenerator {
private static final int aantal_dagen = 42;
private static int aantal_studenten = 50;
private static final int aantal_lessen = 10;
private static final int aantal_locaties = 50;
private static final boolean weekends = false;
static Random random = new Random();
private static Calendar getCalendar(int uur, int minuten, Calendar dag) {
dag.set(Calendar.HOUR_OF_DAY, uur);
dag.set(Calendar.MINUTE, minuten);
return dag;
}
public static ArrayList<Dag> maakRooster() {
ArrayList<Dag> rooster = new ArrayList<Dag>();
Calendar cal = Calendar.getInstance();
for (int i = 0; i <= aantal_dagen; i++) {
cal.add(Calendar.DAY_OF_MONTH, 1); // Altijd 1 dag er bij
if (!(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY && cal
.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) || weekends) { // in weekend geenles
if (random.nextInt(5) >2) { // 2op5 kans dat je les hebt
Dag dag = new Dag((Calendar)cal.clone());
for (int l = 1; l <= aantal_lessen; l++) {
if (random.nextInt(5) > 1) { // 3op5 kans dat je op dat uur les hebt
dag.voegLesToe(
getCalendar(l + 7, 0,(Calendar) dag.getDatum().clone()),
getCalendar(l + 8, 0,(Calendar) dag.getDatum().clone()));
}
}
rooster.add(dag);
}
}
}
return rooster;
}
public static ArrayList<Student> maakStudenten() {
ArrayList<Student> studenten = new ArrayList<Student>();
for (int i = 0; i < aantal_studenten; i++) {
Student student = new Student("KdG" + i);
student.setLesdagen(maakRooster());
studenten.add(student);
}
return studenten;
}
public static ArrayList<Locatie> maakLocaties() {
ArrayList<Locatie> locaties = new ArrayList<Locatie>();
for (int i = 0; i < aantal_locaties; i++) {
Locatie locatie = new Locatie("Lokaal", "GR" + i+1,
random.nextInt(200) + 20);
locatie.setDagen(maakLocatiesSlots());
locaties.add(locatie);
}
return locaties;
}
public static ArrayList<model.locatie.Dag> maakLocatiesSlots() {
ArrayList<model.locatie.Dag> rooster = new ArrayList<model.locatie.Dag>();
Calendar cal = Calendar.getInstance();
for (int i = 0; i <= aantal_dagen; i++) {
cal.add(Calendar.DAY_OF_MONTH, 1); // Altijd 1 dag er bij
model.locatie.Dag dag = new model.locatie.Dag((Calendar)cal.clone());
//System.out.println(dag.getDatum().getTime());
for (int s=0; s<dag.getSlots().size(); s++){ //Hoeveelste slot van de dag
//System.out.println("StartSlot:" + s);
if (random.nextInt(3) > 0){ //2op3kans dat het lokaal op dat slot bezet is
int aantal = random.nextInt(7) + 4; //Minimaal les van 1 uur (4 slots), maximum 2.5 uur);
for (int j = 0; j < aantal; j++){
try{
dag.getSlots().get(s + j).setBezet(true);
//System.out.println("Slot:" + (s + j) + " is bezet");
} catch (IndexOutOfBoundsException ie){
//Einde van slotlijst bereikt
}
}
s += aantal; //Volgend slot om te beginnen in loop is ten vroegste kwartier later dan eind vorige les
}
}
//System.out.println();
rooster.add(dag);
}
return rooster;
}
}
| MathiasVandePol/ws-eventmanagementsystem | src/data/DataGenerator.java | 1,316 | //Hoeveelste slot van de dag
| line_comment | nl | package data;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Random;
import model.lessenrooster.Dag;
import model.lessenrooster.Student;
import model.locatie.Locatie;
public class DataGenerator {
private static final int aantal_dagen = 42;
private static int aantal_studenten = 50;
private static final int aantal_lessen = 10;
private static final int aantal_locaties = 50;
private static final boolean weekends = false;
static Random random = new Random();
private static Calendar getCalendar(int uur, int minuten, Calendar dag) {
dag.set(Calendar.HOUR_OF_DAY, uur);
dag.set(Calendar.MINUTE, minuten);
return dag;
}
public static ArrayList<Dag> maakRooster() {
ArrayList<Dag> rooster = new ArrayList<Dag>();
Calendar cal = Calendar.getInstance();
for (int i = 0; i <= aantal_dagen; i++) {
cal.add(Calendar.DAY_OF_MONTH, 1); // Altijd 1 dag er bij
if (!(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY && cal
.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) || weekends) { // in weekend geenles
if (random.nextInt(5) >2) { // 2op5 kans dat je les hebt
Dag dag = new Dag((Calendar)cal.clone());
for (int l = 1; l <= aantal_lessen; l++) {
if (random.nextInt(5) > 1) { // 3op5 kans dat je op dat uur les hebt
dag.voegLesToe(
getCalendar(l + 7, 0,(Calendar) dag.getDatum().clone()),
getCalendar(l + 8, 0,(Calendar) dag.getDatum().clone()));
}
}
rooster.add(dag);
}
}
}
return rooster;
}
public static ArrayList<Student> maakStudenten() {
ArrayList<Student> studenten = new ArrayList<Student>();
for (int i = 0; i < aantal_studenten; i++) {
Student student = new Student("KdG" + i);
student.setLesdagen(maakRooster());
studenten.add(student);
}
return studenten;
}
public static ArrayList<Locatie> maakLocaties() {
ArrayList<Locatie> locaties = new ArrayList<Locatie>();
for (int i = 0; i < aantal_locaties; i++) {
Locatie locatie = new Locatie("Lokaal", "GR" + i+1,
random.nextInt(200) + 20);
locatie.setDagen(maakLocatiesSlots());
locaties.add(locatie);
}
return locaties;
}
public static ArrayList<model.locatie.Dag> maakLocatiesSlots() {
ArrayList<model.locatie.Dag> rooster = new ArrayList<model.locatie.Dag>();
Calendar cal = Calendar.getInstance();
for (int i = 0; i <= aantal_dagen; i++) {
cal.add(Calendar.DAY_OF_MONTH, 1); // Altijd 1 dag er bij
model.locatie.Dag dag = new model.locatie.Dag((Calendar)cal.clone());
//System.out.println(dag.getDatum().getTime());
for (int s=0; s<dag.getSlots().size(); s++){ //Hoeveelste slot<SUF>
//System.out.println("StartSlot:" + s);
if (random.nextInt(3) > 0){ //2op3kans dat het lokaal op dat slot bezet is
int aantal = random.nextInt(7) + 4; //Minimaal les van 1 uur (4 slots), maximum 2.5 uur);
for (int j = 0; j < aantal; j++){
try{
dag.getSlots().get(s + j).setBezet(true);
//System.out.println("Slot:" + (s + j) + " is bezet");
} catch (IndexOutOfBoundsException ie){
//Einde van slotlijst bereikt
}
}
s += aantal; //Volgend slot om te beginnen in loop is ten vroegste kwartier later dan eind vorige les
}
}
//System.out.println();
rooster.add(dag);
}
return rooster;
}
}
|
84006_2 | package com.marbl.warehouse.domain;
import java.io.Serializable;
public class Onderdeel implements Serializable {
/**
* De code van het onderdeel.
*/
private int code;
/**
* De omschrijving van het onderdeel.
*/
private String omschrijving;
/**
* Het aantal van het onderdeel.
*/
private int aantal;
/**
* De prijs van het object in centen.
*/
private int prijs;
/**
* Creert een nieuw onderdeel-object met de parameters.
*
* @param code De code van het onderdeel.
* @param omschrijving De omschrijving van het onderdeel.
* @param aantal Het aantal van het onderdeel.
* @param prijs De prijs van het onderdeel in centen.
*/
public Onderdeel(int code, String omschrijving, int aantal, int prijs) {
this.code = code;
this.omschrijving = omschrijving;
this.aantal = aantal;
this.prijs = prijs;
}
/**
* Geeft de code van het desbetreffende Onderdeel-object.
*
* @return De code van het desbetreffende Onderdeel-object.
*/
public int getCode() {
return this.code;
}
/**
* Geeft de omschrijving van het desbetreffende Onderdeel-object.
*
* @return De omschrijving van het desbetreffende Onderdeel-object.
*/
public String getOmschrijving() {
return this.omschrijving;
}
/**
* Geeft het aantal van het desbetreffende Onderdeel-object.
*
* @return Het aantal van het desbetreffende Onderdeel-object.
*/
public int getAantal() {
return this.aantal;
}
/**
* Geeft de prijs van het desbetreffende Onderdeel-object.
*
* @return De prijs van het desbetreffende Onderdeel-object.
*/
public int getPrijs() {
return this.prijs;
}
/**
* Set het aantal van het desbetreffende Onderdeel-object.
*
* @param aantal De nieuwe waarde voor het aantal van het onderdeel-object.
*/
public void setAantal(int aantal) {
this.aantal = aantal;
}
}
| MathijsStertefeld/Parafiksit | ParafiksitDomain/src/main/java/com/marbl/warehouse/domain/Onderdeel.java | 700 | /**
* Het aantal van het onderdeel.
*/ | block_comment | nl | package com.marbl.warehouse.domain;
import java.io.Serializable;
public class Onderdeel implements Serializable {
/**
* De code van het onderdeel.
*/
private int code;
/**
* De omschrijving van het onderdeel.
*/
private String omschrijving;
/**
* Het aantal van<SUF>*/
private int aantal;
/**
* De prijs van het object in centen.
*/
private int prijs;
/**
* Creert een nieuw onderdeel-object met de parameters.
*
* @param code De code van het onderdeel.
* @param omschrijving De omschrijving van het onderdeel.
* @param aantal Het aantal van het onderdeel.
* @param prijs De prijs van het onderdeel in centen.
*/
public Onderdeel(int code, String omschrijving, int aantal, int prijs) {
this.code = code;
this.omschrijving = omschrijving;
this.aantal = aantal;
this.prijs = prijs;
}
/**
* Geeft de code van het desbetreffende Onderdeel-object.
*
* @return De code van het desbetreffende Onderdeel-object.
*/
public int getCode() {
return this.code;
}
/**
* Geeft de omschrijving van het desbetreffende Onderdeel-object.
*
* @return De omschrijving van het desbetreffende Onderdeel-object.
*/
public String getOmschrijving() {
return this.omschrijving;
}
/**
* Geeft het aantal van het desbetreffende Onderdeel-object.
*
* @return Het aantal van het desbetreffende Onderdeel-object.
*/
public int getAantal() {
return this.aantal;
}
/**
* Geeft de prijs van het desbetreffende Onderdeel-object.
*
* @return De prijs van het desbetreffende Onderdeel-object.
*/
public int getPrijs() {
return this.prijs;
}
/**
* Set het aantal van het desbetreffende Onderdeel-object.
*
* @param aantal De nieuwe waarde voor het aantal van het onderdeel-object.
*/
public void setAantal(int aantal) {
this.aantal = aantal;
}
}
|
131566_7 | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 ~ 2010 Patrick Huy <[email protected]>
Matthias Butz <[email protected]>
Jan Christian Meyer <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation. You may not use, modify
or distribute this program under any other version of the
GNU Affero General Public License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package server.life;
import config.YamlConfig;
import constants.inventory.ItemConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import provider.Data;
import provider.DataProvider;
import provider.DataProviderFactory;
import provider.DataTool;
import provider.wz.WZFiles;
import server.ItemInformationProvider;
import tools.DatabaseConnection;
import tools.Pair;
import tools.Randomizer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
public class MonsterInformationProvider {
private static final Logger log = LoggerFactory.getLogger(MonsterInformationProvider.class);
// Author : LightPepsi
private static final MonsterInformationProvider instance = new MonsterInformationProvider();
public static MonsterInformationProvider getInstance() {
return instance;
}
private final Map<Integer, List<MonsterDropEntry>> drops = new HashMap<>();
private final List<MonsterGlobalDropEntry> globaldrops = new ArrayList<>();
private final Map<Integer, List<MonsterGlobalDropEntry>> continentdrops = new HashMap<>();
private final Map<Integer, List<Integer>> dropsChancePool = new HashMap<>(); // thanks to ronan
private final Set<Integer> hasNoMultiEquipDrops = new HashSet<>();
private final Map<Integer, List<MonsterDropEntry>> extraMultiEquipDrops = new HashMap<>();
private final Map<Pair<Integer, Integer>, Integer> mobAttackAnimationTime = new HashMap<>();
private final Map<MobSkill, Integer> mobSkillAnimationTime = new HashMap<>();
private final Map<Integer, Pair<Integer, Integer>> mobAttackInfo = new HashMap<>();
private final Map<Integer, Boolean> mobBossCache = new HashMap<>();
private final Map<Integer, String> mobNameCache = new HashMap<>();
protected MonsterInformationProvider() {
retrieveGlobal();
}
public final List<MonsterGlobalDropEntry> getRelevantGlobalDrops(int mapid) {
int continentid = mapid / 100000000;
List<MonsterGlobalDropEntry> contiItems = continentdrops.get(continentid);
if (contiItems == null) { // continent separated global drops found thanks to marcuswoon
contiItems = new ArrayList<>();
for (MonsterGlobalDropEntry e : globaldrops) {
if (e.continentid < 0 || e.continentid == continentid) {
contiItems.add(e);
}
}
continentdrops.put(continentid, contiItems);
}
return contiItems;
}
private void retrieveGlobal() {
try (Connection con = DatabaseConnection.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT * FROM drop_data_global WHERE chance > 0");
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
globaldrops.add(new MonsterGlobalDropEntry(
rs.getInt("itemid"),
rs.getInt("chance"),
rs.getByte("continent"),
rs.getInt("minimum_quantity"),
rs.getInt("maximum_quantity"),
rs.getShort("questid")));
}
} catch (SQLException e) {
log.error("Error retrieving global drops", e);
}
}
public List<MonsterDropEntry> retrieveEffectiveDrop(final int monsterId) {
// this reads the drop entries searching for multi-equip, properly processing them
List<MonsterDropEntry> list = retrieveDrop(monsterId);
if (hasNoMultiEquipDrops.contains(monsterId) || !YamlConfig.config.server.USE_MULTIPLE_SAME_EQUIP_DROP) {
return list;
}
List<MonsterDropEntry> multiDrops = extraMultiEquipDrops.get(monsterId), extra = new LinkedList<>();
if (multiDrops == null) {
multiDrops = new LinkedList<>();
for (MonsterDropEntry mde : list) {
if (ItemConstants.isEquipment(mde.itemId) && mde.Maximum > 1) {
multiDrops.add(mde);
int rnd = Randomizer.rand(mde.Minimum, mde.Maximum);
for (int i = 0; i < rnd - 1; i++) {
extra.add(mde); // this passes copies of the equips' MDE with min/max quantity > 1, but idc on equips they are unused anyways
}
}
}
if (!multiDrops.isEmpty()) {
extraMultiEquipDrops.put(monsterId, multiDrops);
} else {
hasNoMultiEquipDrops.add(monsterId);
}
} else {
for (MonsterDropEntry mde : multiDrops) {
int rnd = Randomizer.rand(mde.Minimum, mde.Maximum);
for (int i = 0; i < rnd - 1; i++) {
extra.add(mde);
}
}
}
List<MonsterDropEntry> ret = new LinkedList<>(list);
ret.addAll(extra);
return ret;
}
public final List<MonsterDropEntry> retrieveDrop(final int monsterId) {
if (drops.containsKey(monsterId)) {
return drops.get(monsterId);
}
final List<MonsterDropEntry> ret = new LinkedList<>();
try (Connection con = DatabaseConnection.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT itemid, chance, minimum_quantity, maximum_quantity, questid FROM drop_data WHERE dropperid = ?")) {
ps.setInt(1, monsterId);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
ret.add(new MonsterDropEntry(rs.getInt("itemid"), rs.getInt("chance"), rs.getInt("minimum_quantity"), rs.getInt("maximum_quantity"), rs.getShort("questid")));
}
}
} catch (SQLException e) {
e.printStackTrace();
return ret;
}
drops.put(monsterId, ret);
return ret;
}
public final List<Integer> retrieveDropPool(final int monsterId) { // ignores Quest and Party Quest items
if (dropsChancePool.containsKey(monsterId)) {
return dropsChancePool.get(monsterId);
}
ItemInformationProvider ii = ItemInformationProvider.getInstance();
List<MonsterDropEntry> dropList = retrieveDrop(monsterId);
List<Integer> ret = new ArrayList<>();
int accProp = 0;
for (MonsterDropEntry mde : dropList) {
if (!ii.isQuestItem(mde.itemId) && !ii.isPartyQuestItem(mde.itemId)) {
accProp += mde.chance;
}
ret.add(accProp);
}
if (accProp == 0) {
ret.clear(); // don't accept mobs dropping no relevant items
}
dropsChancePool.put(monsterId, ret);
return ret;
}
public final void setMobAttackAnimationTime(int monsterId, int attackPos, int animationTime) {
mobAttackAnimationTime.put(new Pair<>(monsterId, attackPos), animationTime);
}
public final Integer getMobAttackAnimationTime(int monsterId, int attackPos) {
Integer time = mobAttackAnimationTime.get(new Pair<>(monsterId, attackPos));
return time == null ? 0 : time;
}
public final void setMobSkillAnimationTime(MobSkill skill, int animationTime) {
mobSkillAnimationTime.put(skill, animationTime);
}
public final Integer getMobSkillAnimationTime(MobSkill skill) {
Integer time = mobSkillAnimationTime.get(skill);
return time == null ? 0 : time;
}
public final void setMobAttackInfo(int monsterId, int attackPos, int mpCon, int coolTime) {
mobAttackInfo.put((monsterId << 3) + attackPos, new Pair<>(mpCon, coolTime));
}
public final Pair<Integer, Integer> getMobAttackInfo(int monsterId, int attackPos) {
if (attackPos < 0 || attackPos > 7) {
return null;
}
return mobAttackInfo.get((monsterId << 3) + attackPos);
}
public static ArrayList<Pair<Integer, String>> getMobsIDsFromName(String search) {
DataProvider dataProvider = DataProviderFactory.getDataProvider(WZFiles.STRING);
ArrayList<Pair<Integer, String>> retMobs = new ArrayList<>();
Data data = dataProvider.getData("Mob.img");
List<Pair<Integer, String>> mobPairList = new LinkedList<>();
for (Data mobIdData : data.getChildren()) {
int mobIdFromData = Integer.parseInt(mobIdData.getName());
String mobNameFromData = DataTool.getString(mobIdData.getChildByPath("name"), "NO-NAME");
mobPairList.add(new Pair<>(mobIdFromData, mobNameFromData));
}
for (Pair<Integer, String> mobPair : mobPairList) {
if (mobPair.getRight().toLowerCase().contains(search.toLowerCase())) {
retMobs.add(mobPair);
}
}
return retMobs;
}
public boolean isBoss(int id) {
Boolean boss = mobBossCache.get(id);
if (boss == null) {
try {
boss = LifeFactory.getMonster(id).isBoss();
} catch (NullPointerException npe) {
boss = false;
} catch (Exception e) { //nonexistant mob
boss = false;
log.warn("Non-existent mob id {}", id, e);
}
mobBossCache.put(id, boss);
}
return boss;
}
public String getMobNameFromId(int id) {
String mobName = mobNameCache.get(id);
if (mobName == null) {
DataProvider dataProvider = DataProviderFactory.getDataProvider(WZFiles.STRING);
Data mobData = dataProvider.getData("Mob.img");
mobName = DataTool.getString(mobData.getChildByPath(id + "/name"), "");
mobNameCache.put(id, mobName);
}
return mobName;
}
public final void clearDrops() {
drops.clear();
hasNoMultiEquipDrops.clear();
extraMultiEquipDrops.clear();
dropsChancePool.clear();
globaldrops.clear();
continentdrops.clear();
retrieveGlobal();
}
}
| MatthewHinds/Cosmic | src/main/java/server/life/MonsterInformationProvider.java | 3,152 | // don't accept mobs dropping no relevant items | line_comment | nl | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 ~ 2010 Patrick Huy <[email protected]>
Matthias Butz <[email protected]>
Jan Christian Meyer <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation. You may not use, modify
or distribute this program under any other version of the
GNU Affero General Public License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package server.life;
import config.YamlConfig;
import constants.inventory.ItemConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import provider.Data;
import provider.DataProvider;
import provider.DataProviderFactory;
import provider.DataTool;
import provider.wz.WZFiles;
import server.ItemInformationProvider;
import tools.DatabaseConnection;
import tools.Pair;
import tools.Randomizer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
public class MonsterInformationProvider {
private static final Logger log = LoggerFactory.getLogger(MonsterInformationProvider.class);
// Author : LightPepsi
private static final MonsterInformationProvider instance = new MonsterInformationProvider();
public static MonsterInformationProvider getInstance() {
return instance;
}
private final Map<Integer, List<MonsterDropEntry>> drops = new HashMap<>();
private final List<MonsterGlobalDropEntry> globaldrops = new ArrayList<>();
private final Map<Integer, List<MonsterGlobalDropEntry>> continentdrops = new HashMap<>();
private final Map<Integer, List<Integer>> dropsChancePool = new HashMap<>(); // thanks to ronan
private final Set<Integer> hasNoMultiEquipDrops = new HashSet<>();
private final Map<Integer, List<MonsterDropEntry>> extraMultiEquipDrops = new HashMap<>();
private final Map<Pair<Integer, Integer>, Integer> mobAttackAnimationTime = new HashMap<>();
private final Map<MobSkill, Integer> mobSkillAnimationTime = new HashMap<>();
private final Map<Integer, Pair<Integer, Integer>> mobAttackInfo = new HashMap<>();
private final Map<Integer, Boolean> mobBossCache = new HashMap<>();
private final Map<Integer, String> mobNameCache = new HashMap<>();
protected MonsterInformationProvider() {
retrieveGlobal();
}
public final List<MonsterGlobalDropEntry> getRelevantGlobalDrops(int mapid) {
int continentid = mapid / 100000000;
List<MonsterGlobalDropEntry> contiItems = continentdrops.get(continentid);
if (contiItems == null) { // continent separated global drops found thanks to marcuswoon
contiItems = new ArrayList<>();
for (MonsterGlobalDropEntry e : globaldrops) {
if (e.continentid < 0 || e.continentid == continentid) {
contiItems.add(e);
}
}
continentdrops.put(continentid, contiItems);
}
return contiItems;
}
private void retrieveGlobal() {
try (Connection con = DatabaseConnection.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT * FROM drop_data_global WHERE chance > 0");
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
globaldrops.add(new MonsterGlobalDropEntry(
rs.getInt("itemid"),
rs.getInt("chance"),
rs.getByte("continent"),
rs.getInt("minimum_quantity"),
rs.getInt("maximum_quantity"),
rs.getShort("questid")));
}
} catch (SQLException e) {
log.error("Error retrieving global drops", e);
}
}
public List<MonsterDropEntry> retrieveEffectiveDrop(final int monsterId) {
// this reads the drop entries searching for multi-equip, properly processing them
List<MonsterDropEntry> list = retrieveDrop(monsterId);
if (hasNoMultiEquipDrops.contains(monsterId) || !YamlConfig.config.server.USE_MULTIPLE_SAME_EQUIP_DROP) {
return list;
}
List<MonsterDropEntry> multiDrops = extraMultiEquipDrops.get(monsterId), extra = new LinkedList<>();
if (multiDrops == null) {
multiDrops = new LinkedList<>();
for (MonsterDropEntry mde : list) {
if (ItemConstants.isEquipment(mde.itemId) && mde.Maximum > 1) {
multiDrops.add(mde);
int rnd = Randomizer.rand(mde.Minimum, mde.Maximum);
for (int i = 0; i < rnd - 1; i++) {
extra.add(mde); // this passes copies of the equips' MDE with min/max quantity > 1, but idc on equips they are unused anyways
}
}
}
if (!multiDrops.isEmpty()) {
extraMultiEquipDrops.put(monsterId, multiDrops);
} else {
hasNoMultiEquipDrops.add(monsterId);
}
} else {
for (MonsterDropEntry mde : multiDrops) {
int rnd = Randomizer.rand(mde.Minimum, mde.Maximum);
for (int i = 0; i < rnd - 1; i++) {
extra.add(mde);
}
}
}
List<MonsterDropEntry> ret = new LinkedList<>(list);
ret.addAll(extra);
return ret;
}
public final List<MonsterDropEntry> retrieveDrop(final int monsterId) {
if (drops.containsKey(monsterId)) {
return drops.get(monsterId);
}
final List<MonsterDropEntry> ret = new LinkedList<>();
try (Connection con = DatabaseConnection.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT itemid, chance, minimum_quantity, maximum_quantity, questid FROM drop_data WHERE dropperid = ?")) {
ps.setInt(1, monsterId);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
ret.add(new MonsterDropEntry(rs.getInt("itemid"), rs.getInt("chance"), rs.getInt("minimum_quantity"), rs.getInt("maximum_quantity"), rs.getShort("questid")));
}
}
} catch (SQLException e) {
e.printStackTrace();
return ret;
}
drops.put(monsterId, ret);
return ret;
}
public final List<Integer> retrieveDropPool(final int monsterId) { // ignores Quest and Party Quest items
if (dropsChancePool.containsKey(monsterId)) {
return dropsChancePool.get(monsterId);
}
ItemInformationProvider ii = ItemInformationProvider.getInstance();
List<MonsterDropEntry> dropList = retrieveDrop(monsterId);
List<Integer> ret = new ArrayList<>();
int accProp = 0;
for (MonsterDropEntry mde : dropList) {
if (!ii.isQuestItem(mde.itemId) && !ii.isPartyQuestItem(mde.itemId)) {
accProp += mde.chance;
}
ret.add(accProp);
}
if (accProp == 0) {
ret.clear(); // don't accept<SUF>
}
dropsChancePool.put(monsterId, ret);
return ret;
}
public final void setMobAttackAnimationTime(int monsterId, int attackPos, int animationTime) {
mobAttackAnimationTime.put(new Pair<>(monsterId, attackPos), animationTime);
}
public final Integer getMobAttackAnimationTime(int monsterId, int attackPos) {
Integer time = mobAttackAnimationTime.get(new Pair<>(monsterId, attackPos));
return time == null ? 0 : time;
}
public final void setMobSkillAnimationTime(MobSkill skill, int animationTime) {
mobSkillAnimationTime.put(skill, animationTime);
}
public final Integer getMobSkillAnimationTime(MobSkill skill) {
Integer time = mobSkillAnimationTime.get(skill);
return time == null ? 0 : time;
}
public final void setMobAttackInfo(int monsterId, int attackPos, int mpCon, int coolTime) {
mobAttackInfo.put((monsterId << 3) + attackPos, new Pair<>(mpCon, coolTime));
}
public final Pair<Integer, Integer> getMobAttackInfo(int monsterId, int attackPos) {
if (attackPos < 0 || attackPos > 7) {
return null;
}
return mobAttackInfo.get((monsterId << 3) + attackPos);
}
public static ArrayList<Pair<Integer, String>> getMobsIDsFromName(String search) {
DataProvider dataProvider = DataProviderFactory.getDataProvider(WZFiles.STRING);
ArrayList<Pair<Integer, String>> retMobs = new ArrayList<>();
Data data = dataProvider.getData("Mob.img");
List<Pair<Integer, String>> mobPairList = new LinkedList<>();
for (Data mobIdData : data.getChildren()) {
int mobIdFromData = Integer.parseInt(mobIdData.getName());
String mobNameFromData = DataTool.getString(mobIdData.getChildByPath("name"), "NO-NAME");
mobPairList.add(new Pair<>(mobIdFromData, mobNameFromData));
}
for (Pair<Integer, String> mobPair : mobPairList) {
if (mobPair.getRight().toLowerCase().contains(search.toLowerCase())) {
retMobs.add(mobPair);
}
}
return retMobs;
}
public boolean isBoss(int id) {
Boolean boss = mobBossCache.get(id);
if (boss == null) {
try {
boss = LifeFactory.getMonster(id).isBoss();
} catch (NullPointerException npe) {
boss = false;
} catch (Exception e) { //nonexistant mob
boss = false;
log.warn("Non-existent mob id {}", id, e);
}
mobBossCache.put(id, boss);
}
return boss;
}
public String getMobNameFromId(int id) {
String mobName = mobNameCache.get(id);
if (mobName == null) {
DataProvider dataProvider = DataProviderFactory.getDataProvider(WZFiles.STRING);
Data mobData = dataProvider.getData("Mob.img");
mobName = DataTool.getString(mobData.getChildByPath(id + "/name"), "");
mobNameCache.put(id, mobName);
}
return mobName;
}
public final void clearDrops() {
drops.clear();
hasNoMultiEquipDrops.clear();
extraMultiEquipDrops.clear();
dropsChancePool.clear();
globaldrops.clear();
continentdrops.clear();
retrieveGlobal();
}
}
|
15339_17 | /**
* @Autor: Matthias Somay & Kenneth Van De Borne
* @Date: 15/12/2018
* @Project: Examen_Java_2019
* @Purpose: Controller klasse JavaFX
*/
package controller;
import db.DatabaseQueries;
import factory.HulpdienstFactory;
import factory.SchipFactory;
import factory.VerkeerstorenFactory;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Circle;
import model.*;
import utilities.demodata.HulpdienstTypeLijst;
import utilities.demodata.SchipTypeLijst;
import utilities.demodata.VerkeerstorenTypeLijst;
import utilities.generator.Generator;
import utilities.states.InNood;
public class MainWindowController {
SchipTypeLijst schipTypeLijst = new SchipTypeLijst();
HulpdienstTypeLijst hulpdienstTypeLijst = new HulpdienstTypeLijst();
VerkeerstorenTypeLijst verkeerstorenTypeLijst = new VerkeerstorenTypeLijst();
DatabaseQueries db = new DatabaseQueries();
Generator generator = new Generator();
@FXML private Pane mapDisplay;
@FXML private ListView<Actor> listData;
@FXML private Button toonAlleVerkeerstorens;
@FXML private Button toonAllehulpdiensten;
@FXML private Button toonAlleSchepen;
@FXML private Button toonAlles;
@FXML private Label labelSnelheid;
@FXML private Label labelKoers;
@FXML private Label labelPersonenAanBoord;
@FXML private Label labelWendbaarheid;
@FXML private TextField ID;
@FXML private TextField locatieLengte;
@FXML private TextField locatieBreedte;
@FXML private TextField snelheid;
@FXML private TextField wendbaarheid;
@FXML private TextField grootte;
@FXML private TextField personenAanboord;
@FXML private TextField koers;
@FXML private ComboBox<String> detailType;
@FXML private Label labelGrootte;
@FXML private Label labelStatus;
@FXML private Label labelZeemijlUur;
@FXML private Label labelSecondeGraad;
@FXML private Label labelM;
@FXML private Label labelGradenTovNoorden;
@FXML private ComboBox<String> status;
@FXML private ComboBox<String> hoofdType;
@FXML private Button slaOp;
@FXML private Button Verwijder;
@FXML private Button maakLeeg;
@FXML private Button startRandomReddingsactie;
// maakt inputvelden leeg
@FXML
void maakLeegButtonPressed(ActionEvent event) {
clearInputBasis();
clearInputVervoermiddel();
hoofdType.setDisable(false);
detailType.setDisable(false);
}
// Creërt nieuwe actor wanneer ID veld leeg is, update actor in het andere geval
@FXML
void slaOpButtonPressed(ActionEvent event) {
if(ID.getText().equals("")){
creatieActor();
}
else{
updateActor();
}
}
// initialiseert comboboxs en schakelt het veld "ID" uit
public void initialize(){
hoofdType.getItems().addAll("Verkeerstoren", "Schip", "Hulpdienst");
status.getItems().addAll("Beschikbaar", "Niet beschikbaar", "In nood");
ID.setDisable(true);
// Method voor het vullen van de database.
/*generator.setUpRandomData(db);*/
db.refreshData();
db.print();
}
//Geeft elke actor weer op de kaart met een eigen kleur, wanneer er op een actor geklikt wordt, worden zijn eigenschappen getoond
public void drawActorOnPane(){
mapDisplay.getChildren().clear();
Paint brushColor;
Circle newCircle;
for (Actor actor: listData.getItems()
) {
if (actor.getClass() == Schip.class){
brushColor = Color.BLACK;
newCircle = new Circle(actor.getLocatie().getBreedte(), actor.getLocatie().getLengte(),5,brushColor);
}
else if (actor.getClass() == Hulpdienst.class){
brushColor = Color.BLUE;
newCircle = new Circle(actor.getLocatie().getBreedte(), actor.getLocatie().getLengte(),5,brushColor);
}
else {
brushColor = Color.RED;
newCircle = new Circle(actor.getLocatie().getBreedte(), actor.getLocatie().getLengte(),7,brushColor);
}
newCircle.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (actor.getClass() == Hulpdienst.class){
toonDataHulpdienst((Hulpdienst)actor);
}
else if (actor.getClass() == Schip.class){
toonDataSchip((Schip)actor);
}
else if (actor.getClass() == Verkeerstoren.class){
toonDataVerkeerstoren((Verkeerstoren) actor);
}
}
});
mapDisplay.getChildren().add(newCircle);
}
}
// Geeft locatie aan van de geselecteerde actor op de kaart
@FXML
void mapDisplayClicked(MouseEvent event) {
if (ID.getText().equals("")) {
locatieBreedte.setText(String.valueOf(event.getX()));
locatieLengte.setText(String.valueOf(event.getY()));
}
}
// method voor het updaten van een geselecteerde actor
public void updateActor(){
if (hoofdType.getValue() != null){
if (hoofdType.getValue() == "Verkeerstoren"){
if (checkInputBasis() == 0){
Verkeerstoren verkeerstorenTemp = null;
for (Verkeerstoren v: db.getVerkeerstorens()
) {
if (v.getId() == Integer.parseInt(ID.getText())){
verkeerstorenTemp = v;
break;
}
}
verkeerstorenTemp.getLocatie().setBreedte(Double.parseDouble(locatieBreedte.getText()));
verkeerstorenTemp.getLocatie().setLengte(Double.parseDouble(locatieLengte.getText()));
db.updateVerkeerstoren(verkeerstorenTemp);
displayAlert(Alert.AlertType.INFORMATION, "Informatie",
"Verkeerstoren is aangepast.");
}
}
else if (hoofdType.getValue() == "Schip"){
if (checkInputBasis() == 0){
if (checkInputVervoermiddel() == 0){
Schip schipTemp = null;
for (Schip s: db.getSchepen()
) {
if (s.getId() == Integer.parseInt(ID.getText())){
schipTemp = s;
break;
}
}
schipTemp.getLocatie().setBreedte(Double.parseDouble(locatieBreedte.getText()));
schipTemp.getLocatie().setLengte(Double.parseDouble(locatieLengte.getText()));
schipTemp.setSnelheid(Double.parseDouble(snelheid.getText()));
schipTemp.setGrootte(Double.parseDouble(grootte.getText()));
schipTemp.setWendbaarheid(Double.parseDouble(wendbaarheid.getText()));
schipTemp.setPersonenAanBoord(Integer.parseInt(personenAanboord.getText()));
schipTemp.setKoers(Double.parseDouble(koers.getText()));
schipTemp.setStatus(db.CalculateState(status.getValue()));
db.updateVervoermiddel(schipTemp, hoofdType.getValue());
displayAlert(Alert.AlertType.INFORMATION, "Informatie",
"Schip is aangepast.");
}
}
}
else {
if (checkInputBasis() == 0){
if (checkInputVervoermiddel() == 0){
Hulpdienst hulpdienstTemp = null;
for (Hulpdienst h: db.getHulpdiensten()
) {
if (h.getId() == Integer.parseInt(ID.getText())){
hulpdienstTemp = h;
break;
}
}
hulpdienstTemp.getLocatie().setBreedte(Double.parseDouble(locatieBreedte.getText()));
hulpdienstTemp.getLocatie().setLengte(Double.parseDouble(locatieLengte.getText()));
hulpdienstTemp.setSnelheid(Double.parseDouble(snelheid.getText()));
hulpdienstTemp.setGrootte(Double.parseDouble(grootte.getText()));
hulpdienstTemp.setWendbaarheid(Double.parseDouble(wendbaarheid.getText()));
hulpdienstTemp.setPersonenAanBoord(Integer.parseInt(personenAanboord.getText()));
hulpdienstTemp.setKoers(Double.parseDouble(koers.getText()));
hulpdienstTemp.setStatus(db.CalculateState(status.getValue()));
db.updateVervoermiddel(hulpdienstTemp, hoofdType.getValue());
displayAlert(Alert.AlertType.INFORMATION, "Informatie",
"Schip is aangepast.");
}
}
}
clearInputBasis();
clearInputVervoermiddel();
db.refreshData();
toonAlleActors();
}
else checkInputBasis();
}
// method voor de creatie van actor aan de hand van het gekozen type
public void creatieActor(){
if (hoofdType.getValue() != null){
if (hoofdType.getValue() == "Verkeerstoren"){
if (checkInputBasis() == 0){
Verkeerstoren verkeerstorenTemp = VerkeerstorenFactory.createVerkeerstoren(
new Coördinaten(Double.parseDouble(locatieLengte.getText()),Double.parseDouble(locatieBreedte.getText())),
detailType.getValue(),
db.getVerkeerstorens());
if (ID.getText().equals("")) {
db.addVerkeerstoren(verkeerstorenTemp);
displayAlert(Alert.AlertType.INFORMATION, "Informatie",
"Verkeerstoren is toegevoegd.");
}
}
}
else if (hoofdType.getValue() == "Schip"){
if (checkInputBasis() == 0){
if (checkInputVervoermiddel() == 0){
Schip schipTemp = SchipFactory.createSchip(
new Coördinaten(Double.parseDouble(locatieLengte.getText()), Double.parseDouble(locatieBreedte.getText())),
Double.parseDouble(snelheid.getText()),
Double.parseDouble(grootte.getText()),
Double.parseDouble(wendbaarheid.getText()),
Integer.parseInt(personenAanboord.getText()),
Double.parseDouble(koers.getText()),
detailType.getValue(),
db.CalculateState(status.getValue()),
db.getVerkeerstorens());
if (ID.getText().equals("")) {
db.addVervoermiddel(schipTemp, hoofdType.getValue());
displayAlert(Alert.AlertType.INFORMATION, "Informatie",
"Schip is toegevoegd.");
}
}
}
}
else {
if (checkInputBasis() == 0){
if (checkInputVervoermiddel() == 0){
Hulpdienst hulpdienstTemp = HulpdienstFactory.createHulpdienst(
new Coördinaten(Double.parseDouble(locatieLengte.getText()), Double.parseDouble(locatieBreedte.getText())),
Double.parseDouble(snelheid.getText()),
Double.parseDouble(grootte.getText()),
Double.parseDouble(wendbaarheid.getText()),
Integer.parseInt(personenAanboord.getText()),
Double.parseDouble(koers.getText()),
detailType.getValue(),
db.CalculateState(status.getValue()),
db.getVerkeerstorens());
if (ID.getText().equals("")) {
db.addVervoermiddel(hulpdienstTemp, hoofdType.getValue());
displayAlert(Alert.AlertType.INFORMATION, "Informatie",
"Hulpdienst is toegevoegd.");
}
}
}
}
clearInputBasis();
clearInputVervoermiddel();
db.refreshData();
toonAlleActors();
}
else checkInputBasis();
}
// start een reddingsactie met een random schip op de kaart
@FXML
void startRandomReddingsactieButtonPressed(ActionEvent event) {
generator.generateRandomSchip(db.getSchepen()).setStatus(new InNood());
}
// toont enkel de schepen in de lijst
@FXML
void toonAlleSchepenButtonPressed(ActionEvent event) {
listData.getItems().setAll(db.getSchepen());
drawActorOnPane();
}
// toont enkel de verkeerstorens in de lijst
@FXML
void toonAlleVerkeerstorensButttonPressed(ActionEvent event) {
listData.getItems().setAll(db.getVerkeerstorens());
drawActorOnPane();
}
// toont enkel de hulpdiensten in de lijst
@FXML
void toonAllehulpdienstenButtonPressed(ActionEvent event) {
listData.getItems().setAll(db.getHulpdiensten());
drawActorOnPane();
}
// toont alle actoren in de lijst m.b.v. toonAlleActors()
@FXML
void toonAllesButtonPressed(ActionEvent event) {
toonAlleActors();
}
// vult de lijst met alle actoren
public void toonAlleActors(){
listData.getItems().setAll(db.getVerkeerstorens());
listData.getItems().addAll(db.getHulpdiensten());
listData.getItems().addAll(db.getSchepen());
drawActorOnPane();
}
// verwijdert actor aan de hand van de gekozen actor in de lijst, lijst wordt vernieuwd na elke bewerking
@FXML
void verwijderButtonPressed(ActionEvent event) {
if (ID.getText() != null){
if (hoofdType.getSelectionModel().getSelectedItem() == "Verkeerstoren"){
db.deleteVerkeerstoren(Integer.parseInt(ID.getText()));
maakLeegButtonPressed(event);
toonAlleActors();
displayAlert(Alert.AlertType.INFORMATION, "Informatie",
"Verkeerstoren is verwijderd.");
}
else if (hoofdType.getSelectionModel().getSelectedItem() == "Schip"){
db.deleteVervoermiddel(Integer.parseInt(ID.getText()));
clearInputVervoermiddel();
maakLeegButtonPressed(event);
toonAlleActors();
displayAlert(Alert.AlertType.INFORMATION, "Informatie",
"Schip is verwijderd.");
}
else if (hoofdType.getSelectionModel().getSelectedItem() == "Hulpdienst"){
db.deleteVervoermiddel(Integer.parseInt(ID.getText()));
clearInputVervoermiddel();
maakLeegButtonPressed(event);
toonAlleActors();
displayAlert(Alert.AlertType.INFORMATION, "Informatie",
"Hulpdienst is verwijderd.");
}
}
}
// vult invulvelden in met de eigenschappen van de geselecteerde actor om eventueel aan te passen
@FXML
void listDataClicked(MouseEvent event) {
if (listData.getSelectionModel().getSelectedItem() != null) {
if (listData.getSelectionModel().getSelectedItem().getClass() == Schip.class) {
Schip schipTemp = (Schip) listData.getSelectionModel().getSelectedItem();
toonDataSchip(schipTemp);
} else if (listData.getSelectionModel().getSelectedItem().getClass() == Verkeerstoren.class) {
Verkeerstoren verkeerstorenTemp = (Verkeerstoren) listData.getSelectionModel().getSelectedItem();
toonDataVerkeerstoren(verkeerstorenTemp);
} else if (listData.getSelectionModel().getSelectedItem().getClass() == Hulpdienst.class) {
Hulpdienst hulpdienstTemp = (Hulpdienst) listData.getSelectionModel().getSelectedItem();
toonDataHulpdienst(hulpdienstTemp);
}
}
}
// vult invulvelden in met de eigenschappen van de geselecteerde actor om eventueel aan te passen
public void toonDataVerkeerstoren(Verkeerstoren verkeerstoren){
ID.setText(String.valueOf(verkeerstoren.getId()));
locatieBreedte.setText(String.valueOf(verkeerstoren.getLocatie().getBreedte()));
locatieLengte.setText(String.valueOf(verkeerstoren.getLocatie().getLengte()));
hoofdType.getSelectionModel().select("Verkeerstoren");
hoofdType.setDisable(true);
detailType.setValue(String.valueOf(verkeerstoren.getType()));
detailType.setDisable(true);
}
// vult invulvelden in met de eigenschappen van de geselecteerde actor om eventueel aan te passen
public void toonDataSchip(Schip schip){
ID.setText(String.valueOf(schip.getId()));
locatieBreedte.setText(String.valueOf(schip.getLocatie().getBreedte()));
locatieLengte.setText(String.valueOf(schip.getLocatie().getLengte()));
hoofdType.getSelectionModel().select("Schip");
hoofdType.setDisable(true);
detailType.setValue(String.valueOf(schip.getType()));
detailType.setDisable(true);
snelheid.setText(String.valueOf(schip.getSnelheid()));
wendbaarheid.setText(String.valueOf(schip.getWendbaarheid()));
grootte.setText(String.valueOf(schip.getGrootte()));
personenAanboord.setText(String.valueOf(schip.getPersonenAanBoord()));
koers.setText(String.valueOf(schip.getKoers()));
status.setValue(schip.getStatus().toString());
}
// vult invulvelden in met de eigenschappen van de geselecteerde actor om eventueel aan te passen
public void toonDataHulpdienst(Hulpdienst hulpdienst){
ID.setText(String.valueOf(hulpdienst.getId()));
locatieBreedte.setText(String.valueOf(hulpdienst.getLocatie().getBreedte()));
locatieLengte.setText(String.valueOf(hulpdienst.getLocatie().getLengte()));
hoofdType.getSelectionModel().select("Hulpdienst");
hoofdType.setDisable(true);
detailType.setValue(String.valueOf(hulpdienst.getType()));
detailType.setDisable(true);
snelheid.setText(String.valueOf(hulpdienst.getSnelheid()));
wendbaarheid.setText(String.valueOf(hulpdienst.getWendbaarheid()));
grootte.setText(String.valueOf(hulpdienst.getGrootte()));
personenAanboord.setText(String.valueOf(hulpdienst.getPersonenAanBoord()));
koers.setText(String.valueOf(hulpdienst.getKoers()));
status.setValue(hulpdienst.getStatus().toString());
}
// toont enkel deze velden als het om een Vervoermiddel gaat
public void visibilityVervoermiddel(Boolean bool){
snelheid.setVisible(bool);
wendbaarheid.setVisible(bool);
grootte.setVisible(bool);
personenAanboord.setVisible(bool);
koers.setVisible(bool);
status.setVisible(bool);
labelGradenTovNoorden.setVisible(bool);
labelGrootte.setVisible(bool);
labelKoers.setVisible(bool);
labelM.setVisible(bool);
labelPersonenAanBoord.setVisible(bool);
labelWendbaarheid.setVisible(bool);
labelZeemijlUur.setVisible(bool);
labelSnelheid.setVisible(bool);
labelSecondeGraad.setVisible(bool);
labelStatus.setVisible(bool);
}
// maakt alle velden met betrekking tot Vervoermiddel leeg
public void clearInputVervoermiddel(){
snelheid.clear();
wendbaarheid.clear();
grootte.clear();
personenAanboord.clear();
koers.clear();
status.getSelectionModel().clearSelection();
}
// maakt alle basisvelden voor elke actor leeg
public void clearInputBasis(){
ID.clear();
locatieBreedte.clear();
locatieLengte.clear();
hoofdType.getSelectionModel().clearSelection();
detailType.getSelectionModel().clearSelection();
}
// wijzigt de ingave van een actor aan de hand van het gekozen Hoofdtype
@FXML
void hoofdTypeClicked(ActionEvent event) {
if (hoofdType.getValue() != null){
switch (hoofdType.getValue()) {
case "Verkeerstoren":
clearInputVervoermiddel();
detailType.getItems().setAll(verkeerstorenTypeLijst.getVerkeerstorenType());
visibilityVervoermiddel(false);
break;
case "Schip":
clearInputVervoermiddel();
detailType.getItems().setAll(schipTypeLijst.getSchipType());
visibilityVervoermiddel(true);
break;
case "Hulpdienst":
clearInputVervoermiddel();
detailType.getItems().setAll(hulpdienstTypeLijst.getHulpdienstType());
visibilityVervoermiddel(true);
break;
default:
break;
}
}
else {visibilityVervoermiddel(true);}
}
// valideert de input voor Vervoermiddel die numeriek moeten zijn
private int validatieVervoermiddel(){
try {
Double.parseDouble(snelheid.getText().replace(",","."));
Double.parseDouble(wendbaarheid.getText().replace(",","."));
Double.parseDouble(grootte.getText().replace(",","."));
Double.parseDouble(personenAanboord.getText().replace(",","."));
Double.parseDouble(koers.getText().replace(",","."));
return 0;
}
catch (Exception e) {
displayAlert(Alert.AlertType.ERROR, "Input is incorrect",
"Inputvelden zijn allemaal numerieke waardes.");
return 1;
}
}
// checkt of alle tekstvelden met betrekking tot Vervoermiddel zijn ingevuld
private int checkInputVervoermiddel(){
if ( snelheid.getText().equals("") ||
wendbaarheid.getText().equals("") ||
grootte.getText().equals("") ||
personenAanboord.getText().equals("") ||
koers.getText().equals("") ||
status.getValue() == null)
{
displayAlert(Alert.AlertType.ERROR, "Ontbrekende gegevens",
"Alle inputvelden zijn vereist.");
return 1;
}
else {
return validatieVervoermiddel();
}
}
// checkt of alle input velden met betrekking tot locatie numerieke waarden zijn
private int validatieBasis(){
try {
Double.parseDouble(locatieLengte.getText().replace(",","."));
Double.parseDouble(locatieBreedte.getText().replace(",","."));
return 0;
}
catch (Exception e) {
displayAlert(Alert.AlertType.ERROR, "Input is incorrect",
"Inputvelden zijn allemaal numerieke waardes.");
return 1;
}
}
// checkt of inputvelden niet leeg zijn
private int checkInputBasis(){
if ( locatieLengte.getText().equals("") ||
locatieBreedte.getText().equals("") ||
detailType.getValue() == null ||
hoofdType.getValue() == null)
{
displayAlert(Alert.AlertType.ERROR, "Ontbrekende gegevens",
"Alle inputvelden zijn vereist.");
return 1;
}
else {
return validatieBasis();
}
}
private void displayAlert(Alert.AlertType type, String title, String message) {
Alert alert = new Alert(type);
alert.setTitle(title);
alert.setContentText(message);
alert.showAndWait();
}
}
| MatthiasSomay/Examen_Java_2019 | Examen_Java_2019/src/controller/MainWindowController.java | 7,139 | // vult invulvelden in met de eigenschappen van de geselecteerde actor om eventueel aan te passen | line_comment | nl | /**
* @Autor: Matthias Somay & Kenneth Van De Borne
* @Date: 15/12/2018
* @Project: Examen_Java_2019
* @Purpose: Controller klasse JavaFX
*/
package controller;
import db.DatabaseQueries;
import factory.HulpdienstFactory;
import factory.SchipFactory;
import factory.VerkeerstorenFactory;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Circle;
import model.*;
import utilities.demodata.HulpdienstTypeLijst;
import utilities.demodata.SchipTypeLijst;
import utilities.demodata.VerkeerstorenTypeLijst;
import utilities.generator.Generator;
import utilities.states.InNood;
public class MainWindowController {
SchipTypeLijst schipTypeLijst = new SchipTypeLijst();
HulpdienstTypeLijst hulpdienstTypeLijst = new HulpdienstTypeLijst();
VerkeerstorenTypeLijst verkeerstorenTypeLijst = new VerkeerstorenTypeLijst();
DatabaseQueries db = new DatabaseQueries();
Generator generator = new Generator();
@FXML private Pane mapDisplay;
@FXML private ListView<Actor> listData;
@FXML private Button toonAlleVerkeerstorens;
@FXML private Button toonAllehulpdiensten;
@FXML private Button toonAlleSchepen;
@FXML private Button toonAlles;
@FXML private Label labelSnelheid;
@FXML private Label labelKoers;
@FXML private Label labelPersonenAanBoord;
@FXML private Label labelWendbaarheid;
@FXML private TextField ID;
@FXML private TextField locatieLengte;
@FXML private TextField locatieBreedte;
@FXML private TextField snelheid;
@FXML private TextField wendbaarheid;
@FXML private TextField grootte;
@FXML private TextField personenAanboord;
@FXML private TextField koers;
@FXML private ComboBox<String> detailType;
@FXML private Label labelGrootte;
@FXML private Label labelStatus;
@FXML private Label labelZeemijlUur;
@FXML private Label labelSecondeGraad;
@FXML private Label labelM;
@FXML private Label labelGradenTovNoorden;
@FXML private ComboBox<String> status;
@FXML private ComboBox<String> hoofdType;
@FXML private Button slaOp;
@FXML private Button Verwijder;
@FXML private Button maakLeeg;
@FXML private Button startRandomReddingsactie;
// maakt inputvelden leeg
@FXML
void maakLeegButtonPressed(ActionEvent event) {
clearInputBasis();
clearInputVervoermiddel();
hoofdType.setDisable(false);
detailType.setDisable(false);
}
// Creërt nieuwe actor wanneer ID veld leeg is, update actor in het andere geval
@FXML
void slaOpButtonPressed(ActionEvent event) {
if(ID.getText().equals("")){
creatieActor();
}
else{
updateActor();
}
}
// initialiseert comboboxs en schakelt het veld "ID" uit
public void initialize(){
hoofdType.getItems().addAll("Verkeerstoren", "Schip", "Hulpdienst");
status.getItems().addAll("Beschikbaar", "Niet beschikbaar", "In nood");
ID.setDisable(true);
// Method voor het vullen van de database.
/*generator.setUpRandomData(db);*/
db.refreshData();
db.print();
}
//Geeft elke actor weer op de kaart met een eigen kleur, wanneer er op een actor geklikt wordt, worden zijn eigenschappen getoond
public void drawActorOnPane(){
mapDisplay.getChildren().clear();
Paint brushColor;
Circle newCircle;
for (Actor actor: listData.getItems()
) {
if (actor.getClass() == Schip.class){
brushColor = Color.BLACK;
newCircle = new Circle(actor.getLocatie().getBreedte(), actor.getLocatie().getLengte(),5,brushColor);
}
else if (actor.getClass() == Hulpdienst.class){
brushColor = Color.BLUE;
newCircle = new Circle(actor.getLocatie().getBreedte(), actor.getLocatie().getLengte(),5,brushColor);
}
else {
brushColor = Color.RED;
newCircle = new Circle(actor.getLocatie().getBreedte(), actor.getLocatie().getLengte(),7,brushColor);
}
newCircle.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (actor.getClass() == Hulpdienst.class){
toonDataHulpdienst((Hulpdienst)actor);
}
else if (actor.getClass() == Schip.class){
toonDataSchip((Schip)actor);
}
else if (actor.getClass() == Verkeerstoren.class){
toonDataVerkeerstoren((Verkeerstoren) actor);
}
}
});
mapDisplay.getChildren().add(newCircle);
}
}
// Geeft locatie aan van de geselecteerde actor op de kaart
@FXML
void mapDisplayClicked(MouseEvent event) {
if (ID.getText().equals("")) {
locatieBreedte.setText(String.valueOf(event.getX()));
locatieLengte.setText(String.valueOf(event.getY()));
}
}
// method voor het updaten van een geselecteerde actor
public void updateActor(){
if (hoofdType.getValue() != null){
if (hoofdType.getValue() == "Verkeerstoren"){
if (checkInputBasis() == 0){
Verkeerstoren verkeerstorenTemp = null;
for (Verkeerstoren v: db.getVerkeerstorens()
) {
if (v.getId() == Integer.parseInt(ID.getText())){
verkeerstorenTemp = v;
break;
}
}
verkeerstorenTemp.getLocatie().setBreedte(Double.parseDouble(locatieBreedte.getText()));
verkeerstorenTemp.getLocatie().setLengte(Double.parseDouble(locatieLengte.getText()));
db.updateVerkeerstoren(verkeerstorenTemp);
displayAlert(Alert.AlertType.INFORMATION, "Informatie",
"Verkeerstoren is aangepast.");
}
}
else if (hoofdType.getValue() == "Schip"){
if (checkInputBasis() == 0){
if (checkInputVervoermiddel() == 0){
Schip schipTemp = null;
for (Schip s: db.getSchepen()
) {
if (s.getId() == Integer.parseInt(ID.getText())){
schipTemp = s;
break;
}
}
schipTemp.getLocatie().setBreedte(Double.parseDouble(locatieBreedte.getText()));
schipTemp.getLocatie().setLengte(Double.parseDouble(locatieLengte.getText()));
schipTemp.setSnelheid(Double.parseDouble(snelheid.getText()));
schipTemp.setGrootte(Double.parseDouble(grootte.getText()));
schipTemp.setWendbaarheid(Double.parseDouble(wendbaarheid.getText()));
schipTemp.setPersonenAanBoord(Integer.parseInt(personenAanboord.getText()));
schipTemp.setKoers(Double.parseDouble(koers.getText()));
schipTemp.setStatus(db.CalculateState(status.getValue()));
db.updateVervoermiddel(schipTemp, hoofdType.getValue());
displayAlert(Alert.AlertType.INFORMATION, "Informatie",
"Schip is aangepast.");
}
}
}
else {
if (checkInputBasis() == 0){
if (checkInputVervoermiddel() == 0){
Hulpdienst hulpdienstTemp = null;
for (Hulpdienst h: db.getHulpdiensten()
) {
if (h.getId() == Integer.parseInt(ID.getText())){
hulpdienstTemp = h;
break;
}
}
hulpdienstTemp.getLocatie().setBreedte(Double.parseDouble(locatieBreedte.getText()));
hulpdienstTemp.getLocatie().setLengte(Double.parseDouble(locatieLengte.getText()));
hulpdienstTemp.setSnelheid(Double.parseDouble(snelheid.getText()));
hulpdienstTemp.setGrootte(Double.parseDouble(grootte.getText()));
hulpdienstTemp.setWendbaarheid(Double.parseDouble(wendbaarheid.getText()));
hulpdienstTemp.setPersonenAanBoord(Integer.parseInt(personenAanboord.getText()));
hulpdienstTemp.setKoers(Double.parseDouble(koers.getText()));
hulpdienstTemp.setStatus(db.CalculateState(status.getValue()));
db.updateVervoermiddel(hulpdienstTemp, hoofdType.getValue());
displayAlert(Alert.AlertType.INFORMATION, "Informatie",
"Schip is aangepast.");
}
}
}
clearInputBasis();
clearInputVervoermiddel();
db.refreshData();
toonAlleActors();
}
else checkInputBasis();
}
// method voor de creatie van actor aan de hand van het gekozen type
public void creatieActor(){
if (hoofdType.getValue() != null){
if (hoofdType.getValue() == "Verkeerstoren"){
if (checkInputBasis() == 0){
Verkeerstoren verkeerstorenTemp = VerkeerstorenFactory.createVerkeerstoren(
new Coördinaten(Double.parseDouble(locatieLengte.getText()),Double.parseDouble(locatieBreedte.getText())),
detailType.getValue(),
db.getVerkeerstorens());
if (ID.getText().equals("")) {
db.addVerkeerstoren(verkeerstorenTemp);
displayAlert(Alert.AlertType.INFORMATION, "Informatie",
"Verkeerstoren is toegevoegd.");
}
}
}
else if (hoofdType.getValue() == "Schip"){
if (checkInputBasis() == 0){
if (checkInputVervoermiddel() == 0){
Schip schipTemp = SchipFactory.createSchip(
new Coördinaten(Double.parseDouble(locatieLengte.getText()), Double.parseDouble(locatieBreedte.getText())),
Double.parseDouble(snelheid.getText()),
Double.parseDouble(grootte.getText()),
Double.parseDouble(wendbaarheid.getText()),
Integer.parseInt(personenAanboord.getText()),
Double.parseDouble(koers.getText()),
detailType.getValue(),
db.CalculateState(status.getValue()),
db.getVerkeerstorens());
if (ID.getText().equals("")) {
db.addVervoermiddel(schipTemp, hoofdType.getValue());
displayAlert(Alert.AlertType.INFORMATION, "Informatie",
"Schip is toegevoegd.");
}
}
}
}
else {
if (checkInputBasis() == 0){
if (checkInputVervoermiddel() == 0){
Hulpdienst hulpdienstTemp = HulpdienstFactory.createHulpdienst(
new Coördinaten(Double.parseDouble(locatieLengte.getText()), Double.parseDouble(locatieBreedte.getText())),
Double.parseDouble(snelheid.getText()),
Double.parseDouble(grootte.getText()),
Double.parseDouble(wendbaarheid.getText()),
Integer.parseInt(personenAanboord.getText()),
Double.parseDouble(koers.getText()),
detailType.getValue(),
db.CalculateState(status.getValue()),
db.getVerkeerstorens());
if (ID.getText().equals("")) {
db.addVervoermiddel(hulpdienstTemp, hoofdType.getValue());
displayAlert(Alert.AlertType.INFORMATION, "Informatie",
"Hulpdienst is toegevoegd.");
}
}
}
}
clearInputBasis();
clearInputVervoermiddel();
db.refreshData();
toonAlleActors();
}
else checkInputBasis();
}
// start een reddingsactie met een random schip op de kaart
@FXML
void startRandomReddingsactieButtonPressed(ActionEvent event) {
generator.generateRandomSchip(db.getSchepen()).setStatus(new InNood());
}
// toont enkel de schepen in de lijst
@FXML
void toonAlleSchepenButtonPressed(ActionEvent event) {
listData.getItems().setAll(db.getSchepen());
drawActorOnPane();
}
// toont enkel de verkeerstorens in de lijst
@FXML
void toonAlleVerkeerstorensButttonPressed(ActionEvent event) {
listData.getItems().setAll(db.getVerkeerstorens());
drawActorOnPane();
}
// toont enkel de hulpdiensten in de lijst
@FXML
void toonAllehulpdienstenButtonPressed(ActionEvent event) {
listData.getItems().setAll(db.getHulpdiensten());
drawActorOnPane();
}
// toont alle actoren in de lijst m.b.v. toonAlleActors()
@FXML
void toonAllesButtonPressed(ActionEvent event) {
toonAlleActors();
}
// vult de lijst met alle actoren
public void toonAlleActors(){
listData.getItems().setAll(db.getVerkeerstorens());
listData.getItems().addAll(db.getHulpdiensten());
listData.getItems().addAll(db.getSchepen());
drawActorOnPane();
}
// verwijdert actor aan de hand van de gekozen actor in de lijst, lijst wordt vernieuwd na elke bewerking
@FXML
void verwijderButtonPressed(ActionEvent event) {
if (ID.getText() != null){
if (hoofdType.getSelectionModel().getSelectedItem() == "Verkeerstoren"){
db.deleteVerkeerstoren(Integer.parseInt(ID.getText()));
maakLeegButtonPressed(event);
toonAlleActors();
displayAlert(Alert.AlertType.INFORMATION, "Informatie",
"Verkeerstoren is verwijderd.");
}
else if (hoofdType.getSelectionModel().getSelectedItem() == "Schip"){
db.deleteVervoermiddel(Integer.parseInt(ID.getText()));
clearInputVervoermiddel();
maakLeegButtonPressed(event);
toonAlleActors();
displayAlert(Alert.AlertType.INFORMATION, "Informatie",
"Schip is verwijderd.");
}
else if (hoofdType.getSelectionModel().getSelectedItem() == "Hulpdienst"){
db.deleteVervoermiddel(Integer.parseInt(ID.getText()));
clearInputVervoermiddel();
maakLeegButtonPressed(event);
toonAlleActors();
displayAlert(Alert.AlertType.INFORMATION, "Informatie",
"Hulpdienst is verwijderd.");
}
}
}
// vult invulvelden in met de eigenschappen van de geselecteerde actor om eventueel aan te passen
@FXML
void listDataClicked(MouseEvent event) {
if (listData.getSelectionModel().getSelectedItem() != null) {
if (listData.getSelectionModel().getSelectedItem().getClass() == Schip.class) {
Schip schipTemp = (Schip) listData.getSelectionModel().getSelectedItem();
toonDataSchip(schipTemp);
} else if (listData.getSelectionModel().getSelectedItem().getClass() == Verkeerstoren.class) {
Verkeerstoren verkeerstorenTemp = (Verkeerstoren) listData.getSelectionModel().getSelectedItem();
toonDataVerkeerstoren(verkeerstorenTemp);
} else if (listData.getSelectionModel().getSelectedItem().getClass() == Hulpdienst.class) {
Hulpdienst hulpdienstTemp = (Hulpdienst) listData.getSelectionModel().getSelectedItem();
toonDataHulpdienst(hulpdienstTemp);
}
}
}
// vult invulvelden<SUF>
public void toonDataVerkeerstoren(Verkeerstoren verkeerstoren){
ID.setText(String.valueOf(verkeerstoren.getId()));
locatieBreedte.setText(String.valueOf(verkeerstoren.getLocatie().getBreedte()));
locatieLengte.setText(String.valueOf(verkeerstoren.getLocatie().getLengte()));
hoofdType.getSelectionModel().select("Verkeerstoren");
hoofdType.setDisable(true);
detailType.setValue(String.valueOf(verkeerstoren.getType()));
detailType.setDisable(true);
}
// vult invulvelden in met de eigenschappen van de geselecteerde actor om eventueel aan te passen
public void toonDataSchip(Schip schip){
ID.setText(String.valueOf(schip.getId()));
locatieBreedte.setText(String.valueOf(schip.getLocatie().getBreedte()));
locatieLengte.setText(String.valueOf(schip.getLocatie().getLengte()));
hoofdType.getSelectionModel().select("Schip");
hoofdType.setDisable(true);
detailType.setValue(String.valueOf(schip.getType()));
detailType.setDisable(true);
snelheid.setText(String.valueOf(schip.getSnelheid()));
wendbaarheid.setText(String.valueOf(schip.getWendbaarheid()));
grootte.setText(String.valueOf(schip.getGrootte()));
personenAanboord.setText(String.valueOf(schip.getPersonenAanBoord()));
koers.setText(String.valueOf(schip.getKoers()));
status.setValue(schip.getStatus().toString());
}
// vult invulvelden in met de eigenschappen van de geselecteerde actor om eventueel aan te passen
public void toonDataHulpdienst(Hulpdienst hulpdienst){
ID.setText(String.valueOf(hulpdienst.getId()));
locatieBreedte.setText(String.valueOf(hulpdienst.getLocatie().getBreedte()));
locatieLengte.setText(String.valueOf(hulpdienst.getLocatie().getLengte()));
hoofdType.getSelectionModel().select("Hulpdienst");
hoofdType.setDisable(true);
detailType.setValue(String.valueOf(hulpdienst.getType()));
detailType.setDisable(true);
snelheid.setText(String.valueOf(hulpdienst.getSnelheid()));
wendbaarheid.setText(String.valueOf(hulpdienst.getWendbaarheid()));
grootte.setText(String.valueOf(hulpdienst.getGrootte()));
personenAanboord.setText(String.valueOf(hulpdienst.getPersonenAanBoord()));
koers.setText(String.valueOf(hulpdienst.getKoers()));
status.setValue(hulpdienst.getStatus().toString());
}
// toont enkel deze velden als het om een Vervoermiddel gaat
public void visibilityVervoermiddel(Boolean bool){
snelheid.setVisible(bool);
wendbaarheid.setVisible(bool);
grootte.setVisible(bool);
personenAanboord.setVisible(bool);
koers.setVisible(bool);
status.setVisible(bool);
labelGradenTovNoorden.setVisible(bool);
labelGrootte.setVisible(bool);
labelKoers.setVisible(bool);
labelM.setVisible(bool);
labelPersonenAanBoord.setVisible(bool);
labelWendbaarheid.setVisible(bool);
labelZeemijlUur.setVisible(bool);
labelSnelheid.setVisible(bool);
labelSecondeGraad.setVisible(bool);
labelStatus.setVisible(bool);
}
// maakt alle velden met betrekking tot Vervoermiddel leeg
public void clearInputVervoermiddel(){
snelheid.clear();
wendbaarheid.clear();
grootte.clear();
personenAanboord.clear();
koers.clear();
status.getSelectionModel().clearSelection();
}
// maakt alle basisvelden voor elke actor leeg
public void clearInputBasis(){
ID.clear();
locatieBreedte.clear();
locatieLengte.clear();
hoofdType.getSelectionModel().clearSelection();
detailType.getSelectionModel().clearSelection();
}
// wijzigt de ingave van een actor aan de hand van het gekozen Hoofdtype
@FXML
void hoofdTypeClicked(ActionEvent event) {
if (hoofdType.getValue() != null){
switch (hoofdType.getValue()) {
case "Verkeerstoren":
clearInputVervoermiddel();
detailType.getItems().setAll(verkeerstorenTypeLijst.getVerkeerstorenType());
visibilityVervoermiddel(false);
break;
case "Schip":
clearInputVervoermiddel();
detailType.getItems().setAll(schipTypeLijst.getSchipType());
visibilityVervoermiddel(true);
break;
case "Hulpdienst":
clearInputVervoermiddel();
detailType.getItems().setAll(hulpdienstTypeLijst.getHulpdienstType());
visibilityVervoermiddel(true);
break;
default:
break;
}
}
else {visibilityVervoermiddel(true);}
}
// valideert de input voor Vervoermiddel die numeriek moeten zijn
private int validatieVervoermiddel(){
try {
Double.parseDouble(snelheid.getText().replace(",","."));
Double.parseDouble(wendbaarheid.getText().replace(",","."));
Double.parseDouble(grootte.getText().replace(",","."));
Double.parseDouble(personenAanboord.getText().replace(",","."));
Double.parseDouble(koers.getText().replace(",","."));
return 0;
}
catch (Exception e) {
displayAlert(Alert.AlertType.ERROR, "Input is incorrect",
"Inputvelden zijn allemaal numerieke waardes.");
return 1;
}
}
// checkt of alle tekstvelden met betrekking tot Vervoermiddel zijn ingevuld
private int checkInputVervoermiddel(){
if ( snelheid.getText().equals("") ||
wendbaarheid.getText().equals("") ||
grootte.getText().equals("") ||
personenAanboord.getText().equals("") ||
koers.getText().equals("") ||
status.getValue() == null)
{
displayAlert(Alert.AlertType.ERROR, "Ontbrekende gegevens",
"Alle inputvelden zijn vereist.");
return 1;
}
else {
return validatieVervoermiddel();
}
}
// checkt of alle input velden met betrekking tot locatie numerieke waarden zijn
private int validatieBasis(){
try {
Double.parseDouble(locatieLengte.getText().replace(",","."));
Double.parseDouble(locatieBreedte.getText().replace(",","."));
return 0;
}
catch (Exception e) {
displayAlert(Alert.AlertType.ERROR, "Input is incorrect",
"Inputvelden zijn allemaal numerieke waardes.");
return 1;
}
}
// checkt of inputvelden niet leeg zijn
private int checkInputBasis(){
if ( locatieLengte.getText().equals("") ||
locatieBreedte.getText().equals("") ||
detailType.getValue() == null ||
hoofdType.getValue() == null)
{
displayAlert(Alert.AlertType.ERROR, "Ontbrekende gegevens",
"Alle inputvelden zijn vereist.");
return 1;
}
else {
return validatieBasis();
}
}
private void displayAlert(Alert.AlertType type, String title, String message) {
Alert alert = new Alert(type);
alert.setTitle(title);
alert.setContentText(message);
alert.showAndWait();
}
}
|
18969_12 | import java.io.IOException;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.LinkedList;
import java.util.Random;
public class SwapOperatorHC {
private boolean visualize = false;
private Random r = new Random(1);
private String file;
private int MAX_DEPTH = 4;
/**Global Graph Variables**/
private Graph g;
private BitMatrix neighbours;
private int[] D;
private int[] tempD;
/**Global Coloring Variables**/
private int NR_OF_COLORS;
private int best_NR_OF_COLORS;
private BitMatrix currentColorSets;
private BitMatrix newColorSets;
private BitMatrix bestColoring;
private int sumPresentConflicts;
/**Local Search Global Variables**/
private long swapOperations;
private long swapImprovements;
private long newColorAssignments;
private long swapChains;
private boolean swapped;
private int colorReductions;
private int iterations;
//global parameters
private int ConflictSumReduction;
private int timesAcceptedSolutions;
private final boolean GRAPHICS = false;
private final boolean GRAPHICSD = false;
private ArrayList<Long> times = new ArrayList<>();
private ArrayList<Long> values = new ArrayList<>();
private ArrayList<ArrayList<Long>> dValues = new ArrayList<>();
private ArrayList<ArrayList<Integer>> nodeColors = new ArrayList<>();
public static void main(String[] args) throws IOException {
new SwapOperatorHC("src/Files/seconds/david.txt");
//new SwapOperatorHC1(args[0]);
}
public SwapOperatorHC(String f) throws IOException {
file = f;
colorGraph();
}
public void colorGraph() throws IOException {
/**experiment Parameters**/
swapOperations = 0;
swapImprovements = 0;
newColorAssignments = 0;
colorReductions = 0;
iterations = 0;
//global parameters
long duration = 0;
sumPresentConflicts = 0;
timesAcceptedSolutions = 0;
int Sum_Best_NR_OF_COLORS = 0;
ConflictSumReduction = 0;
/**experiment Parameters**/
g = new Graph(file);
neighbours = new BitMatrix(g.getNrVertices(), g.getNrVertices());
for (int i = 0; i < g.getNrVertices(); i++) {
LinkedList<Integer> adjList = g.getNeighbors(i);
BitSet temp = new BitSet(g.getNrVertices());
for (Integer integer : adjList) {
if (integer != i) temp.set(integer);
}
neighbours.setRow(temp, i);
}
NR_OF_COLORS = g.getGraphDegree() + 1;
long startTime = System.nanoTime();
currentColorSets = new BitMatrix(NR_OF_COLORS, g.getNrVertices());
initialColoring();
int intialColors = NR_OF_COLORS;
best_NR_OF_COLORS = NR_OF_COLORS;
//System.out.println(NR_OF_COLORS);
D = new int[g.getNrVertices()];
//1 kleurklasse verwijderen & ontkleurde knopen herverdelen over de resterende verzamelingen
removeColor();
newColorSets = new BitMatrix(currentColorSets);
updateD();
for (int j : D) {
sumPresentConflicts += j;
}
localSearch(startTime);
//System.out.println("de graaf werd feasible gekleurd in "+best_NR_OF_COLORS+" kleuren");
long endTime = System.nanoTime();
duration += (endTime-startTime);
Sum_Best_NR_OF_COLORS += best_NR_OF_COLORS;
//System.out.println(file);
String[] filePath = file.split("/");
String fileName = filePath[filePath.length-1];
//System.out.println(fileName);
System.out.println(duration);
StringBuilder data = new StringBuilder(fileName+ "," + Sum_Best_NR_OF_COLORS + "," + duration+ "," + swapOperations +
"," + swapImprovements + "," + newColorAssignments + "," + timesAcceptedSolutions + ","+ConflictSumReduction + "," + swapOperations/swapChains+","+ intialColors+","+colorReductions+","+iterations);
/*if (GRAPHICS) {
System.out.println("sumPresentConflicts");
for (int i = 0; i < values.size(); i++) {
System.out.print(values.get(i)+","+times.get(i));
}
System.out.println();
}
if (GRAPHICSD) {
System.out.println("D");
for (int i = 0; i < g.getNrVertices(); i++) {
for (int j = 0; j < dValues.get(i).size(); j++) {
System.out.print(dValues.get(i).get(j)+","+times.get(j));
}
}
System.out.println();
}*/
//printNodeColors(currentColorSets);
validator();
System.out.println("Tijden in ns:");
System.out.println("avg duration: "+ duration);
System.out.println("G,HC X(G),total duration,#swap,#swap improvement,#new color assignment,# worse solutions accepted,#sum conflicts reduction, avg depth of swap chain, Init X(G), #colorreductions, iteraties");
System.out.println(data);
}
public void printNodeColors(BitMatrix b) {
System.out.print("colors: ");
for (int i = 0; i < g.getNrVertices(); i++) {
System.out.print(getColor(i, b)+" ");
}
System.out.println();
}
public void printD(long time) {
System.out.print("D: "+time+" ");
for (int i = 0; i < g.getNrVertices(); i++) {
System.out.print(D[i]+" ");
}
System.out.println();
}
public void printSumPresentConflicts(long time) {
System.out.println("CH: "+sumPresentConflicts+" "+time);
}
public void printColorRemoved(long time) {
System.out.println("CR: "+time);
}
/**LocalSearch**/
public void localSearch(long absStartTime) {
for (int i = 0; i < g.getNrVertices(); i++) {
dValues.add(new ArrayList<>());
}
double T = 10000;
double T_MIN = 0.001;
int iteraties;
int iteratiesWI;
int eqIterations1 = 2*g.getNrEdges()/(g.getNrVertices()-1);
long timeStart = System.nanoTime();
LinkedList<int[]> currentConflictedNodes = findConflictingNodes(currentColorSets);
LinkedList<int[]> newConflictedNodes = findConflictingNodes(newColorSets);
iteraties=0;
while (T>T_MIN) {
iterations+=iteraties;
System.out.println("T: "+T);
iteraties=0;
iteratiesWI = 0;
while (iteraties<eqIterations1 && iteratiesWI < 10) {
sumPresentConflicts = 0;
for (int[] newConflictedNode : currentConflictedNodes) {
sumPresentConflicts += D[newConflictedNode[0]];
}
if(GRAPHICS || GRAPHICSD) {
long currTime = System.nanoTime() - timeStart;
times.add(currTime);
if (GRAPHICS) {
values.add((long) sumPresentConflicts);
printSumPresentConflicts(currTime);
}
if (GRAPHICSD) {
for (int i = 0; i < g.getNrVertices(); i++) {
dValues.get(i).add((long) D[i]);
}
printD(currTime);
}
}
if (currentConflictedNodes.size() > 0) {
//perform an operation on NewColorSets
int randomConflictedNode = r.nextInt(currentConflictedNodes.size());
tempD = new int[D.length];
swapped = false;
operator(currentConflictedNodes.get(randomConflictedNode)[0], currentConflictedNodes.get(randomConflictedNode)[1], 0);
newConflictedNodes.clear();
newConflictedNodes = findConflictingNodes(newColorSets);
}
int newSumConflicts = 0;
for (int[] newConflictedNode : newConflictedNodes) {
newSumConflicts += D[newConflictedNode[0]] + tempD[newConflictedNode[0]];
}
if(newSumConflicts<sumPresentConflicts) {
ConflictSumReduction++;
if (swapped) swapImprovements++;
iteratiesWI = 0;
sumPresentConflicts = newSumConflicts;
currentColorSets = new BitMatrix(newColorSets);
for (int i = 0; i < D.length; i++) {
D[i] += tempD[i];
}
currentConflictedNodes = findConflictingNodes(currentColorSets);
}
else if (Math.exp((sumPresentConflicts-newSumConflicts)/T)> r.nextDouble()) {
timesAcceptedSolutions++;
currentColorSets = new BitMatrix(newColorSets);
for (int i = 0; i < D.length; i++) {
D[i] += tempD[i];
}
sumPresentConflicts = newSumConflicts;
iteratiesWI = 0;
currentColorSets = new BitMatrix(newColorSets);
currentConflictedNodes = findConflictingNodes(currentColorSets);
}
else {
newColorSets = new BitMatrix(currentColorSets);
iteratiesWI++;
}
if (newSumConflicts == 0) {
colorReductions++;
if (GRAPHICS || GRAPHICSD) printColorRemoved(System.nanoTime() - timeStart);
iteratiesWI = 0;
best_NR_OF_COLORS = NR_OF_COLORS;
if(GRAPHICS) {
long currTime = System.nanoTime() - timeStart;
times.add(currTime);
values.add((long) sumPresentConflicts);
}
//kleur verwijderen waarvoor som van conflict counters (D) het laagst is
removeColor();
//na verwijderne van kleur bevat currentColorSets opnieuw conflicten => lijst aanpassen
currentConflictedNodes = findConflictingNodes(currentColorSets);
}
updateD();
iteraties++;
}
T*=0.999;
}
}
public void addNodeColorsToList() {
long currTime = System.nanoTime();
for (int i = 0; i < g.getNrVertices(); i++) {
nodeColors.get(i).add(getColor(i, newColorSets));
}
}
public static void printColorSets(BitMatrix b) {
for (int i = 0; i < b.getRows(); i++) {
System.out.println(b.getRow(i));
}
System.out.println("#########################");
}
public void initialColoring() {
//genereer initiële kleuring mbv greedy algoritme
//1e knoop (0) toewijzen aan 1e kleurklasse (0)
currentColorSets.getRow(0).set(0, true);
for (int v=1; v< g.getNrVertices(); v++) {
int c = 0;
currentColorSets.getRow(c).set(v, true);
//assign(v, c, currentColoring);
while (neighborConflict(v, c, currentColorSets)){
currentColorSets.getRow(c).set(v, false);
c++;
currentColorSets.getRow(c).set(v, true);
if(c > NR_OF_COLORS) NR_OF_COLORS = c;
}
}
removeInitialRedundantSets(currentColorSets);
}
public boolean neighborConflict(int v, int c, BitMatrix b) {
//check of een de knopen in de kleurklasse van v buren zijn van v
BitSet temp = (BitSet) neighbours.getRow(v).clone();
temp.and(b.getRow(c));
return temp.cardinality() > 0 && !(temp.cardinality() == 1 && temp.get(v));
}
public void removeInitialRedundantSets(BitMatrix b) {
ArrayList<Integer> rowsToRemove = new ArrayList<>();
for (int i = b.getRows()-1; i >= 0; i--) {
if (b.getRow(i).cardinality()==0) rowsToRemove.add(i);
}
for (Integer integer : rowsToRemove) {
b.removeRow(integer);
NR_OF_COLORS--;
}
}
public void removeColor() {
bestColoring = new BitMatrix(currentColorSets);
//vind kleur klasse waarvoor minste conflict counters
int c = leastConflictCounters();
currentColorSets.removeRow(c);
NR_OF_COLORS--;
recolorNodes();
}
public int leastConflictCounters() {
//kleur klasse vinden waar voor de som van de geschiedenis van conflicten van van knopen in die klasse de kleinste is
int row=-1;
int minSum = Integer.MAX_VALUE;
for (int i = 0; i < currentColorSets.getRows(); i++) {
BitSet temp = currentColorSets.getRow(i);
int sum = 0;
for (int j = 0; j < temp.cardinality(); j++) {
int v = temp.nextSetBit(j);
sum += D[v];
}
//System.out.println("color: "+i+", Dsum: "+sum+", |V|: "+currentColorSets.getRow(i).cardinality());
if(sum<minSum) {
row = i;
minSum = sum;
}
}
//System.out.println("gekozen kleur set: "+row+", Dsum: "+minSum);
return row;
}
public void recolorNodes() {
//ongekleurde knopen opnieuw verdelen over overige kleurklassen zodat aantal conflicten (voor die knopen) minimaal is
int[] uncoloredNodes = findUncoloredNodes();
for (int i = 0; i < uncoloredNodes.length; i++) {
int[] colors = new int[NR_OF_COLORS];
//per kleur set bepalen hoeveel buren erin zitten
for (int j = 0; j < NR_OF_COLORS; j++) {
BitSet temp = (BitSet) neighbours.getRow(i).clone();
temp.and(currentColorSets.getRow(j));
colors[j] = temp.cardinality();
}
int new_color = 0;
//ongekleurde knoop toewijzen aan kleurset die minste aantal buren bevat => minst nieuwe conflicten
//indien meedere kleuren zelfde aantal buren => laagste kleur
int min_neigbours = Integer.MAX_VALUE;
for (int j = colors.length-1; j >= 0; j--) {
if (colors[j] <= min_neigbours) {
new_color = j;
min_neigbours = colors[j];
}
}
currentColorSets.getRow(new_color).set(uncoloredNodes[i]);
}
newColorSets = new BitMatrix(currentColorSets);
}
public int[] findUncoloredNodes(){
BitSet temp = (BitSet) currentColorSets.getRow(0).clone();
for (int i = 1; i < currentColorSets.getRows(); i++) {
temp.or(currentColorSets.getRow(i));
}
//na or met elke rij in currentcolorsets zal de bit van elke knoop die een kleur heeft 1 zijn
//alle bits na de or flippen
// enkel bits van knopen die in geen enkele kleurklasse zitten zal 1 zijn
temp.flip(0, g.getNrVertices());
int[] uncoloredNodes = new int[temp.cardinality()];
int nextSetBit = 0;
for (int i = 0; i < temp.cardinality(); i++) {
uncoloredNodes[i] = temp.nextSetBit(nextSetBit);
nextSetBit = uncoloredNodes[i]+1;
}
return uncoloredNodes;
}
public void updateD() {
for (int i = 0; i < g.getNrVertices(); i++) {
for (int j = 0; j < currentColorSets.getRows(); j++) {
if (currentColorSets.getRow(j).get(i)) {
if(neighborConflict(i, j, currentColorSets)) {
BitSet temp = (BitSet) neighbours.getRow(i).clone();
temp.and(currentColorSets.getRow(j));
D[i] += temp.cardinality();
}
break;
}
}
}
}
public void updateDNaSwap() {
for (int i = 0; i < newColorSets.getRows(); i++) {
BitSet color = (BitSet) newColorSets.getRow(i).clone();
for (int j = color.nextSetBit(0); j >=0; j = color.nextSetBit(j+1)) {
// operate on index i here
BitSet n = (BitSet) neighbours.getRow(j).clone();
n.and(color);
tempD[j] += n.cardinality();
if (j == Integer.MAX_VALUE) {
break; // or (i+1) would overflow
}
}
}
}
public LinkedList<int[]> findConflictingNodes(BitMatrix b) {
LinkedList<int[]> conflictingNodes = new LinkedList<>();
//i = knoop
//j = kleur toegewezen aan die knoop
for (int i = 0; i < g.getNrVertices(); i++) {
for (int j = 0; j < NR_OF_COLORS; j++) {
if (b.getRow(j).get(i)) {
if(neighborConflict(i, j, b)) {
int[] temp = new int[2];
temp[0] = i;
temp[1] = j;
conflictingNodes.add(temp);
}
}
}
}
return conflictingNodes;
}
public int getColor(int v, BitMatrix b) {
int k = 0;
while (k<NR_OF_COLORS && !b.getRow(k).get(v)) {
k++;
}
return k;
}
public void operator(int v, int c, int d) {
//System.out.println("d: "+d);
//knoop eerst proberen in ongebruikte kleur om conflict op te lossen
//als geen ongebruikte kleur:
//knoop swappen met buur waarvan D[knoop] = minimaal
//daarna operator oproepen op knoop waarmee geswapped werd
//als knoop geen conflict heeft => keer terug naar vorige knoop die nu andere kleur heeft
int nc = assignUnusedColor(v);
if (nc >= 0 && nc < NR_OF_COLORS) {
//System.out.println("new color: "+nc +" available for node: "+v);
newColorAssignments++;
BitSet temp = new BitSet(g.getNrVertices());
temp.set(v);
temp.flip(0, g.getNrVertices());
for (int j = 0; j < newColorSets.getRows(); j++) {
newColorSets.AND(j, temp);
}
newColorSets.set(nc,v);
//addNodeColorsToList();
} else {
swapped = true;
if (d == 0) swapChains++;
swapOperations++;
int[] nonConflictingNeighbours = findConflictingNeighbours(v,c, false);
if (nonConflictingNeighbours.length != 0) {
//hier methode implementeren om een buur te kiezen waarmee geswapped zal worden
//sorteer buren waar knoop geen conflict mee heeft obv waarden in D[]
//gesorteerdeNCN[0] heeft laagste waarde in D
int[] gesorteerdeNCN = nonConflictingNeighbours;
if (nonConflictingNeighbours.length > 1) {
gesorteerdeNCN = countSortD(nonConflictingNeighbours);
}
int b = gesorteerdeNCN[0];
//swap kleur van knoop met kleur van 1e knoop in gesorteerdeNCN[]
int bc = 0;
while (!newColorSets.getRow(bc).get(b) && bc <= NR_OF_COLORS) {
bc++;
}
//System.out.println("swap d: "+d + ", ("+v+","+b+")");
swap(v, b, c, bc);
//addNodeColorsToList();
//na swap eerst D updaten
updateDNaSwap();
//daarna check of b die nu kleur c heeft (ipv bc), een conflict heeft
if (neighborConflict(b, c, newColorSets) && d < MAX_DEPTH) {
//knoop heeft conflict => roep operator op voor die knoop
operator(b, c, d+1);
}
//knoop heeft geen conflict => keer terug naar vorige knoop kijk of nieuwe conflicten OF nu wel andere kleur mogelijk is in die knoop
}
}
}
public int[] countSortD(int[] buren) {
//buren[] sorteren volgens stijgende waarden van som van conflicten in D[]
//output[0] heeft laagste waarde van D van alle knopen in buren[]
int l = buren.length;
int[] output = new int[l];
int[] subD = new int[l];
for (int i = 0; i < l; i++) {
subD[i] = D[buren[i]] + tempD[buren[i]];
}
int maxval = subD[0];
for (int i = 1; i < l; i++) {
if (subD[i] > maxval) maxval = subD[i];
}
int[] counts = new int[maxval+1];
for (int j : subD) {
counts[j]++;
}
for (int i = 1; i < counts.length; i++) {
counts[i] += counts[i-1];
}
for (int i = l-1; i >= 0; i--) {
output[counts[subD[i]]-1] = buren[i];
counts[subD[i]]--;
}
return output;
}
public int[] findConflictingNeighbours(int v, int c, boolean conflicts) {
//if conflicts == true => return list of neighbours that have a conflict with node v
//if conflicts == false => return list of neighbours that don't have a conflict with node v
BitSet temp = (BitSet) neighbours.getRow(v).clone();
//temp = alle buren van v (zonder v zelf)
if (conflicts) {
//conflicts = true => we willen alle buren van v waarmee v een conflict heeft
temp.and(newColorSets.getRow(c));
//temp = alle buren van v die in dezelfde kleurklasse als v zitten
} else {
//conflicts = false => we willen de buren waarmee v geen conflict heeft
BitSet kleurC = (BitSet) newColorSets.getRow(c).clone();
kleurC.flip(0, g.getNrVertices());
//keurC bevat nu alle knopen die niet in kleur c zitten
temp.and(kleurC);
//temp bevat alle buren van v die niet in kleurklasse c zitten
}
int[] Neighbours = new int[temp.cardinality()];
int i=0;
for (int j = temp.nextSetBit(0); j >= 0; j = temp.nextSetBit(j+1)) {
// operate on index i here
Neighbours[i] = j;
if (j == Integer.MAX_VALUE) {
break; // or (i+1) would overflow
}
i++;
}
return Neighbours;
}
public int assignUnusedColor(int v) {
//v = node
//voor elke kleur checken of buren van de knoop in de verzameling van die kleur zitten
//indien geen buren in verzameling van een knoop => knoop v toewijzen aan de verzameling van die kleur
//alle kleuren gebruikt door buren van de knoop => return -1
BitSet buren = (BitSet) neighbours.getRow(v).clone();
buren.set(v);
//buren bevat v en zijn buren
BitSet temp = new BitSet(buren.length());
temp.or(buren);
//temp bevat v en zijn buren
int unusedColor = -1;
int i = 0;
while (i < NR_OF_COLORS && unusedColor==-1) {
temp.or(buren);
//temp bevat v en zijn buren
temp.and(newColorSets.getRow(i));
//temp bevat de knopen v en zijn buren die in kleur klasse i zitten
if (temp.cardinality() == 0) unusedColor = i;
//als temp leeg is => kleur i wordt niet gebruikt door v of een van zijn buren
i++;
}
return unusedColor;
}
public void swap(int v1, int v2, int c1, int c2) {
newColorSets.getRow(c1).flip(v1);
newColorSets.getRow(c1).flip(v2);
newColorSets.getRow(c2).flip(v1);
newColorSets.getRow(c2).flip(v2);
}
/***Validator***/
public void validator() {
for (int i = 0; i < g.getNrVertices(); i++) {
BitSet adj = (BitSet) neighbours.getRow(i).clone();
adj.and(bestColoring.getRow(getColor(i, bestColoring)));
if (adj.cardinality() > 0) {
//System.out.println("Invalid Solution");
printColorSets(bestColoring);
//System.out.print(i +"has conflict with: ");
for (int j = adj.nextSetBit(0); j >=0 ; j = adj.nextSetBit(j+1)) {
System.out.print(j+", ");
}
}
}
//System.out.println("Valid Solution");
}
}
| MatthieuDL/MasterproefGCP_MatthieuDeLanghe_2022-2023 | src/SwapOperatorHC.java | 7,431 | //kleur klasse vinden waar voor de som van de geschiedenis van conflicten van van knopen in die klasse de kleinste is | line_comment | nl | import java.io.IOException;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.LinkedList;
import java.util.Random;
public class SwapOperatorHC {
private boolean visualize = false;
private Random r = new Random(1);
private String file;
private int MAX_DEPTH = 4;
/**Global Graph Variables**/
private Graph g;
private BitMatrix neighbours;
private int[] D;
private int[] tempD;
/**Global Coloring Variables**/
private int NR_OF_COLORS;
private int best_NR_OF_COLORS;
private BitMatrix currentColorSets;
private BitMatrix newColorSets;
private BitMatrix bestColoring;
private int sumPresentConflicts;
/**Local Search Global Variables**/
private long swapOperations;
private long swapImprovements;
private long newColorAssignments;
private long swapChains;
private boolean swapped;
private int colorReductions;
private int iterations;
//global parameters
private int ConflictSumReduction;
private int timesAcceptedSolutions;
private final boolean GRAPHICS = false;
private final boolean GRAPHICSD = false;
private ArrayList<Long> times = new ArrayList<>();
private ArrayList<Long> values = new ArrayList<>();
private ArrayList<ArrayList<Long>> dValues = new ArrayList<>();
private ArrayList<ArrayList<Integer>> nodeColors = new ArrayList<>();
public static void main(String[] args) throws IOException {
new SwapOperatorHC("src/Files/seconds/david.txt");
//new SwapOperatorHC1(args[0]);
}
public SwapOperatorHC(String f) throws IOException {
file = f;
colorGraph();
}
public void colorGraph() throws IOException {
/**experiment Parameters**/
swapOperations = 0;
swapImprovements = 0;
newColorAssignments = 0;
colorReductions = 0;
iterations = 0;
//global parameters
long duration = 0;
sumPresentConflicts = 0;
timesAcceptedSolutions = 0;
int Sum_Best_NR_OF_COLORS = 0;
ConflictSumReduction = 0;
/**experiment Parameters**/
g = new Graph(file);
neighbours = new BitMatrix(g.getNrVertices(), g.getNrVertices());
for (int i = 0; i < g.getNrVertices(); i++) {
LinkedList<Integer> adjList = g.getNeighbors(i);
BitSet temp = new BitSet(g.getNrVertices());
for (Integer integer : adjList) {
if (integer != i) temp.set(integer);
}
neighbours.setRow(temp, i);
}
NR_OF_COLORS = g.getGraphDegree() + 1;
long startTime = System.nanoTime();
currentColorSets = new BitMatrix(NR_OF_COLORS, g.getNrVertices());
initialColoring();
int intialColors = NR_OF_COLORS;
best_NR_OF_COLORS = NR_OF_COLORS;
//System.out.println(NR_OF_COLORS);
D = new int[g.getNrVertices()];
//1 kleurklasse verwijderen & ontkleurde knopen herverdelen over de resterende verzamelingen
removeColor();
newColorSets = new BitMatrix(currentColorSets);
updateD();
for (int j : D) {
sumPresentConflicts += j;
}
localSearch(startTime);
//System.out.println("de graaf werd feasible gekleurd in "+best_NR_OF_COLORS+" kleuren");
long endTime = System.nanoTime();
duration += (endTime-startTime);
Sum_Best_NR_OF_COLORS += best_NR_OF_COLORS;
//System.out.println(file);
String[] filePath = file.split("/");
String fileName = filePath[filePath.length-1];
//System.out.println(fileName);
System.out.println(duration);
StringBuilder data = new StringBuilder(fileName+ "," + Sum_Best_NR_OF_COLORS + "," + duration+ "," + swapOperations +
"," + swapImprovements + "," + newColorAssignments + "," + timesAcceptedSolutions + ","+ConflictSumReduction + "," + swapOperations/swapChains+","+ intialColors+","+colorReductions+","+iterations);
/*if (GRAPHICS) {
System.out.println("sumPresentConflicts");
for (int i = 0; i < values.size(); i++) {
System.out.print(values.get(i)+","+times.get(i));
}
System.out.println();
}
if (GRAPHICSD) {
System.out.println("D");
for (int i = 0; i < g.getNrVertices(); i++) {
for (int j = 0; j < dValues.get(i).size(); j++) {
System.out.print(dValues.get(i).get(j)+","+times.get(j));
}
}
System.out.println();
}*/
//printNodeColors(currentColorSets);
validator();
System.out.println("Tijden in ns:");
System.out.println("avg duration: "+ duration);
System.out.println("G,HC X(G),total duration,#swap,#swap improvement,#new color assignment,# worse solutions accepted,#sum conflicts reduction, avg depth of swap chain, Init X(G), #colorreductions, iteraties");
System.out.println(data);
}
public void printNodeColors(BitMatrix b) {
System.out.print("colors: ");
for (int i = 0; i < g.getNrVertices(); i++) {
System.out.print(getColor(i, b)+" ");
}
System.out.println();
}
public void printD(long time) {
System.out.print("D: "+time+" ");
for (int i = 0; i < g.getNrVertices(); i++) {
System.out.print(D[i]+" ");
}
System.out.println();
}
public void printSumPresentConflicts(long time) {
System.out.println("CH: "+sumPresentConflicts+" "+time);
}
public void printColorRemoved(long time) {
System.out.println("CR: "+time);
}
/**LocalSearch**/
public void localSearch(long absStartTime) {
for (int i = 0; i < g.getNrVertices(); i++) {
dValues.add(new ArrayList<>());
}
double T = 10000;
double T_MIN = 0.001;
int iteraties;
int iteratiesWI;
int eqIterations1 = 2*g.getNrEdges()/(g.getNrVertices()-1);
long timeStart = System.nanoTime();
LinkedList<int[]> currentConflictedNodes = findConflictingNodes(currentColorSets);
LinkedList<int[]> newConflictedNodes = findConflictingNodes(newColorSets);
iteraties=0;
while (T>T_MIN) {
iterations+=iteraties;
System.out.println("T: "+T);
iteraties=0;
iteratiesWI = 0;
while (iteraties<eqIterations1 && iteratiesWI < 10) {
sumPresentConflicts = 0;
for (int[] newConflictedNode : currentConflictedNodes) {
sumPresentConflicts += D[newConflictedNode[0]];
}
if(GRAPHICS || GRAPHICSD) {
long currTime = System.nanoTime() - timeStart;
times.add(currTime);
if (GRAPHICS) {
values.add((long) sumPresentConflicts);
printSumPresentConflicts(currTime);
}
if (GRAPHICSD) {
for (int i = 0; i < g.getNrVertices(); i++) {
dValues.get(i).add((long) D[i]);
}
printD(currTime);
}
}
if (currentConflictedNodes.size() > 0) {
//perform an operation on NewColorSets
int randomConflictedNode = r.nextInt(currentConflictedNodes.size());
tempD = new int[D.length];
swapped = false;
operator(currentConflictedNodes.get(randomConflictedNode)[0], currentConflictedNodes.get(randomConflictedNode)[1], 0);
newConflictedNodes.clear();
newConflictedNodes = findConflictingNodes(newColorSets);
}
int newSumConflicts = 0;
for (int[] newConflictedNode : newConflictedNodes) {
newSumConflicts += D[newConflictedNode[0]] + tempD[newConflictedNode[0]];
}
if(newSumConflicts<sumPresentConflicts) {
ConflictSumReduction++;
if (swapped) swapImprovements++;
iteratiesWI = 0;
sumPresentConflicts = newSumConflicts;
currentColorSets = new BitMatrix(newColorSets);
for (int i = 0; i < D.length; i++) {
D[i] += tempD[i];
}
currentConflictedNodes = findConflictingNodes(currentColorSets);
}
else if (Math.exp((sumPresentConflicts-newSumConflicts)/T)> r.nextDouble()) {
timesAcceptedSolutions++;
currentColorSets = new BitMatrix(newColorSets);
for (int i = 0; i < D.length; i++) {
D[i] += tempD[i];
}
sumPresentConflicts = newSumConflicts;
iteratiesWI = 0;
currentColorSets = new BitMatrix(newColorSets);
currentConflictedNodes = findConflictingNodes(currentColorSets);
}
else {
newColorSets = new BitMatrix(currentColorSets);
iteratiesWI++;
}
if (newSumConflicts == 0) {
colorReductions++;
if (GRAPHICS || GRAPHICSD) printColorRemoved(System.nanoTime() - timeStart);
iteratiesWI = 0;
best_NR_OF_COLORS = NR_OF_COLORS;
if(GRAPHICS) {
long currTime = System.nanoTime() - timeStart;
times.add(currTime);
values.add((long) sumPresentConflicts);
}
//kleur verwijderen waarvoor som van conflict counters (D) het laagst is
removeColor();
//na verwijderne van kleur bevat currentColorSets opnieuw conflicten => lijst aanpassen
currentConflictedNodes = findConflictingNodes(currentColorSets);
}
updateD();
iteraties++;
}
T*=0.999;
}
}
public void addNodeColorsToList() {
long currTime = System.nanoTime();
for (int i = 0; i < g.getNrVertices(); i++) {
nodeColors.get(i).add(getColor(i, newColorSets));
}
}
public static void printColorSets(BitMatrix b) {
for (int i = 0; i < b.getRows(); i++) {
System.out.println(b.getRow(i));
}
System.out.println("#########################");
}
public void initialColoring() {
//genereer initiële kleuring mbv greedy algoritme
//1e knoop (0) toewijzen aan 1e kleurklasse (0)
currentColorSets.getRow(0).set(0, true);
for (int v=1; v< g.getNrVertices(); v++) {
int c = 0;
currentColorSets.getRow(c).set(v, true);
//assign(v, c, currentColoring);
while (neighborConflict(v, c, currentColorSets)){
currentColorSets.getRow(c).set(v, false);
c++;
currentColorSets.getRow(c).set(v, true);
if(c > NR_OF_COLORS) NR_OF_COLORS = c;
}
}
removeInitialRedundantSets(currentColorSets);
}
public boolean neighborConflict(int v, int c, BitMatrix b) {
//check of een de knopen in de kleurklasse van v buren zijn van v
BitSet temp = (BitSet) neighbours.getRow(v).clone();
temp.and(b.getRow(c));
return temp.cardinality() > 0 && !(temp.cardinality() == 1 && temp.get(v));
}
public void removeInitialRedundantSets(BitMatrix b) {
ArrayList<Integer> rowsToRemove = new ArrayList<>();
for (int i = b.getRows()-1; i >= 0; i--) {
if (b.getRow(i).cardinality()==0) rowsToRemove.add(i);
}
for (Integer integer : rowsToRemove) {
b.removeRow(integer);
NR_OF_COLORS--;
}
}
public void removeColor() {
bestColoring = new BitMatrix(currentColorSets);
//vind kleur klasse waarvoor minste conflict counters
int c = leastConflictCounters();
currentColorSets.removeRow(c);
NR_OF_COLORS--;
recolorNodes();
}
public int leastConflictCounters() {
//kleur klasse<SUF>
int row=-1;
int minSum = Integer.MAX_VALUE;
for (int i = 0; i < currentColorSets.getRows(); i++) {
BitSet temp = currentColorSets.getRow(i);
int sum = 0;
for (int j = 0; j < temp.cardinality(); j++) {
int v = temp.nextSetBit(j);
sum += D[v];
}
//System.out.println("color: "+i+", Dsum: "+sum+", |V|: "+currentColorSets.getRow(i).cardinality());
if(sum<minSum) {
row = i;
minSum = sum;
}
}
//System.out.println("gekozen kleur set: "+row+", Dsum: "+minSum);
return row;
}
public void recolorNodes() {
//ongekleurde knopen opnieuw verdelen over overige kleurklassen zodat aantal conflicten (voor die knopen) minimaal is
int[] uncoloredNodes = findUncoloredNodes();
for (int i = 0; i < uncoloredNodes.length; i++) {
int[] colors = new int[NR_OF_COLORS];
//per kleur set bepalen hoeveel buren erin zitten
for (int j = 0; j < NR_OF_COLORS; j++) {
BitSet temp = (BitSet) neighbours.getRow(i).clone();
temp.and(currentColorSets.getRow(j));
colors[j] = temp.cardinality();
}
int new_color = 0;
//ongekleurde knoop toewijzen aan kleurset die minste aantal buren bevat => minst nieuwe conflicten
//indien meedere kleuren zelfde aantal buren => laagste kleur
int min_neigbours = Integer.MAX_VALUE;
for (int j = colors.length-1; j >= 0; j--) {
if (colors[j] <= min_neigbours) {
new_color = j;
min_neigbours = colors[j];
}
}
currentColorSets.getRow(new_color).set(uncoloredNodes[i]);
}
newColorSets = new BitMatrix(currentColorSets);
}
public int[] findUncoloredNodes(){
BitSet temp = (BitSet) currentColorSets.getRow(0).clone();
for (int i = 1; i < currentColorSets.getRows(); i++) {
temp.or(currentColorSets.getRow(i));
}
//na or met elke rij in currentcolorsets zal de bit van elke knoop die een kleur heeft 1 zijn
//alle bits na de or flippen
// enkel bits van knopen die in geen enkele kleurklasse zitten zal 1 zijn
temp.flip(0, g.getNrVertices());
int[] uncoloredNodes = new int[temp.cardinality()];
int nextSetBit = 0;
for (int i = 0; i < temp.cardinality(); i++) {
uncoloredNodes[i] = temp.nextSetBit(nextSetBit);
nextSetBit = uncoloredNodes[i]+1;
}
return uncoloredNodes;
}
public void updateD() {
for (int i = 0; i < g.getNrVertices(); i++) {
for (int j = 0; j < currentColorSets.getRows(); j++) {
if (currentColorSets.getRow(j).get(i)) {
if(neighborConflict(i, j, currentColorSets)) {
BitSet temp = (BitSet) neighbours.getRow(i).clone();
temp.and(currentColorSets.getRow(j));
D[i] += temp.cardinality();
}
break;
}
}
}
}
public void updateDNaSwap() {
for (int i = 0; i < newColorSets.getRows(); i++) {
BitSet color = (BitSet) newColorSets.getRow(i).clone();
for (int j = color.nextSetBit(0); j >=0; j = color.nextSetBit(j+1)) {
// operate on index i here
BitSet n = (BitSet) neighbours.getRow(j).clone();
n.and(color);
tempD[j] += n.cardinality();
if (j == Integer.MAX_VALUE) {
break; // or (i+1) would overflow
}
}
}
}
public LinkedList<int[]> findConflictingNodes(BitMatrix b) {
LinkedList<int[]> conflictingNodes = new LinkedList<>();
//i = knoop
//j = kleur toegewezen aan die knoop
for (int i = 0; i < g.getNrVertices(); i++) {
for (int j = 0; j < NR_OF_COLORS; j++) {
if (b.getRow(j).get(i)) {
if(neighborConflict(i, j, b)) {
int[] temp = new int[2];
temp[0] = i;
temp[1] = j;
conflictingNodes.add(temp);
}
}
}
}
return conflictingNodes;
}
public int getColor(int v, BitMatrix b) {
int k = 0;
while (k<NR_OF_COLORS && !b.getRow(k).get(v)) {
k++;
}
return k;
}
public void operator(int v, int c, int d) {
//System.out.println("d: "+d);
//knoop eerst proberen in ongebruikte kleur om conflict op te lossen
//als geen ongebruikte kleur:
//knoop swappen met buur waarvan D[knoop] = minimaal
//daarna operator oproepen op knoop waarmee geswapped werd
//als knoop geen conflict heeft => keer terug naar vorige knoop die nu andere kleur heeft
int nc = assignUnusedColor(v);
if (nc >= 0 && nc < NR_OF_COLORS) {
//System.out.println("new color: "+nc +" available for node: "+v);
newColorAssignments++;
BitSet temp = new BitSet(g.getNrVertices());
temp.set(v);
temp.flip(0, g.getNrVertices());
for (int j = 0; j < newColorSets.getRows(); j++) {
newColorSets.AND(j, temp);
}
newColorSets.set(nc,v);
//addNodeColorsToList();
} else {
swapped = true;
if (d == 0) swapChains++;
swapOperations++;
int[] nonConflictingNeighbours = findConflictingNeighbours(v,c, false);
if (nonConflictingNeighbours.length != 0) {
//hier methode implementeren om een buur te kiezen waarmee geswapped zal worden
//sorteer buren waar knoop geen conflict mee heeft obv waarden in D[]
//gesorteerdeNCN[0] heeft laagste waarde in D
int[] gesorteerdeNCN = nonConflictingNeighbours;
if (nonConflictingNeighbours.length > 1) {
gesorteerdeNCN = countSortD(nonConflictingNeighbours);
}
int b = gesorteerdeNCN[0];
//swap kleur van knoop met kleur van 1e knoop in gesorteerdeNCN[]
int bc = 0;
while (!newColorSets.getRow(bc).get(b) && bc <= NR_OF_COLORS) {
bc++;
}
//System.out.println("swap d: "+d + ", ("+v+","+b+")");
swap(v, b, c, bc);
//addNodeColorsToList();
//na swap eerst D updaten
updateDNaSwap();
//daarna check of b die nu kleur c heeft (ipv bc), een conflict heeft
if (neighborConflict(b, c, newColorSets) && d < MAX_DEPTH) {
//knoop heeft conflict => roep operator op voor die knoop
operator(b, c, d+1);
}
//knoop heeft geen conflict => keer terug naar vorige knoop kijk of nieuwe conflicten OF nu wel andere kleur mogelijk is in die knoop
}
}
}
public int[] countSortD(int[] buren) {
//buren[] sorteren volgens stijgende waarden van som van conflicten in D[]
//output[0] heeft laagste waarde van D van alle knopen in buren[]
int l = buren.length;
int[] output = new int[l];
int[] subD = new int[l];
for (int i = 0; i < l; i++) {
subD[i] = D[buren[i]] + tempD[buren[i]];
}
int maxval = subD[0];
for (int i = 1; i < l; i++) {
if (subD[i] > maxval) maxval = subD[i];
}
int[] counts = new int[maxval+1];
for (int j : subD) {
counts[j]++;
}
for (int i = 1; i < counts.length; i++) {
counts[i] += counts[i-1];
}
for (int i = l-1; i >= 0; i--) {
output[counts[subD[i]]-1] = buren[i];
counts[subD[i]]--;
}
return output;
}
public int[] findConflictingNeighbours(int v, int c, boolean conflicts) {
//if conflicts == true => return list of neighbours that have a conflict with node v
//if conflicts == false => return list of neighbours that don't have a conflict with node v
BitSet temp = (BitSet) neighbours.getRow(v).clone();
//temp = alle buren van v (zonder v zelf)
if (conflicts) {
//conflicts = true => we willen alle buren van v waarmee v een conflict heeft
temp.and(newColorSets.getRow(c));
//temp = alle buren van v die in dezelfde kleurklasse als v zitten
} else {
//conflicts = false => we willen de buren waarmee v geen conflict heeft
BitSet kleurC = (BitSet) newColorSets.getRow(c).clone();
kleurC.flip(0, g.getNrVertices());
//keurC bevat nu alle knopen die niet in kleur c zitten
temp.and(kleurC);
//temp bevat alle buren van v die niet in kleurklasse c zitten
}
int[] Neighbours = new int[temp.cardinality()];
int i=0;
for (int j = temp.nextSetBit(0); j >= 0; j = temp.nextSetBit(j+1)) {
// operate on index i here
Neighbours[i] = j;
if (j == Integer.MAX_VALUE) {
break; // or (i+1) would overflow
}
i++;
}
return Neighbours;
}
public int assignUnusedColor(int v) {
//v = node
//voor elke kleur checken of buren van de knoop in de verzameling van die kleur zitten
//indien geen buren in verzameling van een knoop => knoop v toewijzen aan de verzameling van die kleur
//alle kleuren gebruikt door buren van de knoop => return -1
BitSet buren = (BitSet) neighbours.getRow(v).clone();
buren.set(v);
//buren bevat v en zijn buren
BitSet temp = new BitSet(buren.length());
temp.or(buren);
//temp bevat v en zijn buren
int unusedColor = -1;
int i = 0;
while (i < NR_OF_COLORS && unusedColor==-1) {
temp.or(buren);
//temp bevat v en zijn buren
temp.and(newColorSets.getRow(i));
//temp bevat de knopen v en zijn buren die in kleur klasse i zitten
if (temp.cardinality() == 0) unusedColor = i;
//als temp leeg is => kleur i wordt niet gebruikt door v of een van zijn buren
i++;
}
return unusedColor;
}
public void swap(int v1, int v2, int c1, int c2) {
newColorSets.getRow(c1).flip(v1);
newColorSets.getRow(c1).flip(v2);
newColorSets.getRow(c2).flip(v1);
newColorSets.getRow(c2).flip(v2);
}
/***Validator***/
public void validator() {
for (int i = 0; i < g.getNrVertices(); i++) {
BitSet adj = (BitSet) neighbours.getRow(i).clone();
adj.and(bestColoring.getRow(getColor(i, bestColoring)));
if (adj.cardinality() > 0) {
//System.out.println("Invalid Solution");
printColorSets(bestColoring);
//System.out.print(i +"has conflict with: ");
for (int j = adj.nextSetBit(0); j >=0 ; j = adj.nextSetBit(j+1)) {
System.out.print(j+", ");
}
}
}
//System.out.println("Valid Solution");
}
}
|
128466_0 | package me.mattix.the100.commands;
import org.bukkit.Bukkit;
import org.bukkit.Sound;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import me.mattix.the100.GamePlayer;
import me.mattix.the100.Main;
import me.mattix.the100.utils.PlayerUtils;
import me.mattix.the100.utils.TeamsTagsManager;
public class PeopleCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (!(sender instanceof Player)) {
return true;
}
Player player = (Player) sender;
GamePlayer gp = GamePlayer.gamePlayers.get(PlayerUtils.getPlayerName(player.getUniqueId()));
if (gp.isHeda()) {
if (args.length == 0) {
player.sendMessage("§c/people <player> <people>");
return true;
}
if (args.length > 1) {
Player target = Bukkit.getPlayer(args[0]);
String people = args[1];
GamePlayer gpt = GamePlayer.gamePlayers.get(PlayerUtils.getPlayerName(target.getUniqueId()));
Bukkit.getScheduler().runTaskAsynchronously(Main.INSTANCE, () -> {
if (people != null) {
if (target != null && target.isOnline()) {
if (people.equalsIgnoreCase("heda")) {
sendMessage("§6" + target.getName() + " §fest devenu §4Commandant.");
gpt.setHeda(1);
gpt.setPeople("heda");
gpt.setLeader(0);
gpt.setPrefix("§4[Heda] ");
} else if (people.equalsIgnoreCase("flamegarden")) {
sendMessage("§6" + target.getName() + " §fest devenu §cLe Gardien de la Flamme.");
// msg de bienvenue
target.sendMessage(" ");
target.sendMessage("§fVous êtes désormais gardien de la flamme !");
target.sendMessage("§bVotre rôle est de protéger la flamme, objet sacré où résident tous les esprits des précédents commandants.");
target.sendMessage("§cVous devez dévouer votre vie à la flamme et être la personne la plus proche du commandant.");
target.sendMessage(" ");
target.playSound(target.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1f, 1f);
gpt.setPeople("hedaflame");
gpt.setLeader(0);
gpt.setPrefix("§c[Fleimkepa] ");
} else if (people.equalsIgnoreCase("garde")) {
sendMessage("§6" + target.getName() + " §fest devenu §cLe Garde du Commandant.");
// msg de bienvenue
target.sendMessage(" ");
target.sendMessage("§fVous êtes désormais gardien du commandant !");
target.sendMessage("§bVotre rôle est de protéger le commandant, de se sacrifier pour lui et de lui obéir.");
target.sendMessage("§cVous devez dévouer votre vie au commandant et lui faire honneur.");
target.sendMessage(" ");
target.playSound(target.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1f, 1f);
gpt.setPeople("hedagarde");
gpt.setLeader(0);
gpt.setPrefix("§c[Garde] ");
} else if (people.equalsIgnoreCase("trikru")) {
sendMessage("§6" + target.getName() + " §fest devenu §6Trikru.");
// msg de bienvenue
target.sendMessage(" ");
target.sendMessage("§fVous êtes désormais Trikru !");
target.sendMessage("§bVous devez respecter absolument votre chef. Lui désobéir pourrait vous coûter la vie ou même un bannissement du clan."
+ " Votre village a été détruite par le Mont Weather. Vous pouvez soit reconstruire tout votre le village, soit vous installer ailleurs.");
target.sendMessage("§cVous devez être fidèle à votre clan, être utile, efficace et donner le meilleur de vous même.");
target.sendMessage(" ");
target.playSound(target.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1f, 1f);
gpt.setPeople("trikru");
gpt.setLeader(0);
gpt.setPrefix("§6[Trikru] ");
} else if (people.equalsIgnoreCase("azgeda")) {
sendMessage("§6" + target.getName() + " §fest devenu §bAzgeda.");
// msg de bienvenue
target.sendMessage(" ");
target.sendMessage("§fVous êtes désormais Azgeda !");
target.sendMessage("§bVous devez respecter absolument votre chef. Lui désobéir pourrait vous coûter la vie ou même un bannissement du clan."
+ " Vous n'a pas pas de village. Il faut tout construire. Votre espace se situe dans les espace gelés ! Vous manier à la perfection les arcs.");
target.sendMessage("§cVous devez être fidèle à votre clan, être utile, efficace et donner le meilleur de vous même.");
target.sendMessage(" ");
target.playSound(target.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1f, 1f);
gpt.setPeople("azgeda");
gpt.setLeader(0);
gpt.setPrefix("§b[Azgeda] ");
} else if (people.equalsIgnoreCase("skaikru")) {
sendMessage("§6" + target.getName() + " §fest devenu §eSkaikru.");
target.sendMessage(" ");
target.sendMessage("§fVous êtes désormais Skaikru !");
target.sendMessage("§bVous devez respecter absolument votre Chancelier. Lui désobéir pourrait vous coûter la vie ou même un bannissement du clan."
+ " Votre village est les restes du crash ce la station de l'Arche. Il faut redonner vie à ce village. Y'a du boulot !");
target.sendMessage("§cVous devez être fidèle à votre clan, être utile, efficace et donner le meilleur de vous même.");
target.sendMessage(" ");
target.playSound(target.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1f, 1f);
gpt.setPeople("skaikru");
gpt.setLeader(0);
gpt.setPrefix("§e[Skaikru] ");
} else if (people.equalsIgnoreCase("Trishanakru")) {
sendMessage("§6" + target.getName() + " §fest devenu §2Trishanakru.");
target.sendMessage(" ");
target.sendMessage("§fVous êtes désormais Trishanakru !");
target.sendMessage("§bVous devez respecter absolument votre chef. Lui désobéir pourrait vous coûter la vie ou même un bannissement du clan."
+ " Votre clan a été divisé par le précédent commandant. A vous de vous installer là où bon vous semble et faire mieux qu'avant.");
target.sendMessage("§cVous devez être fidèle à votre clan, être utile, efficace et donner le meilleur de vous même.");
target.sendMessage(" ");
target.playSound(target.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1f, 1f);
gpt.setPeople("trishanakru");
gpt.setLeader(0);
gpt.setPrefix("§2[Trisha] ");
} else if (people.equalsIgnoreCase("Trishanakruchef")) {
sendMessage("§6" + target.getName() + " §fest devenu §2Chef des Trishanakru.");
target.sendMessage(" ");
target.sendMessage("§fVous êtes désormais le Chef des Trishanakru !");
target.sendMessage("§bDiriger votre clan honorablement. Respecter vos coutumes. Protéger votre peuple. Rebâtissez un réel avenir pour eux.");
target.sendMessage("§cVous devez être fidèle à votre clan, être utile, efficace et donner le meilleur de vous même.");
target.sendMessage(" ");
target.playSound(target.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1f, 1f);
gpt.setPeople("trishanakru");
gpt.setLeader(1);
gpt.setPrefix("§2[C.Trisha] ");
} else if (people.equalsIgnoreCase("trikruchef")) {
sendMessage("§6" + target.getName() + " §fest devenu §6Chef des Trikru.");
target.sendMessage(" ");
target.sendMessage("§fVous êtes désormais le Chef des Trikru !");
target.sendMessage("§bDiriger votre clan honorablement. Respecter vos coutumes. Protéger votre peuple. Rebâtissez un réel avenir pour eux.");
target.sendMessage("§cVous devez être fidèle à votre clan, être utile, efficace et donner le meilleur de vous même.");
target.sendMessage(" ");
target.playSound(target.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1f, 1f);
gpt.setPeople("trikru");
gpt.setLeader(1);
gpt.setPrefix("§6[C.Trikru] ");
} else if (people.equalsIgnoreCase("azgedachef")) {
sendMessage("§6" + target.getName() + " §fest devenu §bChef des Azgeda.");
target.sendMessage(" ");
target.sendMessage("§fVous êtes désormais le Chef des Azgedas !");
target.sendMessage("§bDiriger votre clan honorablement. Respecter vos coutumes. Protéger votre peuple. Rebâtissez un réel avenir pour eux.");
target.sendMessage("§cVous devez être fidèle à votre clan, être utile, efficace et donner le meilleur de vous même.");
target.sendMessage(" ");
target.playSound(target.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1f, 1f);
gpt.setPeople("azgeda");
gpt.setLeader(1);
gpt.setPrefix("§b[C.Azgeda] ");
} else if (people.equalsIgnoreCase("skaikruchef")) {
TeamsTagsManager.setNameTag(target, "§c§5Admin", "§e[C.Skaikru] ", "");
sendMessage("§6" + target.getName() + " §fest devenu §eChancelier des Skaikru.");
target.sendMessage(" ");
target.sendMessage("§fVous êtes désormais Chancelier du peuple du ciel (Skaikru) !");
target.sendMessage("§bDiriger votre clan honorablement. Respecter vos coutumes. Protéger votre peuple. Rebâtissez un réel avenir pour eux.");
target.sendMessage("§cVous devez être fidèle à votre clan, être utile, efficace et donner le meilleur de vous même.");
target.sendMessage(" ");
target.playSound(target.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1f, 1f);
gpt.setPeople("skaikru");
gpt.setLeader(1);
gpt.setPrefix("§e[C.Skaikru] ");
} else if (people.equalsIgnoreCase("none")) {
sendMessage("§6" + target.getName() + " §fa été rétrogradé.");
gpt.setPeople("none");
gpt.setLeader(0);
gpt.setPrefix("§f");
}
}
}
});
}
} else {
player.sendMessage("§cVous n'avez pas la permission d'utiliser cette commande.");
}
return true;
}
private final void sendMessage(String msg) {
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(msg);
}
}
} | MattiXOfficial/The100 | src/main/java/me/mattix/the100/commands/PeopleCommand.java | 3,805 | // msg de bienvenue | line_comment | nl | package me.mattix.the100.commands;
import org.bukkit.Bukkit;
import org.bukkit.Sound;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import me.mattix.the100.GamePlayer;
import me.mattix.the100.Main;
import me.mattix.the100.utils.PlayerUtils;
import me.mattix.the100.utils.TeamsTagsManager;
public class PeopleCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (!(sender instanceof Player)) {
return true;
}
Player player = (Player) sender;
GamePlayer gp = GamePlayer.gamePlayers.get(PlayerUtils.getPlayerName(player.getUniqueId()));
if (gp.isHeda()) {
if (args.length == 0) {
player.sendMessage("§c/people <player> <people>");
return true;
}
if (args.length > 1) {
Player target = Bukkit.getPlayer(args[0]);
String people = args[1];
GamePlayer gpt = GamePlayer.gamePlayers.get(PlayerUtils.getPlayerName(target.getUniqueId()));
Bukkit.getScheduler().runTaskAsynchronously(Main.INSTANCE, () -> {
if (people != null) {
if (target != null && target.isOnline()) {
if (people.equalsIgnoreCase("heda")) {
sendMessage("§6" + target.getName() + " §fest devenu §4Commandant.");
gpt.setHeda(1);
gpt.setPeople("heda");
gpt.setLeader(0);
gpt.setPrefix("§4[Heda] ");
} else if (people.equalsIgnoreCase("flamegarden")) {
sendMessage("§6" + target.getName() + " §fest devenu §cLe Gardien de la Flamme.");
// msg de<SUF>
target.sendMessage(" ");
target.sendMessage("§fVous êtes désormais gardien de la flamme !");
target.sendMessage("§bVotre rôle est de protéger la flamme, objet sacré où résident tous les esprits des précédents commandants.");
target.sendMessage("§cVous devez dévouer votre vie à la flamme et être la personne la plus proche du commandant.");
target.sendMessage(" ");
target.playSound(target.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1f, 1f);
gpt.setPeople("hedaflame");
gpt.setLeader(0);
gpt.setPrefix("§c[Fleimkepa] ");
} else if (people.equalsIgnoreCase("garde")) {
sendMessage("§6" + target.getName() + " §fest devenu §cLe Garde du Commandant.");
// msg de bienvenue
target.sendMessage(" ");
target.sendMessage("§fVous êtes désormais gardien du commandant !");
target.sendMessage("§bVotre rôle est de protéger le commandant, de se sacrifier pour lui et de lui obéir.");
target.sendMessage("§cVous devez dévouer votre vie au commandant et lui faire honneur.");
target.sendMessage(" ");
target.playSound(target.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1f, 1f);
gpt.setPeople("hedagarde");
gpt.setLeader(0);
gpt.setPrefix("§c[Garde] ");
} else if (people.equalsIgnoreCase("trikru")) {
sendMessage("§6" + target.getName() + " §fest devenu §6Trikru.");
// msg de bienvenue
target.sendMessage(" ");
target.sendMessage("§fVous êtes désormais Trikru !");
target.sendMessage("§bVous devez respecter absolument votre chef. Lui désobéir pourrait vous coûter la vie ou même un bannissement du clan."
+ " Votre village a été détruite par le Mont Weather. Vous pouvez soit reconstruire tout votre le village, soit vous installer ailleurs.");
target.sendMessage("§cVous devez être fidèle à votre clan, être utile, efficace et donner le meilleur de vous même.");
target.sendMessage(" ");
target.playSound(target.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1f, 1f);
gpt.setPeople("trikru");
gpt.setLeader(0);
gpt.setPrefix("§6[Trikru] ");
} else if (people.equalsIgnoreCase("azgeda")) {
sendMessage("§6" + target.getName() + " §fest devenu §bAzgeda.");
// msg de bienvenue
target.sendMessage(" ");
target.sendMessage("§fVous êtes désormais Azgeda !");
target.sendMessage("§bVous devez respecter absolument votre chef. Lui désobéir pourrait vous coûter la vie ou même un bannissement du clan."
+ " Vous n'a pas pas de village. Il faut tout construire. Votre espace se situe dans les espace gelés ! Vous manier à la perfection les arcs.");
target.sendMessage("§cVous devez être fidèle à votre clan, être utile, efficace et donner le meilleur de vous même.");
target.sendMessage(" ");
target.playSound(target.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1f, 1f);
gpt.setPeople("azgeda");
gpt.setLeader(0);
gpt.setPrefix("§b[Azgeda] ");
} else if (people.equalsIgnoreCase("skaikru")) {
sendMessage("§6" + target.getName() + " §fest devenu §eSkaikru.");
target.sendMessage(" ");
target.sendMessage("§fVous êtes désormais Skaikru !");
target.sendMessage("§bVous devez respecter absolument votre Chancelier. Lui désobéir pourrait vous coûter la vie ou même un bannissement du clan."
+ " Votre village est les restes du crash ce la station de l'Arche. Il faut redonner vie à ce village. Y'a du boulot !");
target.sendMessage("§cVous devez être fidèle à votre clan, être utile, efficace et donner le meilleur de vous même.");
target.sendMessage(" ");
target.playSound(target.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1f, 1f);
gpt.setPeople("skaikru");
gpt.setLeader(0);
gpt.setPrefix("§e[Skaikru] ");
} else if (people.equalsIgnoreCase("Trishanakru")) {
sendMessage("§6" + target.getName() + " §fest devenu §2Trishanakru.");
target.sendMessage(" ");
target.sendMessage("§fVous êtes désormais Trishanakru !");
target.sendMessage("§bVous devez respecter absolument votre chef. Lui désobéir pourrait vous coûter la vie ou même un bannissement du clan."
+ " Votre clan a été divisé par le précédent commandant. A vous de vous installer là où bon vous semble et faire mieux qu'avant.");
target.sendMessage("§cVous devez être fidèle à votre clan, être utile, efficace et donner le meilleur de vous même.");
target.sendMessage(" ");
target.playSound(target.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1f, 1f);
gpt.setPeople("trishanakru");
gpt.setLeader(0);
gpt.setPrefix("§2[Trisha] ");
} else if (people.equalsIgnoreCase("Trishanakruchef")) {
sendMessage("§6" + target.getName() + " §fest devenu §2Chef des Trishanakru.");
target.sendMessage(" ");
target.sendMessage("§fVous êtes désormais le Chef des Trishanakru !");
target.sendMessage("§bDiriger votre clan honorablement. Respecter vos coutumes. Protéger votre peuple. Rebâtissez un réel avenir pour eux.");
target.sendMessage("§cVous devez être fidèle à votre clan, être utile, efficace et donner le meilleur de vous même.");
target.sendMessage(" ");
target.playSound(target.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1f, 1f);
gpt.setPeople("trishanakru");
gpt.setLeader(1);
gpt.setPrefix("§2[C.Trisha] ");
} else if (people.equalsIgnoreCase("trikruchef")) {
sendMessage("§6" + target.getName() + " §fest devenu §6Chef des Trikru.");
target.sendMessage(" ");
target.sendMessage("§fVous êtes désormais le Chef des Trikru !");
target.sendMessage("§bDiriger votre clan honorablement. Respecter vos coutumes. Protéger votre peuple. Rebâtissez un réel avenir pour eux.");
target.sendMessage("§cVous devez être fidèle à votre clan, être utile, efficace et donner le meilleur de vous même.");
target.sendMessage(" ");
target.playSound(target.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1f, 1f);
gpt.setPeople("trikru");
gpt.setLeader(1);
gpt.setPrefix("§6[C.Trikru] ");
} else if (people.equalsIgnoreCase("azgedachef")) {
sendMessage("§6" + target.getName() + " §fest devenu §bChef des Azgeda.");
target.sendMessage(" ");
target.sendMessage("§fVous êtes désormais le Chef des Azgedas !");
target.sendMessage("§bDiriger votre clan honorablement. Respecter vos coutumes. Protéger votre peuple. Rebâtissez un réel avenir pour eux.");
target.sendMessage("§cVous devez être fidèle à votre clan, être utile, efficace et donner le meilleur de vous même.");
target.sendMessage(" ");
target.playSound(target.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1f, 1f);
gpt.setPeople("azgeda");
gpt.setLeader(1);
gpt.setPrefix("§b[C.Azgeda] ");
} else if (people.equalsIgnoreCase("skaikruchef")) {
TeamsTagsManager.setNameTag(target, "§c§5Admin", "§e[C.Skaikru] ", "");
sendMessage("§6" + target.getName() + " §fest devenu §eChancelier des Skaikru.");
target.sendMessage(" ");
target.sendMessage("§fVous êtes désormais Chancelier du peuple du ciel (Skaikru) !");
target.sendMessage("§bDiriger votre clan honorablement. Respecter vos coutumes. Protéger votre peuple. Rebâtissez un réel avenir pour eux.");
target.sendMessage("§cVous devez être fidèle à votre clan, être utile, efficace et donner le meilleur de vous même.");
target.sendMessage(" ");
target.playSound(target.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1f, 1f);
gpt.setPeople("skaikru");
gpt.setLeader(1);
gpt.setPrefix("§e[C.Skaikru] ");
} else if (people.equalsIgnoreCase("none")) {
sendMessage("§6" + target.getName() + " §fa été rétrogradé.");
gpt.setPeople("none");
gpt.setLeader(0);
gpt.setPrefix("§f");
}
}
}
});
}
} else {
player.sendMessage("§cVous n'avez pas la permission d'utiliser cette commande.");
}
return true;
}
private final void sendMessage(String msg) {
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(msg);
}
}
} |
103882_3 | package mazestormer.barcode.action;
import static com.google.common.base.Preconditions.checkNotNull;
import mazestormer.player.Player;
import mazestormer.robot.ControllableRobot;
import mazestormer.robot.Pilot;
import mazestormer.state.State;
import mazestormer.state.StateMachine;
import mazestormer.util.Future;
public class DriveOverSeesawAction extends StateMachine<DriveOverSeesawAction, DriveOverSeesawAction.SeesawState>
implements IAction {
private Player player;
@Override
public Future<?> performAction(Player player) {
checkNotNull(player);
this.player = player;
stop(); // indien nog niet gestopt.
// Resolve when finished
FinishFuture future = new FinishFuture();
addStateListener(future);
// Start from the initial state
start();
transition(SeesawState.ONWARDS);
return future;
}
private ControllableRobot getControllableRobot() {
return (ControllableRobot) player.getRobot();
}
private Pilot getPilot() {
return getControllableRobot().getPilot();
}
/**
* <ol>
* <li>rijd vooruit tot aan een bruin-zwart overgang (van de barcode aan de
* andere kant van de wip)</li>
* <li>informatie over wip aan het ontdekte doolhof toevoegen</li>
* <li>rijd vooruit tot 20 cm over een witte lijn (= eerste bruin-wit
* overgang)</li>
* <li>verwijder eventueel tegels uit de queue</li>
* </ol>
*
* @pre robot staat voor de wip aan de neergelaten kant, hij kijkt naar de
* wip
* @post robot staat op een tegel achter de tegel achter de wip, in het
* midden, en kijkt weg van de wip (tegel achter de wip bevat een
* andere barcode). alle informatie over de gepasseerde tegels staat
* in de observedMaze. de eerste tegel, de tegels van de wip en de
* tegel na de wip staan niet meer in de queue
*/
protected void onwards() {
bindTransition(getPilot().travelComplete(122), // TODO 122 juist?
SeesawState.RESUME_EXPLORING);
}
protected void resumeExploring() {
finish();
}
public enum SeesawState implements State<DriveOverSeesawAction, DriveOverSeesawAction.SeesawState> {
ONWARDS {
@Override
public void execute(DriveOverSeesawAction input) {
input.onwards();
}
},
RESUME_EXPLORING {
@Override
public void execute(DriveOverSeesawAction input) {
input.resumeExploring();
}
};
}
private class FinishFuture extends StateMachine.FinishFuture<SeesawState> {
@Override
public boolean isFinished() {
return true;
}
}
}
| MattiasBuelens/MazeStormer | MazeStormer-PC/src/mazestormer/barcode/action/DriveOverSeesawAction.java | 832 | /**
* <ol>
* <li>rijd vooruit tot aan een bruin-zwart overgang (van de barcode aan de
* andere kant van de wip)</li>
* <li>informatie over wip aan het ontdekte doolhof toevoegen</li>
* <li>rijd vooruit tot 20 cm over een witte lijn (= eerste bruin-wit
* overgang)</li>
* <li>verwijder eventueel tegels uit de queue</li>
* </ol>
*
* @pre robot staat voor de wip aan de neergelaten kant, hij kijkt naar de
* wip
* @post robot staat op een tegel achter de tegel achter de wip, in het
* midden, en kijkt weg van de wip (tegel achter de wip bevat een
* andere barcode). alle informatie over de gepasseerde tegels staat
* in de observedMaze. de eerste tegel, de tegels van de wip en de
* tegel na de wip staan niet meer in de queue
*/ | block_comment | nl | package mazestormer.barcode.action;
import static com.google.common.base.Preconditions.checkNotNull;
import mazestormer.player.Player;
import mazestormer.robot.ControllableRobot;
import mazestormer.robot.Pilot;
import mazestormer.state.State;
import mazestormer.state.StateMachine;
import mazestormer.util.Future;
public class DriveOverSeesawAction extends StateMachine<DriveOverSeesawAction, DriveOverSeesawAction.SeesawState>
implements IAction {
private Player player;
@Override
public Future<?> performAction(Player player) {
checkNotNull(player);
this.player = player;
stop(); // indien nog niet gestopt.
// Resolve when finished
FinishFuture future = new FinishFuture();
addStateListener(future);
// Start from the initial state
start();
transition(SeesawState.ONWARDS);
return future;
}
private ControllableRobot getControllableRobot() {
return (ControllableRobot) player.getRobot();
}
private Pilot getPilot() {
return getControllableRobot().getPilot();
}
/**
* <ol>
<SUF>*/
protected void onwards() {
bindTransition(getPilot().travelComplete(122), // TODO 122 juist?
SeesawState.RESUME_EXPLORING);
}
protected void resumeExploring() {
finish();
}
public enum SeesawState implements State<DriveOverSeesawAction, DriveOverSeesawAction.SeesawState> {
ONWARDS {
@Override
public void execute(DriveOverSeesawAction input) {
input.onwards();
}
},
RESUME_EXPLORING {
@Override
public void execute(DriveOverSeesawAction input) {
input.resumeExploring();
}
};
}
private class FinishFuture extends StateMachine.FinishFuture<SeesawState> {
@Override
public boolean isFinished() {
return true;
}
}
}
|
57446_0 | package Utility;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.naming.event.NamingEvent;
import javax.naming.event.NamingExceptionEvent;
import javax.naming.event.ObjectChangeListener;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.UIManager;
import GUI.AdminPanel;
import GUI.ModeratorPanel;
@SuppressWarnings("serial")
public class MComboBox extends JPanel implements ActionListener, ObjectChangeListener {
private STextField placeholder;
private SButton arrow;
private JPopupMenu pop;
private ArrayList<SButton> buttonList;
private JPanel adpa;
public MComboBox(int width, int height, String[] items, final JPanel ap) {
// Default Component stuff
this.setPreferredSize(new Dimension(width, height));
this.setBackground(new Color(255, 255, 255, 0));
this.setOpaque(false);
this.setLayout(new BorderLayout());
this.adpa = ap;
this.pop = new JPopupMenu();
pop.setLayout(new GridLayout(0, 1));
pop.setOpaque(false);
// ///////// UIManager ///////////
UIManager.put("PopupMenu.background", new Color(255, 255, 255, 0));
UIManager.put("PopupMenu.border", BorderFactory.createEmptyBorder());
// ///////// UIManager ///////////
this.buttonList = new ArrayList<SButton>();
// Adding the items that are given in the String[] parameter
// and setting the first String in the String[] to the currentSelected
// item
if (items != null) {
for (int i = 0; i < items.length; i++) {
if (i == 0) {
this.placeholder = new STextField(items[i]);
}
addItem(items[i]);
}
} else {
if(ap instanceof AdminPanel)
this.placeholder = new STextField("Name");
if(ap instanceof ModeratorPanel)
this.placeholder = new STextField("Word");
this.placeholder.setEditable(true);
this.placeholder.setCustomRounded(true, false, true, false);
}
this.arrow = new SButton("\u25BC", SButton.WHITE, 40, 40);
arrow.setColors(new Color(255, 255, 255), new Color(235, 235, 235),
new Color(220, 220, 220));
arrow.setTextColor(Color.BLACK);
arrow.addActionListener(this);
arrow.setCustomRounded(false, true, false, true);
this.add(placeholder, BorderLayout.CENTER);
this.add(arrow, BorderLayout.EAST);
this.placeholder.addKeyListener(new KeyListener(){
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {
buttonList = new ArrayList<SButton>();
if(ap instanceof AdminPanel){
pop.removeAll();
ArrayList<String> data = null;
data = DBCommunicator.requestMoreData("SELECT naam FROM account WHERE naam LIKE '"+ placeholder.getText() + "%'");
for (String pl : data) {
addItem(pl);
}
}else if(ap instanceof ModeratorPanel){
pop.removeAll();
ArrayList<String> data = null;
data = DBCommunicator.requestMoreData("SELECT woord FROM woordenboek WHERE woord LIKE '"+ placeholder.getText() + "%'");
for (String pl : data) {
addItem(pl);
}
}
}});
}
public void addItem(String item) {
final SButton s = new SButton(item, Color.WHITE, this.getWidth(),
this.getHeight());
s.setTextColor(new Color(100, 100, 100));
s.setRounded(true);
s.setAlignment(SButton.LEFT);
if(buttonList.isEmpty()) {
s.setCustomRounded(false, false, false, false);
}
else {
buttonList.get(buttonList.size()-1).setCustomRounded(false, false, false, false);
s.setCustomRounded(false, false, true, true);
}
s.setColors(new Color(255, 255, 255), new Color(235, 235, 235),
new Color(220, 220, 220));
s.setPreferredSize(this.getPreferredSize());
s.addActionListener(this);
for (int i = 1; i < buttonList.size(); i++) {
// buttonList.get(i).setRounded(false);
}
buttonList.add(s);
pop.add(s);
s.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
placeholder.setText(s.getName());
if(adpa instanceof AdminPanel) ((AdminPanel) adpa).update();
}
});
}
public void actionPerformed(ActionEvent e) {
pop.show(this, 0, this.getHeight());
if(e.getSource().equals(arrow)){
arrow.setCustomRounded(false, true, false, false);
placeholder.setCustomRounded(true, false, false, false);
}
for (SButton s : buttonList) {
if (e.getSource().equals(s)) {
placeholder.setText(s.getName());
pop.setVisible(false);
revalidate();
}
}
repaint();
}
public String getSelectedItem() {
return placeholder.getText();
}
public STextField getField(){
return placeholder;
}
public ArrayList<SButton> getButtons(){
return buttonList;
}
@Override
public void namingExceptionThrown(NamingExceptionEvent evt) {
}
@Override
public void objectChanged(NamingEvent evt) {
}
} | MaxNijholt/WordFeud | WordFeud/src/Utility/MComboBox.java | 1,745 | // Default Component stuff | line_comment | nl | package Utility;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.naming.event.NamingEvent;
import javax.naming.event.NamingExceptionEvent;
import javax.naming.event.ObjectChangeListener;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.UIManager;
import GUI.AdminPanel;
import GUI.ModeratorPanel;
@SuppressWarnings("serial")
public class MComboBox extends JPanel implements ActionListener, ObjectChangeListener {
private STextField placeholder;
private SButton arrow;
private JPopupMenu pop;
private ArrayList<SButton> buttonList;
private JPanel adpa;
public MComboBox(int width, int height, String[] items, final JPanel ap) {
// Default Component<SUF>
this.setPreferredSize(new Dimension(width, height));
this.setBackground(new Color(255, 255, 255, 0));
this.setOpaque(false);
this.setLayout(new BorderLayout());
this.adpa = ap;
this.pop = new JPopupMenu();
pop.setLayout(new GridLayout(0, 1));
pop.setOpaque(false);
// ///////// UIManager ///////////
UIManager.put("PopupMenu.background", new Color(255, 255, 255, 0));
UIManager.put("PopupMenu.border", BorderFactory.createEmptyBorder());
// ///////// UIManager ///////////
this.buttonList = new ArrayList<SButton>();
// Adding the items that are given in the String[] parameter
// and setting the first String in the String[] to the currentSelected
// item
if (items != null) {
for (int i = 0; i < items.length; i++) {
if (i == 0) {
this.placeholder = new STextField(items[i]);
}
addItem(items[i]);
}
} else {
if(ap instanceof AdminPanel)
this.placeholder = new STextField("Name");
if(ap instanceof ModeratorPanel)
this.placeholder = new STextField("Word");
this.placeholder.setEditable(true);
this.placeholder.setCustomRounded(true, false, true, false);
}
this.arrow = new SButton("\u25BC", SButton.WHITE, 40, 40);
arrow.setColors(new Color(255, 255, 255), new Color(235, 235, 235),
new Color(220, 220, 220));
arrow.setTextColor(Color.BLACK);
arrow.addActionListener(this);
arrow.setCustomRounded(false, true, false, true);
this.add(placeholder, BorderLayout.CENTER);
this.add(arrow, BorderLayout.EAST);
this.placeholder.addKeyListener(new KeyListener(){
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {
buttonList = new ArrayList<SButton>();
if(ap instanceof AdminPanel){
pop.removeAll();
ArrayList<String> data = null;
data = DBCommunicator.requestMoreData("SELECT naam FROM account WHERE naam LIKE '"+ placeholder.getText() + "%'");
for (String pl : data) {
addItem(pl);
}
}else if(ap instanceof ModeratorPanel){
pop.removeAll();
ArrayList<String> data = null;
data = DBCommunicator.requestMoreData("SELECT woord FROM woordenboek WHERE woord LIKE '"+ placeholder.getText() + "%'");
for (String pl : data) {
addItem(pl);
}
}
}});
}
public void addItem(String item) {
final SButton s = new SButton(item, Color.WHITE, this.getWidth(),
this.getHeight());
s.setTextColor(new Color(100, 100, 100));
s.setRounded(true);
s.setAlignment(SButton.LEFT);
if(buttonList.isEmpty()) {
s.setCustomRounded(false, false, false, false);
}
else {
buttonList.get(buttonList.size()-1).setCustomRounded(false, false, false, false);
s.setCustomRounded(false, false, true, true);
}
s.setColors(new Color(255, 255, 255), new Color(235, 235, 235),
new Color(220, 220, 220));
s.setPreferredSize(this.getPreferredSize());
s.addActionListener(this);
for (int i = 1; i < buttonList.size(); i++) {
// buttonList.get(i).setRounded(false);
}
buttonList.add(s);
pop.add(s);
s.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
placeholder.setText(s.getName());
if(adpa instanceof AdminPanel) ((AdminPanel) adpa).update();
}
});
}
public void actionPerformed(ActionEvent e) {
pop.show(this, 0, this.getHeight());
if(e.getSource().equals(arrow)){
arrow.setCustomRounded(false, true, false, false);
placeholder.setCustomRounded(true, false, false, false);
}
for (SButton s : buttonList) {
if (e.getSource().equals(s)) {
placeholder.setText(s.getName());
pop.setVisible(false);
revalidate();
}
}
repaint();
}
public String getSelectedItem() {
return placeholder.getText();
}
public STextField getField(){
return placeholder;
}
public ArrayList<SButton> getButtons(){
return buttonList;
}
@Override
public void namingExceptionThrown(NamingExceptionEvent evt) {
}
@Override
public void objectChanged(NamingEvent evt) {
}
} |
165279_4 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ui.controller;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import ui.VIVESbike;
/**
* FXML Controller class
*
* @author Martijn
*/
public class StartschermController implements Initializable {
// referentie naar VIVESbike (main)
private VIVESbike parent;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
/**
* Referentie naar parent (start) instellen
*
* @param parent referentie naar de runnable class die alle oproepen naar de
* schermen bestuurt
*/
public void setParent(VIVESbike p) {
parent = p;
}
}
| MaximilianCoutuer/vivesbike | src/ui/controller/StartschermController.java | 280 | /**
* Referentie naar parent (start) instellen
*
* @param parent referentie naar de runnable class die alle oproepen naar de
* schermen bestuurt
*/ | block_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ui.controller;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import ui.VIVESbike;
/**
* FXML Controller class
*
* @author Martijn
*/
public class StartschermController implements Initializable {
// referentie naar VIVESbike (main)
private VIVESbike parent;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
/**
* Referentie naar parent<SUF>*/
public void setParent(VIVESbike p) {
parent = p;
}
}
|
105238_1 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.pepsoft.worldpainter.layers.exporters;
import org.pepsoft.minecraft.Chunk;
import org.pepsoft.util.PerlinNoise;
import org.pepsoft.worldpainter.Dimension;
import org.pepsoft.worldpainter.Tile;
import org.pepsoft.worldpainter.exporting.AbstractLayerExporter;
import org.pepsoft.worldpainter.exporting.FirstPassLayerExporter;
import org.pepsoft.worldpainter.layers.Resources;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import static org.pepsoft.minecraft.Constants.*;
import static org.pepsoft.worldpainter.Constants.*;
/**
*
* @author pepijn
*/
public class ResourcesExporter extends AbstractLayerExporter<Resources> implements FirstPassLayerExporter {
public ResourcesExporter() {
super(Resources.INSTANCE);
}
@Override
public void setSettings(ExporterSettings settings) {
super.setSettings(settings);
ResourcesExporterSettings resourcesSettings = (ResourcesExporterSettings) getSettings();
if (resourcesSettings != null) {
noiseGenerators = new PerlinNoise[256];
seedOffsets = new long[256];
minLevels = new int[256];
maxLevels = new int[256];
chances = new float[256][16];
activeOreCount = 0;
for (int blockType: resourcesSettings.getBlockTypes()) {
if (resourcesSettings.getChance(blockType) == 0) {
continue;
}
activeOreCount++;
noiseGenerators[blockType] = new PerlinNoise(0);
seedOffsets[blockType] = resourcesSettings.getSeedOffset(blockType);
minLevels[blockType] = resourcesSettings.getMinLevel(blockType);
maxLevels[blockType] = resourcesSettings.getMaxLevel(blockType);
chances[blockType] = new float[16];
for (int i = 0; i < 16; i++) {
chances[blockType][i] = PerlinNoise.getLevelForPromillage(Math.min(resourcesSettings.getChance(blockType) * i / 8f, 1000f));
}
}
}
}
@Override
public void render(Dimension dimension, Tile tile, Chunk chunk) {
ResourcesExporterSettings settings = (ResourcesExporterSettings) getSettings();
if (settings == null) {
settings = new ResourcesExporterSettings(dimension.getMaxHeight());
setSettings(settings);
}
final int minimumLevel = settings.getMinimumLevel();
final int xOffset = (chunk.getxPos() & 7) << 4;
final int zOffset = (chunk.getzPos() & 7) << 4;
final long seed = dimension.getSeed();
final int[] oreTypes = new int[activeOreCount];
final int maxY = dimension.getMaxHeight() - 1;
int i = 0;
for (int oreType: settings.getBlockTypes()) {
if (settings.getChance(oreType) == 0) {
continue;
}
oreTypes[i++] = oreType;
}
if ((currentSeed == 0) || (currentSeed != seed)) {
for (int blockType: oreTypes) {
noiseGenerators[blockType].setSeed(seed + seedOffsets[blockType]);
}
}
// int[] counts = new int[256];
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
final int localX = xOffset + x, localY = zOffset + z;
final int worldX = tile.getX() * TILE_SIZE + localX, worldY = tile.getY() * TILE_SIZE + localY;
if (tile.getBitLayerValue(org.pepsoft.worldpainter.layers.Void.INSTANCE, localX, localY)) {
continue;
}
final int resourcesValue = Math.max(minimumLevel, tile.getLayerValue(Resources.INSTANCE, localX, localY));
if (resourcesValue > 0) {
final int terrainheight = tile.getIntHeight(localX, localY);
final double dx = worldX / TINY_BLOBS, dy = worldY / TINY_BLOBS;
final double dirtX = worldX / SMALL_BLOBS, dirtY = worldY / SMALL_BLOBS;
// Capping to maxY really shouldn't be necessary, but we've
// had several reports from the wild of this going higher
// than maxHeight, so there must be some obscure way in
// which the terrainHeight can be raised too high
for (int y = Math.min(terrainheight - dimension.getTopLayerDepth(worldX, worldY, terrainheight), maxY); y > 0; y--) {
final double dz = y / TINY_BLOBS;
final double dirtZ = y / SMALL_BLOBS;
for (int oreType: oreTypes) {
final float chance = chances[oreType][resourcesValue];
if ((chance <= 0.5f)
&& (y >= minLevels[oreType])
&& (y <= maxLevels[oreType])
&& (((oreType == BLK_DIRT) || (oreType == BLK_GRAVEL))
? (noiseGenerators[oreType].getPerlinNoise(dirtX, dirtY, dirtZ) >= chance)
: (noiseGenerators[oreType].getPerlinNoise(dx, dy, dz) >= chance))) {
// counts[oreType]++;
chunk.setBlockType(x, y, z, oreType);
chunk.setDataValue(x, y, z, 0);
break;
}
}
}
}
}
}
// System.out.println("Tile " + tile.getX() + "," + tile.getY());
// for (i = 0; i < 256; i++) {
// if (counts[i] > 0) {
// System.out.printf("Exported %6d of ore type %3d%n", counts[i], i);
// }
// }
// System.out.println();
}
// TODO: resource frequenties onderzoeken met Statistics tool!
private PerlinNoise[] noiseGenerators;
private long[] seedOffsets;
private int[] minLevels, maxLevels;
private float[][] chances;
private int activeOreCount;
private long currentSeed;
public static class ResourcesExporterSettings implements ExporterSettings {
public ResourcesExporterSettings(int maxHeight) {
this(maxHeight, false);
}
public ResourcesExporterSettings(int maxHeight, boolean nether) {
minLevels.put(BLK_GOLD_ORE, 0);
minLevels.put(BLK_IRON_ORE, 0);
minLevels.put(BLK_COAL, 0);
minLevels.put(BLK_LAPIS_LAZULI_ORE, 0);
minLevels.put(BLK_DIAMOND_ORE, 0);
minLevels.put(BLK_REDSTONE_ORE, 0);
minLevels.put(BLK_WATER, 0);
minLevels.put(BLK_LAVA, 0);
minLevels.put(BLK_DIRT, 0);
minLevels.put(BLK_GRAVEL, 0);
minLevels.put(BLK_EMERALD_ORE, 0);
minLevels.put(BLK_QUARTZ_ORE, 0);
maxLevels.put(BLK_GOLD_ORE, 31);
maxLevels.put(BLK_IRON_ORE, 63);
maxLevels.put(BLK_COAL, maxHeight - 1);
maxLevels.put(BLK_LAPIS_LAZULI_ORE, 31);
maxLevels.put(BLK_DIAMOND_ORE, 15);
maxLevels.put(BLK_REDSTONE_ORE, 15);
maxLevels.put(BLK_WATER, maxHeight - 1);
maxLevels.put(BLK_LAVA, 15);
maxLevels.put(BLK_DIRT, maxHeight - 1);
maxLevels.put(BLK_GRAVEL, maxHeight - 1);
maxLevels.put(BLK_EMERALD_ORE, 31);
maxLevels.put(BLK_QUARTZ_ORE, maxHeight - 1);
if (nether) {
chances.put(BLK_GOLD_ORE, 0);
chances.put(BLK_IRON_ORE, 0);
chances.put(BLK_COAL, 0);
chances.put(BLK_LAPIS_LAZULI_ORE, 0);
chances.put(BLK_DIAMOND_ORE, 0);
chances.put(BLK_REDSTONE_ORE, 0);
chances.put(BLK_WATER, 0);
chances.put(BLK_LAVA, 0);
chances.put(BLK_DIRT, 0);
chances.put(BLK_GRAVEL, 0);
chances.put(BLK_EMERALD_ORE, 0);
if (maxHeight != DEFAULT_MAX_HEIGHT_2) {
chances.put(BLK_QUARTZ_ORE, 0);
} else {
chances.put(BLK_QUARTZ_ORE, 6);
}
} else {
chances.put(BLK_GOLD_ORE, 1);
chances.put(BLK_IRON_ORE, 6);
chances.put(BLK_COAL, 10);
chances.put(BLK_LAPIS_LAZULI_ORE, 1);
chances.put(BLK_DIAMOND_ORE, 1);
chances.put(BLK_REDSTONE_ORE, 8);
chances.put(BLK_WATER, 1);
chances.put(BLK_LAVA, 2);
chances.put(BLK_DIRT, 57);
chances.put(BLK_GRAVEL, 28);
if (maxHeight != DEFAULT_MAX_HEIGHT_2) {
chances.put(BLK_EMERALD_ORE, 0);
} else {
chances.put(BLK_EMERALD_ORE, 1);
}
chances.put(BLK_QUARTZ_ORE, 0);
}
Random random = new Random();
for (int blockType: maxLevels.keySet()) {
seedOffsets.put(blockType, random.nextLong());
}
}
private ResourcesExporterSettings(int minimumLevel, Map<Integer, Integer> minLevels, Map<Integer, Integer> maxLevels, Map<Integer, Integer> chances, Map<Integer, Long> seedOffsets) {
this.minimumLevel = minimumLevel;
this.minLevels.putAll(minLevels);
this.maxLevels.putAll(maxLevels);
this.chances.putAll(chances);
this.seedOffsets.putAll(seedOffsets);
}
@Override
public boolean isApplyEverywhere() {
return minimumLevel > 0;
}
public int getMinimumLevel() {
return minimumLevel;
}
public void setMinimumLevel(int minimumLevel) {
this.minimumLevel = minimumLevel;
}
public Set<Integer> getBlockTypes() {
return maxLevels.keySet();
}
public int getMinLevel(int blockType) {
return minLevels.get(blockType);
}
public void setMinLevel(int blockType, int minLevel) {
minLevels.put(blockType, minLevel);
}
public int getMaxLevel(int blockType) {
return maxLevels.get(blockType);
}
public void setMaxLevel(int blockType, int maxLevel) {
maxLevels.put(blockType, maxLevel);
}
public int getChance(int blockType) {
return chances.get(blockType);
}
public void setChance(int blockType, int chance) {
chances.put(blockType, chance);
}
public long getSeedOffset(int blockType) {
return seedOffsets.get(blockType);
}
@Override
public Resources getLayer() {
return Resources.INSTANCE;
}
@Override
public ResourcesExporterSettings clone() {
return new ResourcesExporterSettings(minimumLevel, minLevels, maxLevels, chances, seedOffsets);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
// Fix static water and lava
if (! maxLevels.containsKey(BLK_WATER)) {
logger.warn("Fixing water and lava settings");
maxLevels.put(BLK_WATER, maxLevels.get(BLK_STATIONARY_WATER));
chances.put(BLK_WATER, chances.get(BLK_STATIONARY_WATER));
seedOffsets.put(BLK_WATER, seedOffsets.get(BLK_STATIONARY_WATER));
maxLevels.put(BLK_LAVA, maxLevels.get(BLK_STATIONARY_LAVA));
chances.put(BLK_LAVA, chances.get(BLK_STATIONARY_LAVA));
seedOffsets.put(BLK_LAVA, seedOffsets.get(BLK_STATIONARY_LAVA));
maxLevels.remove(BLK_STATIONARY_WATER);
chances.remove(BLK_STATIONARY_WATER);
seedOffsets.remove(BLK_STATIONARY_WATER);
maxLevels.remove(BLK_STATIONARY_LAVA);
chances.remove(BLK_STATIONARY_LAVA);
seedOffsets.remove(BLK_STATIONARY_LAVA);
}
if (! maxLevels.containsKey(BLK_EMERALD_ORE)) {
maxLevels.put(BLK_EMERALD_ORE, 31);
chances.put(BLK_EMERALD_ORE, 0);
}
Random random = new Random();
if (! seedOffsets.containsKey(BLK_EMERALD_ORE)) {
seedOffsets.put(BLK_EMERALD_ORE, random.nextLong());
}
if (minLevels == null) {
minLevels = new HashMap<>();
for (int blockType: maxLevels.keySet()) {
minLevels.put(blockType, 0);
}
}
if (! minLevels.containsKey(BLK_QUARTZ_ORE)) {
minLevels.put(BLK_QUARTZ_ORE, 0);
maxLevels.put(BLK_QUARTZ_ORE, 255);
chances.put(BLK_QUARTZ_ORE, 0);
seedOffsets.put(BLK_QUARTZ_ORE, random.nextLong());
}
}
private int minimumLevel = 8;
private final Map<Integer, Integer> maxLevels = new HashMap<>();
private final Map<Integer, Integer> chances = new HashMap<>();
private final Map<Integer, Long> seedOffsets = new HashMap<>();
private Map<Integer, Integer> minLevels = new HashMap<>();
private static final long serialVersionUID = 1L;
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ResourcesExporter.class);
}
} | Maxopoly/WorldPainter | WorldPainter/WPCore/src/main/java/org/pepsoft/worldpainter/layers/exporters/ResourcesExporter.java | 4,424 | /**
*
* @author pepijn
*/ | block_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.pepsoft.worldpainter.layers.exporters;
import org.pepsoft.minecraft.Chunk;
import org.pepsoft.util.PerlinNoise;
import org.pepsoft.worldpainter.Dimension;
import org.pepsoft.worldpainter.Tile;
import org.pepsoft.worldpainter.exporting.AbstractLayerExporter;
import org.pepsoft.worldpainter.exporting.FirstPassLayerExporter;
import org.pepsoft.worldpainter.layers.Resources;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import static org.pepsoft.minecraft.Constants.*;
import static org.pepsoft.worldpainter.Constants.*;
/**
*
* @author pepijn
<SUF>*/
public class ResourcesExporter extends AbstractLayerExporter<Resources> implements FirstPassLayerExporter {
public ResourcesExporter() {
super(Resources.INSTANCE);
}
@Override
public void setSettings(ExporterSettings settings) {
super.setSettings(settings);
ResourcesExporterSettings resourcesSettings = (ResourcesExporterSettings) getSettings();
if (resourcesSettings != null) {
noiseGenerators = new PerlinNoise[256];
seedOffsets = new long[256];
minLevels = new int[256];
maxLevels = new int[256];
chances = new float[256][16];
activeOreCount = 0;
for (int blockType: resourcesSettings.getBlockTypes()) {
if (resourcesSettings.getChance(blockType) == 0) {
continue;
}
activeOreCount++;
noiseGenerators[blockType] = new PerlinNoise(0);
seedOffsets[blockType] = resourcesSettings.getSeedOffset(blockType);
minLevels[blockType] = resourcesSettings.getMinLevel(blockType);
maxLevels[blockType] = resourcesSettings.getMaxLevel(blockType);
chances[blockType] = new float[16];
for (int i = 0; i < 16; i++) {
chances[blockType][i] = PerlinNoise.getLevelForPromillage(Math.min(resourcesSettings.getChance(blockType) * i / 8f, 1000f));
}
}
}
}
@Override
public void render(Dimension dimension, Tile tile, Chunk chunk) {
ResourcesExporterSettings settings = (ResourcesExporterSettings) getSettings();
if (settings == null) {
settings = new ResourcesExporterSettings(dimension.getMaxHeight());
setSettings(settings);
}
final int minimumLevel = settings.getMinimumLevel();
final int xOffset = (chunk.getxPos() & 7) << 4;
final int zOffset = (chunk.getzPos() & 7) << 4;
final long seed = dimension.getSeed();
final int[] oreTypes = new int[activeOreCount];
final int maxY = dimension.getMaxHeight() - 1;
int i = 0;
for (int oreType: settings.getBlockTypes()) {
if (settings.getChance(oreType) == 0) {
continue;
}
oreTypes[i++] = oreType;
}
if ((currentSeed == 0) || (currentSeed != seed)) {
for (int blockType: oreTypes) {
noiseGenerators[blockType].setSeed(seed + seedOffsets[blockType]);
}
}
// int[] counts = new int[256];
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
final int localX = xOffset + x, localY = zOffset + z;
final int worldX = tile.getX() * TILE_SIZE + localX, worldY = tile.getY() * TILE_SIZE + localY;
if (tile.getBitLayerValue(org.pepsoft.worldpainter.layers.Void.INSTANCE, localX, localY)) {
continue;
}
final int resourcesValue = Math.max(minimumLevel, tile.getLayerValue(Resources.INSTANCE, localX, localY));
if (resourcesValue > 0) {
final int terrainheight = tile.getIntHeight(localX, localY);
final double dx = worldX / TINY_BLOBS, dy = worldY / TINY_BLOBS;
final double dirtX = worldX / SMALL_BLOBS, dirtY = worldY / SMALL_BLOBS;
// Capping to maxY really shouldn't be necessary, but we've
// had several reports from the wild of this going higher
// than maxHeight, so there must be some obscure way in
// which the terrainHeight can be raised too high
for (int y = Math.min(terrainheight - dimension.getTopLayerDepth(worldX, worldY, terrainheight), maxY); y > 0; y--) {
final double dz = y / TINY_BLOBS;
final double dirtZ = y / SMALL_BLOBS;
for (int oreType: oreTypes) {
final float chance = chances[oreType][resourcesValue];
if ((chance <= 0.5f)
&& (y >= minLevels[oreType])
&& (y <= maxLevels[oreType])
&& (((oreType == BLK_DIRT) || (oreType == BLK_GRAVEL))
? (noiseGenerators[oreType].getPerlinNoise(dirtX, dirtY, dirtZ) >= chance)
: (noiseGenerators[oreType].getPerlinNoise(dx, dy, dz) >= chance))) {
// counts[oreType]++;
chunk.setBlockType(x, y, z, oreType);
chunk.setDataValue(x, y, z, 0);
break;
}
}
}
}
}
}
// System.out.println("Tile " + tile.getX() + "," + tile.getY());
// for (i = 0; i < 256; i++) {
// if (counts[i] > 0) {
// System.out.printf("Exported %6d of ore type %3d%n", counts[i], i);
// }
// }
// System.out.println();
}
// TODO: resource frequenties onderzoeken met Statistics tool!
private PerlinNoise[] noiseGenerators;
private long[] seedOffsets;
private int[] minLevels, maxLevels;
private float[][] chances;
private int activeOreCount;
private long currentSeed;
public static class ResourcesExporterSettings implements ExporterSettings {
public ResourcesExporterSettings(int maxHeight) {
this(maxHeight, false);
}
public ResourcesExporterSettings(int maxHeight, boolean nether) {
minLevels.put(BLK_GOLD_ORE, 0);
minLevels.put(BLK_IRON_ORE, 0);
minLevels.put(BLK_COAL, 0);
minLevels.put(BLK_LAPIS_LAZULI_ORE, 0);
minLevels.put(BLK_DIAMOND_ORE, 0);
minLevels.put(BLK_REDSTONE_ORE, 0);
minLevels.put(BLK_WATER, 0);
minLevels.put(BLK_LAVA, 0);
minLevels.put(BLK_DIRT, 0);
minLevels.put(BLK_GRAVEL, 0);
minLevels.put(BLK_EMERALD_ORE, 0);
minLevels.put(BLK_QUARTZ_ORE, 0);
maxLevels.put(BLK_GOLD_ORE, 31);
maxLevels.put(BLK_IRON_ORE, 63);
maxLevels.put(BLK_COAL, maxHeight - 1);
maxLevels.put(BLK_LAPIS_LAZULI_ORE, 31);
maxLevels.put(BLK_DIAMOND_ORE, 15);
maxLevels.put(BLK_REDSTONE_ORE, 15);
maxLevels.put(BLK_WATER, maxHeight - 1);
maxLevels.put(BLK_LAVA, 15);
maxLevels.put(BLK_DIRT, maxHeight - 1);
maxLevels.put(BLK_GRAVEL, maxHeight - 1);
maxLevels.put(BLK_EMERALD_ORE, 31);
maxLevels.put(BLK_QUARTZ_ORE, maxHeight - 1);
if (nether) {
chances.put(BLK_GOLD_ORE, 0);
chances.put(BLK_IRON_ORE, 0);
chances.put(BLK_COAL, 0);
chances.put(BLK_LAPIS_LAZULI_ORE, 0);
chances.put(BLK_DIAMOND_ORE, 0);
chances.put(BLK_REDSTONE_ORE, 0);
chances.put(BLK_WATER, 0);
chances.put(BLK_LAVA, 0);
chances.put(BLK_DIRT, 0);
chances.put(BLK_GRAVEL, 0);
chances.put(BLK_EMERALD_ORE, 0);
if (maxHeight != DEFAULT_MAX_HEIGHT_2) {
chances.put(BLK_QUARTZ_ORE, 0);
} else {
chances.put(BLK_QUARTZ_ORE, 6);
}
} else {
chances.put(BLK_GOLD_ORE, 1);
chances.put(BLK_IRON_ORE, 6);
chances.put(BLK_COAL, 10);
chances.put(BLK_LAPIS_LAZULI_ORE, 1);
chances.put(BLK_DIAMOND_ORE, 1);
chances.put(BLK_REDSTONE_ORE, 8);
chances.put(BLK_WATER, 1);
chances.put(BLK_LAVA, 2);
chances.put(BLK_DIRT, 57);
chances.put(BLK_GRAVEL, 28);
if (maxHeight != DEFAULT_MAX_HEIGHT_2) {
chances.put(BLK_EMERALD_ORE, 0);
} else {
chances.put(BLK_EMERALD_ORE, 1);
}
chances.put(BLK_QUARTZ_ORE, 0);
}
Random random = new Random();
for (int blockType: maxLevels.keySet()) {
seedOffsets.put(blockType, random.nextLong());
}
}
private ResourcesExporterSettings(int minimumLevel, Map<Integer, Integer> minLevels, Map<Integer, Integer> maxLevels, Map<Integer, Integer> chances, Map<Integer, Long> seedOffsets) {
this.minimumLevel = minimumLevel;
this.minLevels.putAll(minLevels);
this.maxLevels.putAll(maxLevels);
this.chances.putAll(chances);
this.seedOffsets.putAll(seedOffsets);
}
@Override
public boolean isApplyEverywhere() {
return minimumLevel > 0;
}
public int getMinimumLevel() {
return minimumLevel;
}
public void setMinimumLevel(int minimumLevel) {
this.minimumLevel = minimumLevel;
}
public Set<Integer> getBlockTypes() {
return maxLevels.keySet();
}
public int getMinLevel(int blockType) {
return minLevels.get(blockType);
}
public void setMinLevel(int blockType, int minLevel) {
minLevels.put(blockType, minLevel);
}
public int getMaxLevel(int blockType) {
return maxLevels.get(blockType);
}
public void setMaxLevel(int blockType, int maxLevel) {
maxLevels.put(blockType, maxLevel);
}
public int getChance(int blockType) {
return chances.get(blockType);
}
public void setChance(int blockType, int chance) {
chances.put(blockType, chance);
}
public long getSeedOffset(int blockType) {
return seedOffsets.get(blockType);
}
@Override
public Resources getLayer() {
return Resources.INSTANCE;
}
@Override
public ResourcesExporterSettings clone() {
return new ResourcesExporterSettings(minimumLevel, minLevels, maxLevels, chances, seedOffsets);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
// Fix static water and lava
if (! maxLevels.containsKey(BLK_WATER)) {
logger.warn("Fixing water and lava settings");
maxLevels.put(BLK_WATER, maxLevels.get(BLK_STATIONARY_WATER));
chances.put(BLK_WATER, chances.get(BLK_STATIONARY_WATER));
seedOffsets.put(BLK_WATER, seedOffsets.get(BLK_STATIONARY_WATER));
maxLevels.put(BLK_LAVA, maxLevels.get(BLK_STATIONARY_LAVA));
chances.put(BLK_LAVA, chances.get(BLK_STATIONARY_LAVA));
seedOffsets.put(BLK_LAVA, seedOffsets.get(BLK_STATIONARY_LAVA));
maxLevels.remove(BLK_STATIONARY_WATER);
chances.remove(BLK_STATIONARY_WATER);
seedOffsets.remove(BLK_STATIONARY_WATER);
maxLevels.remove(BLK_STATIONARY_LAVA);
chances.remove(BLK_STATIONARY_LAVA);
seedOffsets.remove(BLK_STATIONARY_LAVA);
}
if (! maxLevels.containsKey(BLK_EMERALD_ORE)) {
maxLevels.put(BLK_EMERALD_ORE, 31);
chances.put(BLK_EMERALD_ORE, 0);
}
Random random = new Random();
if (! seedOffsets.containsKey(BLK_EMERALD_ORE)) {
seedOffsets.put(BLK_EMERALD_ORE, random.nextLong());
}
if (minLevels == null) {
minLevels = new HashMap<>();
for (int blockType: maxLevels.keySet()) {
minLevels.put(blockType, 0);
}
}
if (! minLevels.containsKey(BLK_QUARTZ_ORE)) {
minLevels.put(BLK_QUARTZ_ORE, 0);
maxLevels.put(BLK_QUARTZ_ORE, 255);
chances.put(BLK_QUARTZ_ORE, 0);
seedOffsets.put(BLK_QUARTZ_ORE, random.nextLong());
}
}
private int minimumLevel = 8;
private final Map<Integer, Integer> maxLevels = new HashMap<>();
private final Map<Integer, Integer> chances = new HashMap<>();
private final Map<Integer, Long> seedOffsets = new HashMap<>();
private Map<Integer, Integer> minLevels = new HashMap<>();
private static final long serialVersionUID = 1L;
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ResourcesExporter.class);
}
} |
52525_20 | package main.java.group37.bejeweled.combination;
import main.java.group37.bejeweled.board.Board;
import main.java.group37.bejeweled.board.Tile;
import main.java.group37.bejeweled.combination.Combination.Type;
import java.util.ArrayList;
import java.util.List;
/**
* This class can be used to find the type and tiles of combinations on the board
* at that specific moment.
* @author group37
*/
public class CombinationFinder {
private Board board;
/**
* The constructor for the combinationfinder.
* @param board, the current board.
*/
public CombinationFinder(Board board) {
this.board = board;
}
/**
* This method provides the possibility to set the board.
* @param board, the board to be set.
*/
public void setBoard(Board board) {
this.board = board;
}
/**
* This method provides the possibility to get the board.
*/
public Board getBoard() {
return this.board;
}
/**
* Returns a list, which contains lists with 2 objects: (State,List of tiles),
* eg. (Tile.State.NORMAL,List(t1,t2,t3)).
* This is a list of all the valid combinations on the board at this time.
*/
public List<Combination> getAllCombinationsOnBoard() {
List<Combination> allcombinations = new ArrayList<Combination>();
Combination tile = null;
for (int i = 0; i < board.getWidth(); i++) { //for every tile on the board
for (int j = 0; j < board.getHeight(); j++) {
tile = getSingleCombinationX(board.getTileAt(i,j));
if (!(tile == null)) {
if (!sameCombination(allcombinations, tile)) {
allcombinations.add(tile);
}
}
tile = getSingleCombinationY(board.getTileAt(i,j));
if (!(tile == null)) {
if (!sameCombination(allcombinations, tile)) {
allcombinations.add(tile);
}
}
}
}
return allcombinations;
}
/**
* Sees whether
* @param tile
* makes a valid combination in x direction on the board,
* @return a list with first the state of the combination,
* and second the list of tiles in de combi.
*/
public Combination getSingleCombinationX(Tile tile) {
Combination combi = null;
List<Tile> tiles = new ArrayList<Tile>();
//check x direction
for (int q = tile.getX() + 1; q < board.getWidth(); q++) { //check to the right
if (tile.equalsColor(board.getTileAt(q, tile.getY()))) {
tiles.add(board.getTileAt(q, tile.getY()));
} else {
break;
}
}
for (int q = tile.getX() - 1; q >= 0; q--) { //check to the left
if (board.validBorders(q, tile.getY())) {
if (tile.equalsColor(board.getTileAt(q, tile.getY()))) {
tiles.add(board.getTileAt(q, tile.getY()));
} else {
break;
}
}
}
if (tiles.size() < 2) { //less than 3 in a row
tiles.clear();
} else {
tiles.add(tile);
if (tiles.size() == 3) {
List<Tile> specialShape = findLTshapeX(tiles); // check for T and L shapes
if (specialShape.isEmpty()) {
combi = CombinationFactory.makeCombination(Type.NORMAL);
} else {
tiles.addAll(specialShape);
combi = CombinationFactory.makeCombination(Type.STAR);
}
} else if (tiles.size() == 4) {
combi = CombinationFactory.makeCombination(Type.FLAME);
} else if (tiles.size() == 5) {
combi = CombinationFactory.makeCombination(Type.HYPERCUBE);
}
if (!(combi == null)) {
combi.setTiles(tiles);
}
}
return combi;
}
/**
* Sees whether
* @param tile
* makes a valid combination in y direction on the board,
* @return a list with first the state of the combination,
* and second the list of tiles in de combi.
*/
public Combination getSingleCombinationY(Tile tile) {
Combination combi = null;
List<Tile> tiles = new ArrayList<Tile>();
//check y direction
for (int q = tile.getY() + 1; q < board.getHeight(); q++) { //check down
if (tile.equalsColor(board.getTileAt(tile.getX(),q))) {
tiles.add(board.getTileAt(tile.getX(),q));
} else {
break;
}
}
for (int q = tile.getY() - 1; q >= 0; q--) { //check up
if (tile.equalsColor(board.getTileAt(tile.getX(),q))) {
tiles.add(board.getTileAt(tile.getX(),q));
} else {
break;
}
}
if (tiles.size() < 2) { //less than 3 in a row
tiles.clear();
} else {
tiles.add(tile);
if (tiles.size() == 3) {
List<Tile> specialShape = findLTshapeY(tiles); // check for T and L shapes
if (specialShape.isEmpty()) {
combi = CombinationFactory.makeCombination(Type.NORMAL);
} else {
tiles.addAll(specialShape);
combi = CombinationFactory.makeCombination(Type.STAR);
}
} else if (tiles.size() == 4) {
combi = CombinationFactory.makeCombination(Type.FLAME);
} else if (tiles.size() == 5) {
combi = CombinationFactory.makeCombination(Type.HYPERCUBE);
}
if (!(combi == null)) {
combi.setTiles(tiles);
}
}
return combi;
}
/**
* Checks is combination already exists.
* @param allcombinations : All combinations already in the list
* @param singlecombination : Combination to be compared
* @return true if singlecombination is already in allcombinations
*/
public boolean sameCombination(List<Combination> allcombinations, Combination singlecombination) {
boolean same = false;
for (Combination combi : allcombinations) {
if (combi.getTiles().containsAll(singlecombination.getTiles())) {
same = true;
}
}
return same;
}
/**
* Given
* @param tiles three tiles of the same color in a row in x direction
* the method looks wheter these three tiles are part of an L or T shape.
* @return the list of tiles which are added if an L or T shape is present.
*/
public List<Tile> findLTshapeX(List<Tile> tiles) {
List<Tile> newtiles = new ArrayList<Tile>();
for (Tile t : tiles) {
if (t.getY() + 1 < 8 && t.equalsColor(board.getTileAt(t.getX(),t.getY() + 1))) {
if (t.getY() + 2 < 8 && t.equalsColor(board.getTileAt(t.getX(),t.getY() + 2))) { //2 erboven
newtiles.add(board.getTileAt(t.getX(),t.getY() + 1));
newtiles.add(board.getTileAt(t.getX(),t.getY() + 2));
break;
} else if (t.getY() - 1 >= 0 && t.equalsColor(board.getTileAt(t.getX(),t.getY() - 1))) {
// 1 erboven, 1 beneden
newtiles.add(board.getTileAt(t.getX(),t.getY() + 1));
newtiles.add(board.getTileAt(t.getX(),t.getY() - 1));
break;
}
} else if (t.getY() - 2 >= 0 && t.equalsColor(board.getTileAt(t.getX(),t.getY() - 1))
&& t.equalsColor( board.getTileAt(t.getX(),t.getY() - 2))) { // 2 beneden
newtiles.add(board.getTileAt(t.getX(),t.getY() - 1));
newtiles.add(board.getTileAt(t.getX(),t.getY() - 2));
break;
}
}
return newtiles;
}
/**
* Given
* @param tiles three tiles of the same color in a row in y direction
* the method looks wheter these three tiles are part of an L or T shape.
* @return the list of tiles which are added if an L or T shape is present.
*/
public List<Tile> findLTshapeY(List<Tile> tiles) {
List<Tile> newtiles = new ArrayList<Tile>();
for (Tile t : tiles) {
if (t.getX() + 1 < 8 && board.getTileAt(t.getX() + 1, t.getY()).equalsColor(t)) {
if (t.getX() + 2 < 8 && board.getTileAt(t.getX() + 2, t.getY()).equalsColor(t)) { //2 r
newtiles.add(board.getTileAt(t.getX() + 1, t.getY()));
newtiles.add(board.getTileAt(t.getX() + 2, t.getY()));
break;
} else if (t.getX() - 1 >= 0
&& board.getTileAt(t.getX() - 1, t.getY()).equalsColor(t)) { // 1 rechts, 1 links
newtiles.add(board.getTileAt(t.getX() + 1, t.getY()));
newtiles.add(board.getTileAt(t.getX() - 1, t.getY()));
break;
}
} else if (t.getX() - 2 >= 0 && board.getTileAt(t.getX() - 1, t.getY()).equalsColor(t)
&& board.getTileAt(t.getX() - 2, t.getY()).equalsColor(t)) { // 2 links
newtiles.add(board.getTileAt(t.getX() - 1, t.getY()));
newtiles.add(board.getTileAt(t.getX() - 2, t.getY()));
break;
}
}
return newtiles;
}
/**
* Prints the combinations obtained by getAllCombinationsOnBoard().
*/
public void printCombinations() {
List<Combination> res = this.getAllCombinationsOnBoard();
System.out.println("chains: " + res.size());
for (Combination combi : res) {
System.out.println("\tType: " + combi.getType());
System.out.println("\t" + combi.getTiles());
}
}
}
| Mayke93/Bejeweled-Group-37 | src/main/java/group37/bejeweled/combination/CombinationFinder.java | 3,179 | // 1 rechts, 1 links | line_comment | nl | package main.java.group37.bejeweled.combination;
import main.java.group37.bejeweled.board.Board;
import main.java.group37.bejeweled.board.Tile;
import main.java.group37.bejeweled.combination.Combination.Type;
import java.util.ArrayList;
import java.util.List;
/**
* This class can be used to find the type and tiles of combinations on the board
* at that specific moment.
* @author group37
*/
public class CombinationFinder {
private Board board;
/**
* The constructor for the combinationfinder.
* @param board, the current board.
*/
public CombinationFinder(Board board) {
this.board = board;
}
/**
* This method provides the possibility to set the board.
* @param board, the board to be set.
*/
public void setBoard(Board board) {
this.board = board;
}
/**
* This method provides the possibility to get the board.
*/
public Board getBoard() {
return this.board;
}
/**
* Returns a list, which contains lists with 2 objects: (State,List of tiles),
* eg. (Tile.State.NORMAL,List(t1,t2,t3)).
* This is a list of all the valid combinations on the board at this time.
*/
public List<Combination> getAllCombinationsOnBoard() {
List<Combination> allcombinations = new ArrayList<Combination>();
Combination tile = null;
for (int i = 0; i < board.getWidth(); i++) { //for every tile on the board
for (int j = 0; j < board.getHeight(); j++) {
tile = getSingleCombinationX(board.getTileAt(i,j));
if (!(tile == null)) {
if (!sameCombination(allcombinations, tile)) {
allcombinations.add(tile);
}
}
tile = getSingleCombinationY(board.getTileAt(i,j));
if (!(tile == null)) {
if (!sameCombination(allcombinations, tile)) {
allcombinations.add(tile);
}
}
}
}
return allcombinations;
}
/**
* Sees whether
* @param tile
* makes a valid combination in x direction on the board,
* @return a list with first the state of the combination,
* and second the list of tiles in de combi.
*/
public Combination getSingleCombinationX(Tile tile) {
Combination combi = null;
List<Tile> tiles = new ArrayList<Tile>();
//check x direction
for (int q = tile.getX() + 1; q < board.getWidth(); q++) { //check to the right
if (tile.equalsColor(board.getTileAt(q, tile.getY()))) {
tiles.add(board.getTileAt(q, tile.getY()));
} else {
break;
}
}
for (int q = tile.getX() - 1; q >= 0; q--) { //check to the left
if (board.validBorders(q, tile.getY())) {
if (tile.equalsColor(board.getTileAt(q, tile.getY()))) {
tiles.add(board.getTileAt(q, tile.getY()));
} else {
break;
}
}
}
if (tiles.size() < 2) { //less than 3 in a row
tiles.clear();
} else {
tiles.add(tile);
if (tiles.size() == 3) {
List<Tile> specialShape = findLTshapeX(tiles); // check for T and L shapes
if (specialShape.isEmpty()) {
combi = CombinationFactory.makeCombination(Type.NORMAL);
} else {
tiles.addAll(specialShape);
combi = CombinationFactory.makeCombination(Type.STAR);
}
} else if (tiles.size() == 4) {
combi = CombinationFactory.makeCombination(Type.FLAME);
} else if (tiles.size() == 5) {
combi = CombinationFactory.makeCombination(Type.HYPERCUBE);
}
if (!(combi == null)) {
combi.setTiles(tiles);
}
}
return combi;
}
/**
* Sees whether
* @param tile
* makes a valid combination in y direction on the board,
* @return a list with first the state of the combination,
* and second the list of tiles in de combi.
*/
public Combination getSingleCombinationY(Tile tile) {
Combination combi = null;
List<Tile> tiles = new ArrayList<Tile>();
//check y direction
for (int q = tile.getY() + 1; q < board.getHeight(); q++) { //check down
if (tile.equalsColor(board.getTileAt(tile.getX(),q))) {
tiles.add(board.getTileAt(tile.getX(),q));
} else {
break;
}
}
for (int q = tile.getY() - 1; q >= 0; q--) { //check up
if (tile.equalsColor(board.getTileAt(tile.getX(),q))) {
tiles.add(board.getTileAt(tile.getX(),q));
} else {
break;
}
}
if (tiles.size() < 2) { //less than 3 in a row
tiles.clear();
} else {
tiles.add(tile);
if (tiles.size() == 3) {
List<Tile> specialShape = findLTshapeY(tiles); // check for T and L shapes
if (specialShape.isEmpty()) {
combi = CombinationFactory.makeCombination(Type.NORMAL);
} else {
tiles.addAll(specialShape);
combi = CombinationFactory.makeCombination(Type.STAR);
}
} else if (tiles.size() == 4) {
combi = CombinationFactory.makeCombination(Type.FLAME);
} else if (tiles.size() == 5) {
combi = CombinationFactory.makeCombination(Type.HYPERCUBE);
}
if (!(combi == null)) {
combi.setTiles(tiles);
}
}
return combi;
}
/**
* Checks is combination already exists.
* @param allcombinations : All combinations already in the list
* @param singlecombination : Combination to be compared
* @return true if singlecombination is already in allcombinations
*/
public boolean sameCombination(List<Combination> allcombinations, Combination singlecombination) {
boolean same = false;
for (Combination combi : allcombinations) {
if (combi.getTiles().containsAll(singlecombination.getTiles())) {
same = true;
}
}
return same;
}
/**
* Given
* @param tiles three tiles of the same color in a row in x direction
* the method looks wheter these three tiles are part of an L or T shape.
* @return the list of tiles which are added if an L or T shape is present.
*/
public List<Tile> findLTshapeX(List<Tile> tiles) {
List<Tile> newtiles = new ArrayList<Tile>();
for (Tile t : tiles) {
if (t.getY() + 1 < 8 && t.equalsColor(board.getTileAt(t.getX(),t.getY() + 1))) {
if (t.getY() + 2 < 8 && t.equalsColor(board.getTileAt(t.getX(),t.getY() + 2))) { //2 erboven
newtiles.add(board.getTileAt(t.getX(),t.getY() + 1));
newtiles.add(board.getTileAt(t.getX(),t.getY() + 2));
break;
} else if (t.getY() - 1 >= 0 && t.equalsColor(board.getTileAt(t.getX(),t.getY() - 1))) {
// 1 erboven, 1 beneden
newtiles.add(board.getTileAt(t.getX(),t.getY() + 1));
newtiles.add(board.getTileAt(t.getX(),t.getY() - 1));
break;
}
} else if (t.getY() - 2 >= 0 && t.equalsColor(board.getTileAt(t.getX(),t.getY() - 1))
&& t.equalsColor( board.getTileAt(t.getX(),t.getY() - 2))) { // 2 beneden
newtiles.add(board.getTileAt(t.getX(),t.getY() - 1));
newtiles.add(board.getTileAt(t.getX(),t.getY() - 2));
break;
}
}
return newtiles;
}
/**
* Given
* @param tiles three tiles of the same color in a row in y direction
* the method looks wheter these three tiles are part of an L or T shape.
* @return the list of tiles which are added if an L or T shape is present.
*/
public List<Tile> findLTshapeY(List<Tile> tiles) {
List<Tile> newtiles = new ArrayList<Tile>();
for (Tile t : tiles) {
if (t.getX() + 1 < 8 && board.getTileAt(t.getX() + 1, t.getY()).equalsColor(t)) {
if (t.getX() + 2 < 8 && board.getTileAt(t.getX() + 2, t.getY()).equalsColor(t)) { //2 r
newtiles.add(board.getTileAt(t.getX() + 1, t.getY()));
newtiles.add(board.getTileAt(t.getX() + 2, t.getY()));
break;
} else if (t.getX() - 1 >= 0
&& board.getTileAt(t.getX() - 1, t.getY()).equalsColor(t)) { // 1 rechts,<SUF>
newtiles.add(board.getTileAt(t.getX() + 1, t.getY()));
newtiles.add(board.getTileAt(t.getX() - 1, t.getY()));
break;
}
} else if (t.getX() - 2 >= 0 && board.getTileAt(t.getX() - 1, t.getY()).equalsColor(t)
&& board.getTileAt(t.getX() - 2, t.getY()).equalsColor(t)) { // 2 links
newtiles.add(board.getTileAt(t.getX() - 1, t.getY()));
newtiles.add(board.getTileAt(t.getX() - 2, t.getY()));
break;
}
}
return newtiles;
}
/**
* Prints the combinations obtained by getAllCombinationsOnBoard().
*/
public void printCombinations() {
List<Combination> res = this.getAllCombinationsOnBoard();
System.out.println("chains: " + res.size());
for (Combination combi : res) {
System.out.println("\tType: " + combi.getType());
System.out.println("\t" + combi.getTiles());
}
}
}
|
107873_0 | import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import org.jxmapviewer.viewer.GeoPosition;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Request {
public JPanel requestPanel;
private JTextArea QueryField, ResultArea;
private JList History;
private JButton SendButton, ClearButton, SelectButton;
private JPanel ResponsePanel, DisplayPanel;
private CardLayout cardLayout;
private List<String> queryHistory, displayedQueryHistory;
private Map map;
public Request(){
BaseInitialise();
}
public Request(Map map){
BaseInitialise();
this.map = map;
}
private void BaseInitialise(){
queryHistory = new ArrayList<String>();
displayedQueryHistory = new ArrayList<String>();
cardLayout = new CardLayout();
initializeButtons();
CardLayout card = (CardLayout)DisplayPanel.getLayout();
card.show(DisplayPanel, "Resultaat");
UpdateHistory();
}
public void UpdateHistory(){
DefaultListModel<String> listModel = new DefaultListModel<String>();
for (String query : displayedQueryHistory){
listModel.addElement(query);
}
if(listModel.isEmpty()) listModel.addElement("geschiedenis is leeg");
History.setModel(listModel);
}
private void initializeButtons(){
SendButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String query = QueryField.getText();
if(query == null || query.isEmpty()) return;
addToHistory(query);
UpdateHistory();
String QueryResult = ApiController.runJsonQuery(query);
try {
if (QueryResult.contains("\"geometrie\"") || QueryResult.contains("\"geometry\"")) {
String cordString = QueryResult.substring(QueryResult.indexOf("((") + 2);
cordString = cordString.substring(0, cordString.indexOf("))"));
UpdateMap(GeoController.ParseGeoPosition(cordString));
}
} catch (java.lang.NumberFormatException error) {
QueryResult = "[{ \"Kon coordinaten niet goed parsen\": 1 }]";
}
String result = queryResultFormat(QueryResult);
ResultArea.setText(result);
}
});
SelectButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(queryHistory.isEmpty()){
QueryField.setText("");
return;
}
if(History.getSelectedIndex() == -1) return;
QueryField.setText(queryHistory.get(History.getSelectedIndex()));
}
});
ClearButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
queryHistory.clear();
displayedQueryHistory.clear();
UpdateHistory();
}
});
}
public void addToHistory(String s){
if(s == null || s.isEmpty()) return;
if(queryHistory.isEmpty())
{
queryHistory.add(s);
displayedQueryHistory.add(cleanQueryForDisplay(s));
return;
}
String previous = queryHistory.get(queryHistory.size()-1);
if(Objects.equals(previous, s)) return;
queryHistory.add(s);
displayedQueryHistory.add(cleanQueryForDisplay(s));
}
private String cleanQueryForDisplay(String s) {
String query = s.replaceAll("\n", " ");
query = query.replaceAll(" +", " ");// " +" is voor meerdere whitespacen
if(query.startsWith("query ")) query = query.substring(6);
if(query.length() >= 100) query = query.substring(0, 100) + "...";
return query;
}
private String queryResultFormat(String format){
if(format == null || format.isEmpty()) return "";
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement je = JsonParser.parseString(format);
return gson.toJson(je);
}
private void UpdateMap(ArrayList<GeoPosition> points){
map.SetAreaPainter(points);
}
} | MayorBosranger/QsdGui | src/Request.java | 1,213 | // " +" is voor meerdere whitespacen | line_comment | nl | import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import org.jxmapviewer.viewer.GeoPosition;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Request {
public JPanel requestPanel;
private JTextArea QueryField, ResultArea;
private JList History;
private JButton SendButton, ClearButton, SelectButton;
private JPanel ResponsePanel, DisplayPanel;
private CardLayout cardLayout;
private List<String> queryHistory, displayedQueryHistory;
private Map map;
public Request(){
BaseInitialise();
}
public Request(Map map){
BaseInitialise();
this.map = map;
}
private void BaseInitialise(){
queryHistory = new ArrayList<String>();
displayedQueryHistory = new ArrayList<String>();
cardLayout = new CardLayout();
initializeButtons();
CardLayout card = (CardLayout)DisplayPanel.getLayout();
card.show(DisplayPanel, "Resultaat");
UpdateHistory();
}
public void UpdateHistory(){
DefaultListModel<String> listModel = new DefaultListModel<String>();
for (String query : displayedQueryHistory){
listModel.addElement(query);
}
if(listModel.isEmpty()) listModel.addElement("geschiedenis is leeg");
History.setModel(listModel);
}
private void initializeButtons(){
SendButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String query = QueryField.getText();
if(query == null || query.isEmpty()) return;
addToHistory(query);
UpdateHistory();
String QueryResult = ApiController.runJsonQuery(query);
try {
if (QueryResult.contains("\"geometrie\"") || QueryResult.contains("\"geometry\"")) {
String cordString = QueryResult.substring(QueryResult.indexOf("((") + 2);
cordString = cordString.substring(0, cordString.indexOf("))"));
UpdateMap(GeoController.ParseGeoPosition(cordString));
}
} catch (java.lang.NumberFormatException error) {
QueryResult = "[{ \"Kon coordinaten niet goed parsen\": 1 }]";
}
String result = queryResultFormat(QueryResult);
ResultArea.setText(result);
}
});
SelectButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(queryHistory.isEmpty()){
QueryField.setText("");
return;
}
if(History.getSelectedIndex() == -1) return;
QueryField.setText(queryHistory.get(History.getSelectedIndex()));
}
});
ClearButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
queryHistory.clear();
displayedQueryHistory.clear();
UpdateHistory();
}
});
}
public void addToHistory(String s){
if(s == null || s.isEmpty()) return;
if(queryHistory.isEmpty())
{
queryHistory.add(s);
displayedQueryHistory.add(cleanQueryForDisplay(s));
return;
}
String previous = queryHistory.get(queryHistory.size()-1);
if(Objects.equals(previous, s)) return;
queryHistory.add(s);
displayedQueryHistory.add(cleanQueryForDisplay(s));
}
private String cleanQueryForDisplay(String s) {
String query = s.replaceAll("\n", " ");
query = query.replaceAll(" +", " ");// " +"<SUF>
if(query.startsWith("query ")) query = query.substring(6);
if(query.length() >= 100) query = query.substring(0, 100) + "...";
return query;
}
private String queryResultFormat(String format){
if(format == null || format.isEmpty()) return "";
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement je = JsonParser.parseString(format);
return gson.toJson(je);
}
private void UpdateMap(ArrayList<GeoPosition> points){
map.SetAreaPainter(points);
}
} |
72301_16 | /*
* Copyright (C) 2018 mayurdivate
*
* 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 umac.guava;
import java.util.HashMap;
/**
*
* @author mayurdivate
*/
public class Genome {
private String genomeName;
private String orgCode;
private String txdb;
private String orgdb;
private String orgdbSymbol;
private String organismName;
private String genomeSize;
public static Genome getGenomeObject(String genomeBuild){
HashMap<String, Genome> genomeHashMap = getAvailableGenomes();
if(genomeHashMap.containsKey(genomeBuild)){
return genomeHashMap.get(genomeBuild);
}
return null;
}
public static String[] getGenomeArray(){
String[] genomes = {
"-select-",
"hg19",
"hg38",
"hg18",
"mm10",
"mm9",
"rheMac8",
"rheMac3",
"rn6",
"rn5",
"rn4",
"danRer10",
"galGal4",
"panTro4",
"susScr3",
"dm6",
"dm3",
"canFam3",
"ce11",
"ce6",
"bosTau8"};
return genomes;
}
public static HashMap<String, Genome> getAvailableGenomes(){
HashMap<String, Genome> genomeHashMap = new HashMap<>();
// url to txdb https://www.bioconductor.org/help/workflows/annotation/Annotation_Resources/
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
String orgName = "Homo sapiens";
String genomeSize = "hs";
Genome hg18 = new Genome("hg18", "Hs", "TxDb.Hsapiens.UCSC.hg18.knownGene", "org.Hs.eg.db", "org.Hs.egSYMBOL",orgName,genomeSize);
Genome hg19 = new Genome("hg19", "Hs", "TxDb.Hsapiens.UCSC.hg19.knownGene", "org.Hs.eg.db", "org.Hs.egSYMBOL",orgName,genomeSize);
Genome hg38 = new Genome("hg38", "Hs", "TxDb.Hsapiens.UCSC.hg38.knownGene", "org.Hs.eg.db", "org.Hs.egSYMBOL",orgName,genomeSize);
genomeHashMap.put("hg18", hg18);
genomeHashMap.put("hg19", hg19);
genomeHashMap.put("hg38", hg38);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
orgName = "Mus musculus";
genomeSize = "mm";
Genome mm10 = new Genome("mm10", "Mm", "TxDb.Mmusculus.UCSC.mm10.knownGene", "org.Mm.eg.db", "org.Mm.egSYMBOL",orgName,genomeSize);
Genome mm9 = new Genome("mm9", "Mm", "TxDb.Mmusculus.UCSC.mm9.knownGene", "org.Mm.eg.db", "org.Mm.egSYMBOL",orgName,genomeSize);
genomeHashMap.put("mm10", mm10);
genomeHashMap.put("mm9", mm9);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
orgName = "Macaca mulatta";
genomeSize = "2.6e9";
Genome rheMac3 = new Genome("rheMac3", "Mmu", "TxDb.Mmulatta.UCSC.rheMac3.refGene", "org.Mmu.eg.db", "org.Mmu.egSYMBOL",orgName,genomeSize);
Genome rheMac8 = new Genome("rheMac8", "Mmu", "TxDb.Mmulatta.UCSC.rheMac3.refGene", "org.Mmu.eg.db", "org.Mmu.egSYMBOL",orgName,genomeSize);
genomeHashMap.put("rheMac3", rheMac3);
genomeHashMap.put("rheMac8", rheMac8);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
orgName = "Rattus norvegicus";
genomeSize = "2.2e9";
Genome rn4 = new Genome("rn4", "Rn", "TxDb.Rnorvegicus.UCSC.rn4.ensGene", "org.Rn.eg.db", "org.Rn.egSYMBOL",orgName,genomeSize);
Genome rn5 = new Genome("rn5", "Rn", "TxDb.Rnorvegicus.UCSC.rn5.refGene", "org.Rn.eg.db", "org.Rn.egSYMBOL",orgName,genomeSize);
Genome rn6 = new Genome("rn6", "Rn", "TxDb.Rnorvegicus.UCSC.rn6.refGene", "org.Rn.eg.db", "org.Rn.egSYMBOL",orgName,genomeSize);
genomeHashMap.put("rn4",rn4 );
genomeHashMap.put("rn5",rn5 );
genomeHashMap.put("rn6",rn6 );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
orgName = "Danio rerio";
genomeSize = "1.3e9";
Genome Dr10 = new Genome("danRer10", "Dr", "TxDb.Drerio.UCSC.danRer10.refGene", "org.Dr.eg.db", "org.Dr.egSYMBOL",orgName,genomeSize);
genomeHashMap.put("danRer10",Dr10 );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
orgName = "Gallus gallus";
genomeSize = "8.3e8";
Genome gg4 = new Genome("galGal4", "Hs", "TxDb.Ggallus.UCSC.galGal4.refGene", "org.Gg.eg.db", "org.Gg.egSYMBOL",orgName,genomeSize);
genomeHashMap.put("galGal4",gg4 );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
orgName = "Pan troglodytes";
genomeSize = "2.6e9";
Genome pt4 = new Genome("panTro4", "Hs", "TxDb.Ptroglodytes.UCSC.panTro4.refGene", "org.Pt.eg.db ", "org.Pt.egSYMBOL",orgName,genomeSize);
genomeHashMap.put("panTro4",pt4 );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
orgName = "Sus scrofa";
genomeSize = "2.2e9";
Genome susScr3 = new Genome("susScr3", "Ss", "TxDb.Sscrofa.UCSC.susScr3.refGene", "org.Ss.eg.db", "org.Ss.egSYMBOL",orgName,genomeSize);
genomeHashMap.put("susScr3",susScr3 );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
orgName = "Drosophila melanogaster";
genomeSize = "dm";
Genome dm3 = new Genome("dm3", "Dm", "TxDb.Dmelanogaster.UCSC.dm3.ensGene", "org.Dm.eg.db", "org.Dm.egSYMBOL",orgName,genomeSize);
Genome dm6 = new Genome("dm6", "Dm", "TxDb.Dmelanogaster.UCSC.dm6.ensGene", "org.Dm.eg.db", "org.Dm.egSYMBOL",orgName,genomeSize);
genomeHashMap.put("dm3",dm3 );
genomeHashMap.put("dm6",dm6 );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
orgName = "Canis familiaris";
genomeSize = "2e9";
Genome cf3 = new Genome("canFam3", "Cf", "TxDb.Cfamiliaris.UCSC.canFam3.refGene", "org.Cf.eg.db", "org.Cf.egSYMBOL",orgName,genomeSize);
genomeHashMap.put("canFam3",cf3 );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
orgName = "Caenorhabditis elegans";
genomeSize = "ce";
Genome ce6 = new Genome("ce6", "Ce", "TxDb.Celegans.UCSC.ce6.ensGene", "org.Ce.eg.db", "org.Ce.egSYMBOL",orgName,genomeSize);
Genome ce11 = new Genome("ce11", "Ce", "TxDb.Celegans.UCSC.ce11.refGene", "org.Ce.eg.db", "org.Ce.egSYMBOL",orgName,genomeSize);
genomeHashMap.put("ce6",ce6 );
genomeHashMap.put("ce11",ce11);
orgName = "Bos taurus";
genomeSize = "2.1e9";
Genome bt8 = new Genome("bosTau8", "Bt", "TxDb.Btaurus.UCSC.bosTau8.refGene", "org.Bt.eg.db", "org.Bt.egSYMBOL",orgName,genomeSize);
genomeHashMap.put("bosTau8",bt8);
return genomeHashMap;
}
public Genome(String genomeName, String orgCode, String txdb, String orgdb, String orgdbSymbol, String organismName, String genomeSize) {
this.genomeName = genomeName;
this.orgCode = orgCode;
this.txdb = txdb;
this.orgdb = orgdb;
this.orgdbSymbol = orgdbSymbol;
this.organismName = organismName;
this.genomeSize = genomeSize;
}
/**
* @return the genomeName
*/
public String getGenomeName() {
return genomeName;
}
/**
* @param genomeName the genomeName to set
*/
public void setGenomeName(String genomeName) {
this.genomeName = genomeName;
}
/**
* @return the orgCode
*/
public String getOrgCode() {
return orgCode;
}
/**
* @param orgCode the orgCode to set
*/
public void setOrgCode(String orgCode) {
this.orgCode = orgCode;
}
/**
* @return the txdb
*/
public String getTxdb() {
return txdb;
}
/**
* @param txdb the txdb to set
*/
public void setTxdb(String txdb) {
this.txdb = txdb;
}
/**
* @return the orgdb
*/
public String getOrgdb() {
return orgdb;
}
/**
* @param orgdb the orgdb to set
*/
public void setOrgdb(String orgdb) {
this.orgdb = orgdb;
}
/**
* @return the orgdbSymbol
*/
public String getOrgdbSymbol() {
return orgdbSymbol;
}
/**
* @param orgdbSymbol the orgdbSymbol to set
*/
public void setOrgdbSymbol(String orgdbSymbol) {
this.orgdbSymbol = orgdbSymbol;
}
/**
* @return the organismName
*/
public String getOrganismName() {
return organismName;
}
/**
* @param organismName the organismName to set
*/
public void setOrganismName(String organismName) {
this.organismName = organismName;
}
/**
* @return the genomeSize
*/
public String getGenomeSize() {
return genomeSize;
}
/**
* @param genomeSize the genomeSize to set
*/
public void setGenomeSize(String genomeSize) {
this.genomeSize = genomeSize;
}
}
| MayurDivate/GUAVASourceCode | src/umac/guava/Genome.java | 3,427 | /**
* @param genomeSize the genomeSize to set
*/ | block_comment | nl | /*
* Copyright (C) 2018 mayurdivate
*
* 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 umac.guava;
import java.util.HashMap;
/**
*
* @author mayurdivate
*/
public class Genome {
private String genomeName;
private String orgCode;
private String txdb;
private String orgdb;
private String orgdbSymbol;
private String organismName;
private String genomeSize;
public static Genome getGenomeObject(String genomeBuild){
HashMap<String, Genome> genomeHashMap = getAvailableGenomes();
if(genomeHashMap.containsKey(genomeBuild)){
return genomeHashMap.get(genomeBuild);
}
return null;
}
public static String[] getGenomeArray(){
String[] genomes = {
"-select-",
"hg19",
"hg38",
"hg18",
"mm10",
"mm9",
"rheMac8",
"rheMac3",
"rn6",
"rn5",
"rn4",
"danRer10",
"galGal4",
"panTro4",
"susScr3",
"dm6",
"dm3",
"canFam3",
"ce11",
"ce6",
"bosTau8"};
return genomes;
}
public static HashMap<String, Genome> getAvailableGenomes(){
HashMap<String, Genome> genomeHashMap = new HashMap<>();
// url to txdb https://www.bioconductor.org/help/workflows/annotation/Annotation_Resources/
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
String orgName = "Homo sapiens";
String genomeSize = "hs";
Genome hg18 = new Genome("hg18", "Hs", "TxDb.Hsapiens.UCSC.hg18.knownGene", "org.Hs.eg.db", "org.Hs.egSYMBOL",orgName,genomeSize);
Genome hg19 = new Genome("hg19", "Hs", "TxDb.Hsapiens.UCSC.hg19.knownGene", "org.Hs.eg.db", "org.Hs.egSYMBOL",orgName,genomeSize);
Genome hg38 = new Genome("hg38", "Hs", "TxDb.Hsapiens.UCSC.hg38.knownGene", "org.Hs.eg.db", "org.Hs.egSYMBOL",orgName,genomeSize);
genomeHashMap.put("hg18", hg18);
genomeHashMap.put("hg19", hg19);
genomeHashMap.put("hg38", hg38);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
orgName = "Mus musculus";
genomeSize = "mm";
Genome mm10 = new Genome("mm10", "Mm", "TxDb.Mmusculus.UCSC.mm10.knownGene", "org.Mm.eg.db", "org.Mm.egSYMBOL",orgName,genomeSize);
Genome mm9 = new Genome("mm9", "Mm", "TxDb.Mmusculus.UCSC.mm9.knownGene", "org.Mm.eg.db", "org.Mm.egSYMBOL",orgName,genomeSize);
genomeHashMap.put("mm10", mm10);
genomeHashMap.put("mm9", mm9);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
orgName = "Macaca mulatta";
genomeSize = "2.6e9";
Genome rheMac3 = new Genome("rheMac3", "Mmu", "TxDb.Mmulatta.UCSC.rheMac3.refGene", "org.Mmu.eg.db", "org.Mmu.egSYMBOL",orgName,genomeSize);
Genome rheMac8 = new Genome("rheMac8", "Mmu", "TxDb.Mmulatta.UCSC.rheMac3.refGene", "org.Mmu.eg.db", "org.Mmu.egSYMBOL",orgName,genomeSize);
genomeHashMap.put("rheMac3", rheMac3);
genomeHashMap.put("rheMac8", rheMac8);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
orgName = "Rattus norvegicus";
genomeSize = "2.2e9";
Genome rn4 = new Genome("rn4", "Rn", "TxDb.Rnorvegicus.UCSC.rn4.ensGene", "org.Rn.eg.db", "org.Rn.egSYMBOL",orgName,genomeSize);
Genome rn5 = new Genome("rn5", "Rn", "TxDb.Rnorvegicus.UCSC.rn5.refGene", "org.Rn.eg.db", "org.Rn.egSYMBOL",orgName,genomeSize);
Genome rn6 = new Genome("rn6", "Rn", "TxDb.Rnorvegicus.UCSC.rn6.refGene", "org.Rn.eg.db", "org.Rn.egSYMBOL",orgName,genomeSize);
genomeHashMap.put("rn4",rn4 );
genomeHashMap.put("rn5",rn5 );
genomeHashMap.put("rn6",rn6 );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
orgName = "Danio rerio";
genomeSize = "1.3e9";
Genome Dr10 = new Genome("danRer10", "Dr", "TxDb.Drerio.UCSC.danRer10.refGene", "org.Dr.eg.db", "org.Dr.egSYMBOL",orgName,genomeSize);
genomeHashMap.put("danRer10",Dr10 );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
orgName = "Gallus gallus";
genomeSize = "8.3e8";
Genome gg4 = new Genome("galGal4", "Hs", "TxDb.Ggallus.UCSC.galGal4.refGene", "org.Gg.eg.db", "org.Gg.egSYMBOL",orgName,genomeSize);
genomeHashMap.put("galGal4",gg4 );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
orgName = "Pan troglodytes";
genomeSize = "2.6e9";
Genome pt4 = new Genome("panTro4", "Hs", "TxDb.Ptroglodytes.UCSC.panTro4.refGene", "org.Pt.eg.db ", "org.Pt.egSYMBOL",orgName,genomeSize);
genomeHashMap.put("panTro4",pt4 );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
orgName = "Sus scrofa";
genomeSize = "2.2e9";
Genome susScr3 = new Genome("susScr3", "Ss", "TxDb.Sscrofa.UCSC.susScr3.refGene", "org.Ss.eg.db", "org.Ss.egSYMBOL",orgName,genomeSize);
genomeHashMap.put("susScr3",susScr3 );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
orgName = "Drosophila melanogaster";
genomeSize = "dm";
Genome dm3 = new Genome("dm3", "Dm", "TxDb.Dmelanogaster.UCSC.dm3.ensGene", "org.Dm.eg.db", "org.Dm.egSYMBOL",orgName,genomeSize);
Genome dm6 = new Genome("dm6", "Dm", "TxDb.Dmelanogaster.UCSC.dm6.ensGene", "org.Dm.eg.db", "org.Dm.egSYMBOL",orgName,genomeSize);
genomeHashMap.put("dm3",dm3 );
genomeHashMap.put("dm6",dm6 );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
orgName = "Canis familiaris";
genomeSize = "2e9";
Genome cf3 = new Genome("canFam3", "Cf", "TxDb.Cfamiliaris.UCSC.canFam3.refGene", "org.Cf.eg.db", "org.Cf.egSYMBOL",orgName,genomeSize);
genomeHashMap.put("canFam3",cf3 );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
orgName = "Caenorhabditis elegans";
genomeSize = "ce";
Genome ce6 = new Genome("ce6", "Ce", "TxDb.Celegans.UCSC.ce6.ensGene", "org.Ce.eg.db", "org.Ce.egSYMBOL",orgName,genomeSize);
Genome ce11 = new Genome("ce11", "Ce", "TxDb.Celegans.UCSC.ce11.refGene", "org.Ce.eg.db", "org.Ce.egSYMBOL",orgName,genomeSize);
genomeHashMap.put("ce6",ce6 );
genomeHashMap.put("ce11",ce11);
orgName = "Bos taurus";
genomeSize = "2.1e9";
Genome bt8 = new Genome("bosTau8", "Bt", "TxDb.Btaurus.UCSC.bosTau8.refGene", "org.Bt.eg.db", "org.Bt.egSYMBOL",orgName,genomeSize);
genomeHashMap.put("bosTau8",bt8);
return genomeHashMap;
}
public Genome(String genomeName, String orgCode, String txdb, String orgdb, String orgdbSymbol, String organismName, String genomeSize) {
this.genomeName = genomeName;
this.orgCode = orgCode;
this.txdb = txdb;
this.orgdb = orgdb;
this.orgdbSymbol = orgdbSymbol;
this.organismName = organismName;
this.genomeSize = genomeSize;
}
/**
* @return the genomeName
*/
public String getGenomeName() {
return genomeName;
}
/**
* @param genomeName the genomeName to set
*/
public void setGenomeName(String genomeName) {
this.genomeName = genomeName;
}
/**
* @return the orgCode
*/
public String getOrgCode() {
return orgCode;
}
/**
* @param orgCode the orgCode to set
*/
public void setOrgCode(String orgCode) {
this.orgCode = orgCode;
}
/**
* @return the txdb
*/
public String getTxdb() {
return txdb;
}
/**
* @param txdb the txdb to set
*/
public void setTxdb(String txdb) {
this.txdb = txdb;
}
/**
* @return the orgdb
*/
public String getOrgdb() {
return orgdb;
}
/**
* @param orgdb the orgdb to set
*/
public void setOrgdb(String orgdb) {
this.orgdb = orgdb;
}
/**
* @return the orgdbSymbol
*/
public String getOrgdbSymbol() {
return orgdbSymbol;
}
/**
* @param orgdbSymbol the orgdbSymbol to set
*/
public void setOrgdbSymbol(String orgdbSymbol) {
this.orgdbSymbol = orgdbSymbol;
}
/**
* @return the organismName
*/
public String getOrganismName() {
return organismName;
}
/**
* @param organismName the organismName to set
*/
public void setOrganismName(String organismName) {
this.organismName = organismName;
}
/**
* @return the genomeSize
*/
public String getGenomeSize() {
return genomeSize;
}
/**
* @param genomeSize the<SUF>*/
public void setGenomeSize(String genomeSize) {
this.genomeSize = genomeSize;
}
}
|
213155_0 | /**
* Vincent Verboven
* 14/11/2022
*/
public class TestLeden {
public static void main(String[] args) {
Leden leden = new Leden();
leden.voegLidToe(new Lid(1001, "Luka", Soort.GEWOON));
leden.voegLidToe(new Lid(1002, "Gevorg", Soort.ERELID));
leden.voegLidToe(new Lid(1003, "Lorenzo", Soort.STEUNEND));
leden.voegLidToe(new Lid(1004, "Pavel", Soort.GEWOON));
leden.voegLidToe(new Lid(1005, "Sarah", Soort.GEWOON));
leden.voegLidToe(new Lid(1006, "Noam", Soort.ERELID));
leden.printActieveLeden();
}
}
| Meastro85/OOPROG-Java1 | P2W1/P2W1/Voetbalclub/src/TestLeden.java | 242 | /**
* Vincent Verboven
* 14/11/2022
*/ | block_comment | nl | /**
* Vincent Verboven
<SUF>*/
public class TestLeden {
public static void main(String[] args) {
Leden leden = new Leden();
leden.voegLidToe(new Lid(1001, "Luka", Soort.GEWOON));
leden.voegLidToe(new Lid(1002, "Gevorg", Soort.ERELID));
leden.voegLidToe(new Lid(1003, "Lorenzo", Soort.STEUNEND));
leden.voegLidToe(new Lid(1004, "Pavel", Soort.GEWOON));
leden.voegLidToe(new Lid(1005, "Sarah", Soort.GEWOON));
leden.voegLidToe(new Lid(1006, "Noam", Soort.ERELID));
leden.printActieveLeden();
}
}
|
184901_30 | /*
* Copyright (c) 2000-2004 Ben Mazur ([email protected])
* Copyright (c) 2024 - The MegaMek Team. All Rights Reserved.
*
* This file is part of MegaMek.
*
* MegaMek 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.
*
* MegaMek 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 MegaMek. If not, see <http://www.gnu.org/licenses/>.
*/
package megamek.common;
import megamek.client.ui.swing.util.PlayerColour;
import megamek.common.icons.Camouflage;
import megamek.common.options.OptionsConstants;
import java.util.Objects;
import java.util.Vector;
/**
* Represents a player in the game.
*
* Note that Player should be usable for any type of game (TW, AS, BF, SBF) and therefore should not
* make any direct use of Game, Entity, AlphaStrikeElement etc., instead using IGame and InGameObject if necessary.
*/
public final class Player extends TurnOrdered {
//region Variable Declarations
private static final long serialVersionUID = 6828849559007455761L;
public static final int PLAYER_NONE = -1;
public static final int TEAM_NONE = 0;
public static final int TEAM_UNASSIGNED = -1;
public static final String[] TEAM_NAMES = {"No Team", "Team 1", "Team 2", "Team 3", "Team 4", "Team 5"};
private transient IGame game;
private String name;
private String email;
private final int id;
private int team = TEAM_NONE;
private boolean done = false; // done with phase
private boolean ghost = false; // disconnected player
private boolean bot = false;
private boolean observer = false;
private boolean gameMaster = false;
private boolean seeAll = false; // Observer or Game Master can observe double-blind games
private boolean singleBlind = false; // Bot can observe double-blind games
// deployment settings
private int startingPos = Board.START_ANY;
private int startOffset = 0;
private int startWidth = 3;
private int startingAnyNWx = Entity.STARTING_ANY_NONE;
private int startingAnyNWy = Entity.STARTING_ANY_NONE;
private int startingAnySEx = Entity.STARTING_ANY_NONE;
private int startingAnySEy = Entity.STARTING_ANY_NONE;
// number of minefields
private int numMfConv = 0;
private int numMfCmd = 0;
private int numMfVibra = 0;
private int numMfActive = 0;
private int numMfInferno = 0;
// hexes that are automatically hit by artillery
private Vector<Coords> artyAutoHitHexes = new Vector<>();
private int initialEntityCount;
private int initialBV;
// initiative bonuses go here because we don't know if teams are rolling
// initiative collectively
// if they are then we pick the best non-zero bonuses
private int constantInitBonus = 0;
private int streakCompensationBonus = 0;
private Camouflage camouflage = new Camouflage(Camouflage.COLOUR_CAMOUFLAGE, PlayerColour.BLUE.name());
private PlayerColour colour = PlayerColour.BLUE;
private Vector<Minefield> visibleMinefields = new Vector<>();
private boolean admitsDefeat = false;
//Voting should not be stored in save game so marked transient
private transient boolean votedToAllowTeamChange = false;
private transient boolean votedToAllowGameMaster = false;
//endregion Variable Declarations
//region Constructors
public Player(int id, String name) {
this.name = name;
this.id = id;
}
//endregion Constructors
public Vector<Minefield> getMinefields() {
return visibleMinefields;
}
public void addMinefield(Minefield mf) {
visibleMinefields.addElement(mf);
}
public void addMinefields(Vector<Minefield> minefields) {
for (int i = 0; i < minefields.size(); i++) {
visibleMinefields.addElement(minefields.elementAt(i));
}
}
public void removeMinefield(Minefield mf) {
visibleMinefields.removeElement(mf);
}
public void removeMinefields() {
visibleMinefields.removeAllElements();
}
public void removeArtyAutoHitHexes() {
artyAutoHitHexes.removeAllElements();
}
public boolean containsMinefield(Minefield mf) {
return visibleMinefields.contains(mf);
}
public boolean hasMinefields() {
return (numMfCmd > 0) || (numMfConv > 0) || (numMfVibra > 0) || (numMfActive > 0) || (numMfInferno > 0);
}
public void setNbrMFConventional(int nbrMF) {
numMfConv = nbrMF;
}
public void setNbrMFCommand(int nbrMF) {
numMfCmd = nbrMF;
}
public void setNbrMFVibra(int nbrMF) {
numMfVibra = nbrMF;
}
public void setNbrMFActive(int nbrMF) {
numMfActive = nbrMF;
}
public void setNbrMFInferno(int nbrMF) {
numMfInferno = nbrMF;
}
public int getNbrMFConventional() {
return numMfConv;
}
public int getNbrMFCommand() {
return numMfCmd;
}
public int getNbrMFVibra() {
return numMfVibra;
}
public int getNbrMFActive() {
return numMfActive;
}
public int getNbrMFInferno() {
return numMfInferno;
}
public Camouflage getCamouflage() {
return camouflage;
}
public void setCamouflage(Camouflage camouflage) {
this.camouflage = camouflage;
}
public void setGame(IGame game) {
this.game = game;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getId() {
return id;
}
public int getTeam() {
return team;
}
public void setTeam(int team) {
this.team = team;
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
public boolean isGhost() {
return ghost;
}
public void setGhost(boolean ghost) {
this.ghost = ghost;
}
/**
* @return true if this player connected as a bot.
*/
public boolean isBot() {
return bot;
}
/**
* Sets whether this player connected as a bot.
*/
public void setBot(boolean bot) {
this.bot = bot;
}
/** @return true if this player may become a Game Master. Any human may be a GM*/
public boolean isGameMasterPermitted() {
return !bot;
}
/** @return true if {@link #gameMaster} flag is true and {@link #isGameMasterPermitted()}*/
public boolean isGameMaster() {
return (isGameMasterPermitted() && gameMaster);
}
/**
* If you are checking to see this player is a Game Master, use {@link #isGameMaster()} ()} instead
* @return the value of gameMaster flag, without checking if it is permitted.
*/
public boolean getGameMaster() {
return gameMaster;
}
/**
* sets {@link #gameMaster} but this only allows GM status if other conditions permits it.
* see {@link #isGameMaster()}
*/
public void setGameMaster(boolean gameMaster) {
this.gameMaster = gameMaster;
}
/** @return true if {@link #observer} flag is true and not in VICTORY phase*/
public boolean isObserver() {
if ((game != null) && game.getPhase().isVictory()) {
return false;
}
return observer;
}
/**
* sets {@link #seeAll}. This will only enable seeAll if other conditions allow it.
* see {@link #canIgnoreDoubleBlind()}
*/
public void setSeeAll(boolean seeAll) {
this.seeAll = seeAll;
}
/**
* If you are checking to see if double-blind applies to this player, use {@link #canIgnoreDoubleBlind()}
* @return the value of seeAll flag, without checking if it is permitted
*/
public boolean getSeeAll() {
return seeAll;
}
/**
* If you are checking to see if double-blind applies to this player, use {@link #canIgnoreDoubleBlind()}
* @return true if {@link #seeAll} is true and is permitted
*/
public boolean canSeeAll() {
return (isSeeAllPermitted() && seeAll);
}
/**
* If you are checking to see if double-blind applies to this player, use {@link #canIgnoreDoubleBlind()}
* @return true if player is allowed use seeAll
* */
public boolean isSeeAllPermitted() {
return gameMaster || observer;
}
/** set the {@link #observer} flag. Observers have no units ad no team */
public void setObserver(boolean observer) {
this.observer = observer;
}
/**
* sets {@link #seeAll}. This will only enable seeAll if other conditions allow it.
* see {@link #canIgnoreDoubleBlind()}
*/
public void setSingleBlind(boolean singleBlind) {
this.singleBlind = singleBlind;
}
/**
* If you are checking to see this player can ignore double-blind, use {@link #canIgnoreDoubleBlind()} ()} instead
* @return the value of singleBlind flag, without checking if it is permitted.
*/
public boolean getSingleBlind() {
return singleBlind;
}
/**
* @return true if singleBlind flag is true and {@link #isSingleBlindPermitted()}
*/
public boolean canSeeSingleBlind() {
return (isSingleBlindPermitted() && singleBlind);
}
/**
* If you are checking to see if double-blind applies to this player, use {@link #canIgnoreDoubleBlind()}
* @return true if player is allowed use singleblind (bots only)
* */
public boolean isSingleBlindPermitted() {
return bot;
}
/**
* Double-blind uses Line-of-sight to determine which units are displayed on the board
* and in reports. seeAll and singleBlind flags allow this to be ignored, granting a view
* of the entire map and units.
* @return true if this player ignores the double-blind setting.
*/
public boolean canIgnoreDoubleBlind() {
return canSeeSingleBlind() || canSeeAll();
}
public PlayerColour getColour() {
return colour;
}
public void setColour(PlayerColour colour) {
this.colour = Objects.requireNonNull(colour, "Colour cannot be set to null");
}
public int getStartingPos() {
return startingPos;
}
public void setStartingPos(int startingPos) {
this.startingPos = startingPos;
}
public int getStartOffset() {
return startOffset;
}
public void setStartOffset(int startOffset) {
this.startOffset = startOffset;
}
public int getStartWidth() {
return startWidth;
}
public void setStartWidth(int startWidth) {
this.startWidth = startWidth;
}
public int getStartingAnyNWx() {
return startingAnyNWx;
}
public void setStartingAnyNWx(int i) {
this.startingAnyNWx = i;
}
public int getStartingAnyNWy() {
return startingAnyNWy;
}
public void setStartingAnyNWy(int i) {
this.startingAnyNWy = i;
}
public int getStartingAnySEx() {
return startingAnySEx;
}
public void setStartingAnySEx(int i) {
this.startingAnySEx = i;
}
public int getStartingAnySEy() {
return startingAnySEy;
}
public void setStartingAnySEy(int i) {
this.startingAnySEy = i;
}
/**
* Set deployment zone to edge of board for reinforcements
*/
public void adjustStartingPosForReinforcements() {
if (startingPos > 10) {
startingPos -= 10; // deep deploy change to standard
}
if (startingPos == Board.START_CENTER) {
startingPos = Board.START_ANY; // center changes to any
}
}
public boolean isEnemyOf(Player other) {
if (null == other) {
return true;
}
return (id != other.getId())
&& ((team == TEAM_NONE) || (team == TEAM_UNASSIGNED) || (team != other.getTeam()));
}
public void setAdmitsDefeat(boolean admitsDefeat) {
this.admitsDefeat = admitsDefeat;
}
public boolean admitsDefeat() {
return admitsDefeat;
}
public void setVotedToAllowTeamChange(boolean allowChange) {
votedToAllowTeamChange = allowChange;
}
public boolean getVotedToAllowTeamChange() {
return votedToAllowTeamChange;
}
public void setVotedToAllowGameMaster(boolean allowChange) {
votedToAllowGameMaster = allowChange;
}
public boolean getVotedToAllowGameMaster() {
return votedToAllowGameMaster;
}
public void setArtyAutoHitHexes(Vector<Coords> artyAutoHitHexes) {
this.artyAutoHitHexes = artyAutoHitHexes;
}
public Vector<Coords> getArtyAutoHitHexes() {
return artyAutoHitHexes;
}
public void addArtyAutoHitHex(Coords c) {
artyAutoHitHexes.add(c);
}
public int getInitialEntityCount() {
return initialEntityCount;
}
public void setInitialEntityCount(final int initialEntityCount) {
this.initialEntityCount = initialEntityCount;
}
public void changeInitialEntityCount(final int initialEntityCountChange) {
this.initialEntityCount += initialEntityCountChange;
}
/**
* Returns the combined strength (Battle Value/PV) of all the player's usable assets. This includes only
* units that should count according to {@link InGameObject#countForStrengthSum()}.
*
* @return The combined strength (BV/PV) of all the player's assets
*/
public int getBV() {
return game.getInGameObjects().stream()
.filter(this::isMyUnit)
.filter(InGameObject::countForStrengthSum)
.mapToInt(InGameObject::getStrength).sum();
}
/**
* Returns true when the given unit belongs to this Player.
*
* @param unit The unit
* @return True when the unit belongs to "me", this Player
*/
public boolean isMyUnit(InGameObject unit) {
return unit.getOwnerId() == id;
}
public int getInitialBV() {
return initialBV;
}
public void setInitialBV(final int initialBV) {
this.initialBV = initialBV;
}
public void changeInitialBV(final int initialBVChange) {
this.initialBV += initialBVChange;
}
@Override
public void setInitCompensationBonus(int newBonus) {
streakCompensationBonus = newBonus;
}
@Override
public int getInitCompensationBonus() {
return streakCompensationBonus;
}
public void setConstantInitBonus(int b) {
constantInitBonus = b;
}
public int getConstantInitBonus() {
return constantInitBonus;
}
/**
* @return the bonus to this player's initiative rolls granted by his units
*/
public int getTurnInitBonus() {
if (game == null) {
return 0;
}
int bonus = 0;
for (InGameObject object : game.getInGameObjects()) {
if (object instanceof Entity && ((Entity) object).getOwner().equals(this)) {
Entity entity = (Entity) object;
if (game.getOptions().booleanOption(OptionsConstants.ADVANCED_TACOPS_MOBILE_HQS)) {
bonus = Math.max(entity.getHQIniBonus(), bonus);
}
bonus = Math.max(bonus, entity.getQuirkIniBonus());
}
}
return bonus;
}
/**
* @return the bonus to this player's initiative rolls for the highest value initiative
* (i.e. the 'commander')
*/
public int getCommandBonus() {
if (game == null) {
return 0;
}
int commandb = 0;
for (InGameObject unit : game.getInGameObjects()) {
if (unit instanceof Entity) {
Entity entity = (Entity) unit;
if ((null != entity.getOwner())
&& entity.getOwner().equals(this)
&& !entity.isDestroyed()
&& entity.isDeployed()
&& !entity.isOffBoard()
&& entity.getCrew().isActive()
&& !entity.isCaptured()
&& !(entity instanceof MechWarrior)) {
int bonus = 0;
if (game.getOptions().booleanOption(OptionsConstants.RPG_COMMAND_INIT)) {
bonus = entity.getCrew().getCommandBonus();
}
//Even if the RPG option is not enabled, we still get the command bonus provided by special equipment.
//Since we are not designating a single force commander at this point, we assume a superheavy tripod
//is the force commander if that gives the highest bonus.
if (entity.hasCommandConsoleBonus() || entity.getCrew().hasActiveTechOfficer()) {
bonus += 2;
}
//Once we've gotten the status of the command console (if any), reset the flag that tracks
//the previous turn's action.
if (bonus > commandb) {
commandb = bonus;
}
}
}
}
return commandb;
}
public String getColorForPlayer() {
return "<B><font color='" + getColour().getHexString(0x00F0F0F0) + "'>" + getName() + "</font></B>";
}
/**
* Clears any data from this Player that should not be transmitted to other players from the server,
* such as email addresses. Note that this changes this Player's data permanently and should typically
* be done to a copy of the player, see {@link #copy()}.
*/
public void redactPrivateData() {
this.email = null;
}
@Override
public String toString() {
return "Player " + getId() + " (" + getName() + ")";
}
/**
* Two players are equal if their ids are equal
*/
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
} else if ((null == object) || (getClass() != object.getClass())) {
return false;
} else {
final Player other = (Player) object;
return other.id == id;
}
}
@Override
public int hashCode() {
return id;
}
public Player copy() {
var copy = new Player(id, name);
copy.email = email;
copy.game = game;
copy.team = team;
copy.done = done;
copy.ghost = ghost;
copy.bot = bot;
copy.observer = observer;
copy.gameMaster = gameMaster;
copy.seeAll = seeAll;
copy.singleBlind = singleBlind;
copy.startingPos = startingPos;
copy.startOffset = startOffset;
copy.startWidth = startWidth;
copy.startingAnyNWx = startingAnyNWx;
copy.startingAnyNWy = startingAnyNWy;
copy.startingAnySEx = startingAnySEx;
copy.startingAnySEy = startingAnySEy;
copy.numMfConv = numMfConv;
copy.numMfCmd = numMfCmd;
copy.numMfVibra = numMfVibra;
copy.numMfActive = numMfActive;
copy.numMfInferno = numMfInferno;
copy.artyAutoHitHexes = new Vector<>(artyAutoHitHexes);
copy.initialEntityCount = initialEntityCount;
copy.initialBV = initialBV;
copy.constantInitBonus = constantInitBonus;
copy.streakCompensationBonus = streakCompensationBonus;
copy.camouflage = camouflage;
copy.colour = colour;
copy.visibleMinefields = new Vector<>(visibleMinefields);
copy.admitsDefeat = admitsDefeat;
return copy;
}
} | MegaMek/megamek | megamek/src/megamek/common/Player.java | 5,954 | // deep deploy change to standard | line_comment | nl | /*
* Copyright (c) 2000-2004 Ben Mazur ([email protected])
* Copyright (c) 2024 - The MegaMek Team. All Rights Reserved.
*
* This file is part of MegaMek.
*
* MegaMek 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.
*
* MegaMek 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 MegaMek. If not, see <http://www.gnu.org/licenses/>.
*/
package megamek.common;
import megamek.client.ui.swing.util.PlayerColour;
import megamek.common.icons.Camouflage;
import megamek.common.options.OptionsConstants;
import java.util.Objects;
import java.util.Vector;
/**
* Represents a player in the game.
*
* Note that Player should be usable for any type of game (TW, AS, BF, SBF) and therefore should not
* make any direct use of Game, Entity, AlphaStrikeElement etc., instead using IGame and InGameObject if necessary.
*/
public final class Player extends TurnOrdered {
//region Variable Declarations
private static final long serialVersionUID = 6828849559007455761L;
public static final int PLAYER_NONE = -1;
public static final int TEAM_NONE = 0;
public static final int TEAM_UNASSIGNED = -1;
public static final String[] TEAM_NAMES = {"No Team", "Team 1", "Team 2", "Team 3", "Team 4", "Team 5"};
private transient IGame game;
private String name;
private String email;
private final int id;
private int team = TEAM_NONE;
private boolean done = false; // done with phase
private boolean ghost = false; // disconnected player
private boolean bot = false;
private boolean observer = false;
private boolean gameMaster = false;
private boolean seeAll = false; // Observer or Game Master can observe double-blind games
private boolean singleBlind = false; // Bot can observe double-blind games
// deployment settings
private int startingPos = Board.START_ANY;
private int startOffset = 0;
private int startWidth = 3;
private int startingAnyNWx = Entity.STARTING_ANY_NONE;
private int startingAnyNWy = Entity.STARTING_ANY_NONE;
private int startingAnySEx = Entity.STARTING_ANY_NONE;
private int startingAnySEy = Entity.STARTING_ANY_NONE;
// number of minefields
private int numMfConv = 0;
private int numMfCmd = 0;
private int numMfVibra = 0;
private int numMfActive = 0;
private int numMfInferno = 0;
// hexes that are automatically hit by artillery
private Vector<Coords> artyAutoHitHexes = new Vector<>();
private int initialEntityCount;
private int initialBV;
// initiative bonuses go here because we don't know if teams are rolling
// initiative collectively
// if they are then we pick the best non-zero bonuses
private int constantInitBonus = 0;
private int streakCompensationBonus = 0;
private Camouflage camouflage = new Camouflage(Camouflage.COLOUR_CAMOUFLAGE, PlayerColour.BLUE.name());
private PlayerColour colour = PlayerColour.BLUE;
private Vector<Minefield> visibleMinefields = new Vector<>();
private boolean admitsDefeat = false;
//Voting should not be stored in save game so marked transient
private transient boolean votedToAllowTeamChange = false;
private transient boolean votedToAllowGameMaster = false;
//endregion Variable Declarations
//region Constructors
public Player(int id, String name) {
this.name = name;
this.id = id;
}
//endregion Constructors
public Vector<Minefield> getMinefields() {
return visibleMinefields;
}
public void addMinefield(Minefield mf) {
visibleMinefields.addElement(mf);
}
public void addMinefields(Vector<Minefield> minefields) {
for (int i = 0; i < minefields.size(); i++) {
visibleMinefields.addElement(minefields.elementAt(i));
}
}
public void removeMinefield(Minefield mf) {
visibleMinefields.removeElement(mf);
}
public void removeMinefields() {
visibleMinefields.removeAllElements();
}
public void removeArtyAutoHitHexes() {
artyAutoHitHexes.removeAllElements();
}
public boolean containsMinefield(Minefield mf) {
return visibleMinefields.contains(mf);
}
public boolean hasMinefields() {
return (numMfCmd > 0) || (numMfConv > 0) || (numMfVibra > 0) || (numMfActive > 0) || (numMfInferno > 0);
}
public void setNbrMFConventional(int nbrMF) {
numMfConv = nbrMF;
}
public void setNbrMFCommand(int nbrMF) {
numMfCmd = nbrMF;
}
public void setNbrMFVibra(int nbrMF) {
numMfVibra = nbrMF;
}
public void setNbrMFActive(int nbrMF) {
numMfActive = nbrMF;
}
public void setNbrMFInferno(int nbrMF) {
numMfInferno = nbrMF;
}
public int getNbrMFConventional() {
return numMfConv;
}
public int getNbrMFCommand() {
return numMfCmd;
}
public int getNbrMFVibra() {
return numMfVibra;
}
public int getNbrMFActive() {
return numMfActive;
}
public int getNbrMFInferno() {
return numMfInferno;
}
public Camouflage getCamouflage() {
return camouflage;
}
public void setCamouflage(Camouflage camouflage) {
this.camouflage = camouflage;
}
public void setGame(IGame game) {
this.game = game;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getId() {
return id;
}
public int getTeam() {
return team;
}
public void setTeam(int team) {
this.team = team;
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
public boolean isGhost() {
return ghost;
}
public void setGhost(boolean ghost) {
this.ghost = ghost;
}
/**
* @return true if this player connected as a bot.
*/
public boolean isBot() {
return bot;
}
/**
* Sets whether this player connected as a bot.
*/
public void setBot(boolean bot) {
this.bot = bot;
}
/** @return true if this player may become a Game Master. Any human may be a GM*/
public boolean isGameMasterPermitted() {
return !bot;
}
/** @return true if {@link #gameMaster} flag is true and {@link #isGameMasterPermitted()}*/
public boolean isGameMaster() {
return (isGameMasterPermitted() && gameMaster);
}
/**
* If you are checking to see this player is a Game Master, use {@link #isGameMaster()} ()} instead
* @return the value of gameMaster flag, without checking if it is permitted.
*/
public boolean getGameMaster() {
return gameMaster;
}
/**
* sets {@link #gameMaster} but this only allows GM status if other conditions permits it.
* see {@link #isGameMaster()}
*/
public void setGameMaster(boolean gameMaster) {
this.gameMaster = gameMaster;
}
/** @return true if {@link #observer} flag is true and not in VICTORY phase*/
public boolean isObserver() {
if ((game != null) && game.getPhase().isVictory()) {
return false;
}
return observer;
}
/**
* sets {@link #seeAll}. This will only enable seeAll if other conditions allow it.
* see {@link #canIgnoreDoubleBlind()}
*/
public void setSeeAll(boolean seeAll) {
this.seeAll = seeAll;
}
/**
* If you are checking to see if double-blind applies to this player, use {@link #canIgnoreDoubleBlind()}
* @return the value of seeAll flag, without checking if it is permitted
*/
public boolean getSeeAll() {
return seeAll;
}
/**
* If you are checking to see if double-blind applies to this player, use {@link #canIgnoreDoubleBlind()}
* @return true if {@link #seeAll} is true and is permitted
*/
public boolean canSeeAll() {
return (isSeeAllPermitted() && seeAll);
}
/**
* If you are checking to see if double-blind applies to this player, use {@link #canIgnoreDoubleBlind()}
* @return true if player is allowed use seeAll
* */
public boolean isSeeAllPermitted() {
return gameMaster || observer;
}
/** set the {@link #observer} flag. Observers have no units ad no team */
public void setObserver(boolean observer) {
this.observer = observer;
}
/**
* sets {@link #seeAll}. This will only enable seeAll if other conditions allow it.
* see {@link #canIgnoreDoubleBlind()}
*/
public void setSingleBlind(boolean singleBlind) {
this.singleBlind = singleBlind;
}
/**
* If you are checking to see this player can ignore double-blind, use {@link #canIgnoreDoubleBlind()} ()} instead
* @return the value of singleBlind flag, without checking if it is permitted.
*/
public boolean getSingleBlind() {
return singleBlind;
}
/**
* @return true if singleBlind flag is true and {@link #isSingleBlindPermitted()}
*/
public boolean canSeeSingleBlind() {
return (isSingleBlindPermitted() && singleBlind);
}
/**
* If you are checking to see if double-blind applies to this player, use {@link #canIgnoreDoubleBlind()}
* @return true if player is allowed use singleblind (bots only)
* */
public boolean isSingleBlindPermitted() {
return bot;
}
/**
* Double-blind uses Line-of-sight to determine which units are displayed on the board
* and in reports. seeAll and singleBlind flags allow this to be ignored, granting a view
* of the entire map and units.
* @return true if this player ignores the double-blind setting.
*/
public boolean canIgnoreDoubleBlind() {
return canSeeSingleBlind() || canSeeAll();
}
public PlayerColour getColour() {
return colour;
}
public void setColour(PlayerColour colour) {
this.colour = Objects.requireNonNull(colour, "Colour cannot be set to null");
}
public int getStartingPos() {
return startingPos;
}
public void setStartingPos(int startingPos) {
this.startingPos = startingPos;
}
public int getStartOffset() {
return startOffset;
}
public void setStartOffset(int startOffset) {
this.startOffset = startOffset;
}
public int getStartWidth() {
return startWidth;
}
public void setStartWidth(int startWidth) {
this.startWidth = startWidth;
}
public int getStartingAnyNWx() {
return startingAnyNWx;
}
public void setStartingAnyNWx(int i) {
this.startingAnyNWx = i;
}
public int getStartingAnyNWy() {
return startingAnyNWy;
}
public void setStartingAnyNWy(int i) {
this.startingAnyNWy = i;
}
public int getStartingAnySEx() {
return startingAnySEx;
}
public void setStartingAnySEx(int i) {
this.startingAnySEx = i;
}
public int getStartingAnySEy() {
return startingAnySEy;
}
public void setStartingAnySEy(int i) {
this.startingAnySEy = i;
}
/**
* Set deployment zone to edge of board for reinforcements
*/
public void adjustStartingPosForReinforcements() {
if (startingPos > 10) {
startingPos -= 10; // deep deploy<SUF>
}
if (startingPos == Board.START_CENTER) {
startingPos = Board.START_ANY; // center changes to any
}
}
public boolean isEnemyOf(Player other) {
if (null == other) {
return true;
}
return (id != other.getId())
&& ((team == TEAM_NONE) || (team == TEAM_UNASSIGNED) || (team != other.getTeam()));
}
public void setAdmitsDefeat(boolean admitsDefeat) {
this.admitsDefeat = admitsDefeat;
}
public boolean admitsDefeat() {
return admitsDefeat;
}
public void setVotedToAllowTeamChange(boolean allowChange) {
votedToAllowTeamChange = allowChange;
}
public boolean getVotedToAllowTeamChange() {
return votedToAllowTeamChange;
}
public void setVotedToAllowGameMaster(boolean allowChange) {
votedToAllowGameMaster = allowChange;
}
public boolean getVotedToAllowGameMaster() {
return votedToAllowGameMaster;
}
public void setArtyAutoHitHexes(Vector<Coords> artyAutoHitHexes) {
this.artyAutoHitHexes = artyAutoHitHexes;
}
public Vector<Coords> getArtyAutoHitHexes() {
return artyAutoHitHexes;
}
public void addArtyAutoHitHex(Coords c) {
artyAutoHitHexes.add(c);
}
public int getInitialEntityCount() {
return initialEntityCount;
}
public void setInitialEntityCount(final int initialEntityCount) {
this.initialEntityCount = initialEntityCount;
}
public void changeInitialEntityCount(final int initialEntityCountChange) {
this.initialEntityCount += initialEntityCountChange;
}
/**
* Returns the combined strength (Battle Value/PV) of all the player's usable assets. This includes only
* units that should count according to {@link InGameObject#countForStrengthSum()}.
*
* @return The combined strength (BV/PV) of all the player's assets
*/
public int getBV() {
return game.getInGameObjects().stream()
.filter(this::isMyUnit)
.filter(InGameObject::countForStrengthSum)
.mapToInt(InGameObject::getStrength).sum();
}
/**
* Returns true when the given unit belongs to this Player.
*
* @param unit The unit
* @return True when the unit belongs to "me", this Player
*/
public boolean isMyUnit(InGameObject unit) {
return unit.getOwnerId() == id;
}
public int getInitialBV() {
return initialBV;
}
public void setInitialBV(final int initialBV) {
this.initialBV = initialBV;
}
public void changeInitialBV(final int initialBVChange) {
this.initialBV += initialBVChange;
}
@Override
public void setInitCompensationBonus(int newBonus) {
streakCompensationBonus = newBonus;
}
@Override
public int getInitCompensationBonus() {
return streakCompensationBonus;
}
public void setConstantInitBonus(int b) {
constantInitBonus = b;
}
public int getConstantInitBonus() {
return constantInitBonus;
}
/**
* @return the bonus to this player's initiative rolls granted by his units
*/
public int getTurnInitBonus() {
if (game == null) {
return 0;
}
int bonus = 0;
for (InGameObject object : game.getInGameObjects()) {
if (object instanceof Entity && ((Entity) object).getOwner().equals(this)) {
Entity entity = (Entity) object;
if (game.getOptions().booleanOption(OptionsConstants.ADVANCED_TACOPS_MOBILE_HQS)) {
bonus = Math.max(entity.getHQIniBonus(), bonus);
}
bonus = Math.max(bonus, entity.getQuirkIniBonus());
}
}
return bonus;
}
/**
* @return the bonus to this player's initiative rolls for the highest value initiative
* (i.e. the 'commander')
*/
public int getCommandBonus() {
if (game == null) {
return 0;
}
int commandb = 0;
for (InGameObject unit : game.getInGameObjects()) {
if (unit instanceof Entity) {
Entity entity = (Entity) unit;
if ((null != entity.getOwner())
&& entity.getOwner().equals(this)
&& !entity.isDestroyed()
&& entity.isDeployed()
&& !entity.isOffBoard()
&& entity.getCrew().isActive()
&& !entity.isCaptured()
&& !(entity instanceof MechWarrior)) {
int bonus = 0;
if (game.getOptions().booleanOption(OptionsConstants.RPG_COMMAND_INIT)) {
bonus = entity.getCrew().getCommandBonus();
}
//Even if the RPG option is not enabled, we still get the command bonus provided by special equipment.
//Since we are not designating a single force commander at this point, we assume a superheavy tripod
//is the force commander if that gives the highest bonus.
if (entity.hasCommandConsoleBonus() || entity.getCrew().hasActiveTechOfficer()) {
bonus += 2;
}
//Once we've gotten the status of the command console (if any), reset the flag that tracks
//the previous turn's action.
if (bonus > commandb) {
commandb = bonus;
}
}
}
}
return commandb;
}
public String getColorForPlayer() {
return "<B><font color='" + getColour().getHexString(0x00F0F0F0) + "'>" + getName() + "</font></B>";
}
/**
* Clears any data from this Player that should not be transmitted to other players from the server,
* such as email addresses. Note that this changes this Player's data permanently and should typically
* be done to a copy of the player, see {@link #copy()}.
*/
public void redactPrivateData() {
this.email = null;
}
@Override
public String toString() {
return "Player " + getId() + " (" + getName() + ")";
}
/**
* Two players are equal if their ids are equal
*/
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
} else if ((null == object) || (getClass() != object.getClass())) {
return false;
} else {
final Player other = (Player) object;
return other.id == id;
}
}
@Override
public int hashCode() {
return id;
}
public Player copy() {
var copy = new Player(id, name);
copy.email = email;
copy.game = game;
copy.team = team;
copy.done = done;
copy.ghost = ghost;
copy.bot = bot;
copy.observer = observer;
copy.gameMaster = gameMaster;
copy.seeAll = seeAll;
copy.singleBlind = singleBlind;
copy.startingPos = startingPos;
copy.startOffset = startOffset;
copy.startWidth = startWidth;
copy.startingAnyNWx = startingAnyNWx;
copy.startingAnyNWy = startingAnyNWy;
copy.startingAnySEx = startingAnySEx;
copy.startingAnySEy = startingAnySEy;
copy.numMfConv = numMfConv;
copy.numMfCmd = numMfCmd;
copy.numMfVibra = numMfVibra;
copy.numMfActive = numMfActive;
copy.numMfInferno = numMfInferno;
copy.artyAutoHitHexes = new Vector<>(artyAutoHitHexes);
copy.initialEntityCount = initialEntityCount;
copy.initialBV = initialBV;
copy.constantInitBonus = constantInitBonus;
copy.streakCompensationBonus = streakCompensationBonus;
copy.camouflage = camouflage;
copy.colour = colour;
copy.visibleMinefields = new Vector<>(visibleMinefields);
copy.admitsDefeat = admitsDefeat;
return copy;
}
} |
78474_27 | import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.Vector;
public class MovieLensGender {
ArrayList<String> train;
ArrayList<String> test;
HashMap<String, User> users;
HashMap<String, Movie> movies;
HashMap<String, String> similar;
public MovieLensGender(){
users = new HashMap<String, User>();
movies = new HashMap<String, Movie>();
similar = new HashMap<String, String>();
}
public void setHyperParams(){
//These are not the best values for hyper-parameters.
//Find the best values over a validation set.
GlobalParams.ethaForWeights = 0.01; //Learning rate for weights
GlobalParams.ethaForHiddens = 0.03; //Learning rate for numeric latent properties
GlobalParams.lambdaForWeights = 0.0002; //Regularization hyper-parameter for weights
GlobalParams.lambdaForHiddens = 0.0002; //Regularization hyper-parameter for numeric latent properties
GlobalParams.lambdaForMean = 0.85; //Regularization towards the mean
GlobalParams.numIteration = 300; //Maximum number of iterations
GlobalParams.numRandomWalk = 1; //Initialize the network K times and pick the best initialization
GlobalParams.splitPercentage = 0.80; //Split data for train/test
GlobalParams.regularizationTypeForWeights = "L1"; //Type of regularization for weights
GlobalParams.regularizationTypeForHiddens = "L1"; //Type of regularization for numeric latent properties
GlobalParams.maxRandom = 0.01; //When generating random numbers for initialization, this is the maximum value
}
public void createTrainTestForCV(int fold){
List<String> user_ids = Arrays.asList(users.keySet().toArray(new String[users.keySet().size()]));
train = new ArrayList<String>();
test = new ArrayList<String>();
int numUsersInTest = user_ids.size() / GlobalParams.numFolds;
double index = 0;
for(String user_id : user_ids){
if(index < fold * numUsersInTest || index > (fold + 1) * numUsersInTest)
train.add(user_id);
else{
test.add(user_id);
}
index++;
}
}
public void readFile() throws FileNotFoundException{
BufferedReader br = new BufferedReader(new FileReader(new File("datasets/ml-1m/users.dat")));
for(String nextLine : br.lines().toArray(String[]::new)){
String[] line = nextLine.split("::");
User user = new User(line[0]);
user.gender = line[1];
user.age = line[2];
user.occupation = line[3];
users.put(line[0], user);
}
br = new BufferedReader(new FileReader(new File("datasets/ml-1m/movies.dat")));
for(String nextLine : br.lines().toArray(String[]::new)){
String[] line = nextLine.split("::");
Movie movie = new Movie(line[0]);
for(String genre : line[2].split(",")){
movie.genre.put(genre, "true");
}
movies.put(line[0], movie);
}
br = new BufferedReader(new FileReader(new File("datasets/ml-1m/ratings.dat")));
for(String nextLine : br.lines().toArray(String[]::new)){
String[] line = nextLine.split("::");
users.get(line[0]).moviesRated.put(line[1], "yes");
users.get(line[0]).moviesRatedVector.addElement(line[1]);
movies.get(line[1]).ratedBy.put(line[0], "yes");
}
}
public void learnModel(){
//This version has two numeric latent properties and one hidden layer. The final version used in the paper has two hidden layers.
HashMap<String, HashMap<String, String>> data = new HashMap<String, HashMap<String, String>>();
String targetPRV = "Gender";
String targetValue = "M";
String[] genres = {"Action", "Drama"};
String[] occupations = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"};
String[] ages = {"1", "18", "25", "35", "45", "50", "56"};
String[] rates = {"yes"};
for(String genre : genres){
data.put(genre, new HashMap<String, String>());
}
data.put("Age", new HashMap<String, String>());
data.put("Gender", new HashMap<String, String>());
data.put("Occupation", new HashMap<String, String>());
data.put("Rate", new HashMap<String, String>());
data.put("RatePrime", new HashMap<String, String>());
data.put("FeatSim", new HashMap<String, String>());
for(String movie_id : movies.keySet()){
for(String genre : genres){
data.get(genre).put(movie_id, movies.get(movie_id).genre.getOrDefault(genre, "false"));
}
}
for(String key : this.similar.keySet()){
data.get("FeatSim").put(key, this.similar.get(key));
}
double probTargetClass = 0.0;
for(String user_id : train){
if(users.get(user_id).gender.equals(targetValue))
probTargetClass++;
data.get("Age").put(user_id, users.get(user_id).age);
data.get("Gender").put(user_id, users.get(user_id).gender);
data.get("Occupation").put(user_id, users.get(user_id).occupation);
for(String movie_id : users.get(user_id).moviesRated.keySet()){
data.get("Rate").put(user_id + "," + movie_id, users.get(user_id).moviesRated.get(movie_id));
data.get("RatePrime").put(user_id + "," + movie_id, users.get(user_id).moviesRated.get(movie_id));
}
}
probTargetClass /= train.size();
Set<String> movie_ids = movies.keySet();
Set<String> user_ids = users.keySet();
LogVar m = new LogVar("m", movie_ids.toArray(new String[movie_ids.size()]), "movie");
LogVar m_prime = new LogVar("m_prime", movie_ids.toArray(new String[movie_ids.size()]), "movie");
LogVar p = new LogVar("p", user_ids.toArray(new String[user_ids.size()]), "people");
PRV rate = new PRV("Rate", new LogVar[]{p, m}, "observed_input");
PRV rate_prime = new PRV("RatePrime", new LogVar[]{p, m_prime}, "observed_input");
PRV[] genre_prvs = new PRV[genres.length];
for(int i = 0; i < genre_prvs.length; i++)
genre_prvs[i] = new PRV(genres[i], new LogVar[]{m}, "observed_input");
PRV gender = new PRV("Gender", new LogVar[]{p}, "observed_input");
PRV age = new PRV("Age", new LogVar[]{p}, "observed_input");
PRV occupation = new PRV("Occupation", new LogVar[]{p}, "observed_input");
PRV feat1_m = new PRV("Feat1_m", new LogVar[]{m}, "unobserved_input");
data.put("Feat1_m", feat1_m.randomValues());
PRV feat2_m = new PRV("Feat2_m", new LogVar[]{m}, "unobserved_input");
data.put("Feat2_m", feat2_m.randomValues());
PRV[][] rates_genres_prvs = new PRV[rates.length][genres.length];
PRV[] hidden_input1_prvs = new PRV[rates.length];
PRV[] hidden_input2_prvs = new PRV[rates.length];
for(int i = 0; i < rates.length; i++){
for(int j = 0; j < genres.length; j++){
rates_genres_prvs[i][j] = new PRV("H" + i + "_" + j, new LogVar[]{p}, "hidden");
}
hidden_input1_prvs[i] = new PRV("HI1_" + i, new LogVar[]{p}, "hidden");
hidden_input2_prvs[i] = new PRV("HI2_" + i, new LogVar[]{p}, "hidden");
}
WeightedFormula base = new WeightedFormula(new Literal[]{}, 1);
WeightedFormula[][] rates_genres_wfs = new WeightedFormula[rates.length][genres.length];
WeightedFormula[] hidden_input1_wfs = new WeightedFormula[rates.length];
WeightedFormula[] hidden_input2_wfs = new WeightedFormula[rates.length];
WeightedFormula[][] hidden_layer1_rates_genres_wfs = new WeightedFormula[rates.length][genres.length];
WeightedFormula[] hidden_layer1_hidden_input1_wfs = new WeightedFormula[rates.length];
WeightedFormula[] hidden_layer1_hidden_input2_wfs = new WeightedFormula[rates.length];
for(int i = 0; i < rates.length; i++){
for(int j = 0; j < genres.length; j++){
rates_genres_wfs[i][j] = new WeightedFormula(new Literal[]{rate.lit(rates[i]), genre_prvs[j].lit("true")}, 1);
hidden_layer1_rates_genres_wfs[i][j] = new WeightedFormula(new Literal[]{rates_genres_prvs[i][j].lit("NA!")}, 1);
}
hidden_input1_wfs[i] = new WeightedFormula(new Literal[]{rate.lit(rates[i]), feat1_m.lit("NA!")}, 1);
hidden_input2_wfs[i] = new WeightedFormula(new Literal[]{rate.lit(rates[i]), feat2_m.lit("NA!")}, 1);
hidden_layer1_hidden_input1_wfs[i] = new WeightedFormula(new Literal[]{hidden_input1_prvs[i].lit("NA!")}, 1);
hidden_layer1_hidden_input2_wfs[i] = new WeightedFormula(new Literal[]{hidden_input2_prvs[i].lit("NA!")}, 1);
}
WeightedFormula[] occupation_wfs = new WeightedFormula[occupations.length];
for(int i = 0; i < occupation_wfs.length; i++){
occupation_wfs[i] = new WeightedFormula(new Literal[]{occupation.lit(occupations[i])}, 1);
}
WeightedFormula[] age_wfs = new WeightedFormula[ages.length];
for(int i = 0; i < age_wfs.length; i++){
age_wfs[i] = new WeightedFormula(new Literal[]{age.lit(ages[i])}, 1);
}
RelNeuron[][] rates_genres_rns = new RelNeuron[rates.length][genres.length];
for(int i = 0; i < rates.length; i++){
for(int j = 0; j < genres.length; j++){
rates_genres_rns[i][j] = new RelNeuron(rates_genres_prvs[i][j], new WeightedFormula[]{rates_genres_wfs[i][j], base});
}
}
RelNeuron[] hidden_input1_rns = new RelNeuron[rates.length];
for(int i = 0; i < rates.length; i++){
hidden_input1_rns[i] = new RelNeuron(hidden_input1_prvs[i], new WeightedFormula[]{hidden_input1_wfs[i], base});
}
RelNeuron[] hidden_input2_rns = new RelNeuron[rates.length];
for(int i = 0; i < rates.length; i++){
hidden_input2_rns[i] = new RelNeuron(hidden_input2_prvs[i], new WeightedFormula[]{hidden_input2_wfs[i], base});
}
int num_hidden_inputs = 2;
WeightedFormula[] gender_wfs = new WeightedFormula[1 + occupation_wfs.length + age_wfs.length + rates.length * genres.length + num_hidden_inputs * rates.length];
int index = 0;
gender_wfs[index++] = new WeightedFormula(base);
for(int i = 0; i < occupation_wfs.length; i++)
gender_wfs[index++] = occupation_wfs[i];
for(int i = 0; i < age_wfs.length; i++)
gender_wfs[index++] = age_wfs[i];
for(int i = 0; i < rates.length; i++)
for(int j = 0; j < genres.length; j++)
gender_wfs[index++] = hidden_layer1_rates_genres_wfs[i][j];
for(int i = 0; i < hidden_input1_wfs.length; i++)
gender_wfs[index++] = hidden_layer1_hidden_input1_wfs[i];
for(int i = 0; i < hidden_input2_wfs.length; i++)
gender_wfs[index++] = hidden_layer1_hidden_input2_wfs[i];
RelNeuron gender_rn = new RelNeuron(gender, gender_wfs);
RelNeuron[] layer1_rns = new RelNeuron[rates.length * genres.length + num_hidden_inputs * rates.length];
index = 0;
for(int i = 0; i < rates.length; i++)
for(int j = 0; j < genres.length; j++)
layer1_rns[index++] = rates_genres_rns[i][j];
for(int i = 0; i < rates.length; i++)
layer1_rns[index++] = hidden_input1_rns[i];
for(int i = 0; i < rates.length; i++)
layer1_rns[index++] = hidden_input2_rns[i];
Layer linear_layer1 = new LinearLayer(layer1_rns);
Layer sig_layer1 = new SigmoidLayer();
Layer linear_layer2 = new LinearLayer(new RelNeuron[]{gender_rn});
Layer sig_layer2 = new SigmoidLayer();
Layer sum_sqr_error_layer = new SumSquaredErrorLayer(targetValue);
RNN rnn = new RNN(new Layer[]{linear_layer1, sig_layer1, linear_layer2, sig_layer2, sum_sqr_error_layer});
double train_error = rnn.train(data, data.get(targetPRV));
System.out.println("The final error on train data: " + train_error);
//calculating the performance on train data
System.out.println("Performance on train data");
HashMap<String, String> predictions = rnn.test(data).get(targetPRV);
Measures measures = new Measures(data.get(targetPRV), predictions, targetValue);
System.out.println("Accuracy: " + measures.accuracy(0.5));
System.out.println("MAE: " + measures.MAE());
System.out.println("MSE: " + measures.MSE());
System.out.println("ACLL: " + measures.ACLL());
//calculating the performance on test data
GlobalParams.learningStatus = "test";
System.out.println("Performance on test data");
predictions = new HashMap<String, String>();
HashMap<String, String> targets = new HashMap<String, String>();
//Adding n user in each run
System.out.println(test.size());
for(int i = 0; i < test.size(); i += GlobalParams.testBatch){
for(int j = i; j < i + GlobalParams.testBatch && j < test.size(); j++){
targets.put(test.get(j), users.get(test.get(j)).gender);
}
for(int j = i; j < i + GlobalParams.testBatch && j < test.size(); j++){
data.get("Gender").put(test.get(j), users.get(test.get(j)).gender);
data.get("Age").put(test.get(j), users.get(test.get(j)).age);
data.get("Occupation").put(test.get(j), users.get(test.get(j)).occupation);
for(String movie_id : users.get(test.get(j)).moviesRated.keySet()){
data.get("Rate").put(test.get(j) + "," + movie_id, users.get(test.get(j)).moviesRated.get(movie_id));
}
}
HashMap<String, String> rnn_preds = rnn.test(data).get(targetPRV);
for(int j = i; j < i + GlobalParams.testBatch && j < test.size(); j++){
double userPred = Double.parseDouble(rnn_preds.get(test.get(j)));
userPred = GlobalParams.lambdaForMean * userPred + (1 - GlobalParams.lambdaForMean) * probTargetClass;
predictions.put(test.get(j), "" + userPred);
}
for(int j = i; j < i + GlobalParams.testBatch && j < test.size(); j++){
data.get("Gender").remove(test.get(j));
data.get("Age").remove(test.get(j));
data.get("Occupation").remove(test.get(j));
for(String movie_id : users.get(test.get(j)).moviesRated.keySet()){
data.get("Rate").remove(test.get(j) + "," + movie_id);
}
}
}
measures = new Measures(targets, predictions, targetValue);
System.out.println("Accuracy with 0.5 boundary: " + measures.accuracy(0.5));
System.out.println("MAE: " + measures.MAE());
System.out.println("MSE: " + measures.MSE());
System.out.println("ACLL: " + measures.ACLL());
// This part of the code was used for the experiment on extrapolating to unseen cases and addressing the population size issue
// int[] Qs = {75, 100};
// int[] Qs = {0, 1, 2, 3, 4, 5, 7, 10, 15, 20, 30, 40, 50, 75, 100, 125, 150, 200, 250, 300, 400, 500};
// for(int q = 0; q < Qs.length; q++){
// predictions = new HashMap<String, String>();
// targets = new HashMap<String, String>();
// for(int i = 0; i < test.size(); i += GlobalParams.testBatch){
// for(int j = i; j < i + GlobalParams.testBatch && j < test.size(); j++){
// targets.put(test.get(j), users.get(test.get(j)).gender);
// }
// for(int j = i; j < i + GlobalParams.testBatch && j < test.size(); j++){
// data.get("Gender").put(test.get(j), users.get(test.get(j)).gender);
// data.get("Age").put(test.get(j), users.get(test.get(j)).age);
// data.get("Occupation").put(test.get(j), users.get(test.get(j)).occupation);
// for(int k = 0; k < Qs[q] && k < users.get(test.get(j)).moviesRatedVector.size(); k++){
// String movie_id = users.get(test.get(j)).moviesRatedVector.elementAt(k);
// data.get("Rate").put(test.get(j) + "," + movie_id, "yes");
// }
// // for(String movie_id : users.get(test.get(j)).moviesRated.keySet()){
// // data.get("Rate").put(test.get(j) + "," + movie_id, users.get(test.get(j)).moviesRated.get(movie_id));
// // }
// }
//
// HashMap<String, String> rnn_preds = rnn.test(data).get(targetPRV);
// for(int j = i; j < i + GlobalParams.testBatch && j < test.size(); j++){
// double userPred = Double.parseDouble(rnn_preds.get(test.get(j)));
// userPred = GlobalParams.lambdaForMean * userPred + (1 - GlobalParams.lambdaForMean) * 0.71;
// predictions.put(test.get(j), "" + userPred);
// }
//
// for(int j = i; j < i + GlobalParams.testBatch && j < test.size(); j++){
// data.get("Gender").remove(test.get(j));
// data.get("Age").remove(test.get(j));
// data.get("Occupation").remove(test.get(j));
// for(int k = 0; k < Qs[q] && k < users.get(test.get(j)).moviesRatedVector.size(); k++){
// String movie_id = users.get(test.get(j)).moviesRatedVector.elementAt(k);
// data.get("Rate").remove(test.get(j) + "," + movie_id);
// }
// // for(String movie_id : users.get(test.get(j)).moviesRated.keySet()){
// // data.get("Rate").remove(test.get(j) + "," + movie_id);
// // }
// }
// }
// System.out.println("Q = " + Qs[q]);
// measures = new Measures(targets, predictions, targetValue);
// System.out.println("Accuracy with 0.5 boundary: " + measures.accuracy(0.5));
// System.out.println("MSE: " + measures.MSE());
// System.out.println("ACLL: " + measures.ACLL());
// }
}
public static void main(String[] args) throws FileNotFoundException {
System.out.println("MovieLensGenderLarge");
for(int i = 0; i < GlobalParams.numRuns; i++){
MovieLensGender mlg = new MovieLensGender();
mlg.setHyperParams();
mlg.readFile();
mlg.createTrainTestForCV(0);
mlg.learnModel();
}
}
}
class User {
String id;
String age;
String gender;
String occupation;
HashMap<String, String> moviesRated;
Vector<String> moviesRatedVector;
public User(String id){
this.id = id;
moviesRated = new HashMap<String, String>();
moviesRatedVector = new Vector<String>();
}
}
class Movie {
String id;
HashMap<String, String> genre;
HashMap<String, String> ratedBy;
public Movie(String id){
this.id = id;
ratedBy = new HashMap<String, String>();
genre = new HashMap<String, String>();
}
} | Mehran-k/RelNN | MovieLensGender.java | 6,765 | // String movie_id = users.get(test.get(j)).moviesRatedVector.elementAt(k);
| line_comment | nl | import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.Vector;
public class MovieLensGender {
ArrayList<String> train;
ArrayList<String> test;
HashMap<String, User> users;
HashMap<String, Movie> movies;
HashMap<String, String> similar;
public MovieLensGender(){
users = new HashMap<String, User>();
movies = new HashMap<String, Movie>();
similar = new HashMap<String, String>();
}
public void setHyperParams(){
//These are not the best values for hyper-parameters.
//Find the best values over a validation set.
GlobalParams.ethaForWeights = 0.01; //Learning rate for weights
GlobalParams.ethaForHiddens = 0.03; //Learning rate for numeric latent properties
GlobalParams.lambdaForWeights = 0.0002; //Regularization hyper-parameter for weights
GlobalParams.lambdaForHiddens = 0.0002; //Regularization hyper-parameter for numeric latent properties
GlobalParams.lambdaForMean = 0.85; //Regularization towards the mean
GlobalParams.numIteration = 300; //Maximum number of iterations
GlobalParams.numRandomWalk = 1; //Initialize the network K times and pick the best initialization
GlobalParams.splitPercentage = 0.80; //Split data for train/test
GlobalParams.regularizationTypeForWeights = "L1"; //Type of regularization for weights
GlobalParams.regularizationTypeForHiddens = "L1"; //Type of regularization for numeric latent properties
GlobalParams.maxRandom = 0.01; //When generating random numbers for initialization, this is the maximum value
}
public void createTrainTestForCV(int fold){
List<String> user_ids = Arrays.asList(users.keySet().toArray(new String[users.keySet().size()]));
train = new ArrayList<String>();
test = new ArrayList<String>();
int numUsersInTest = user_ids.size() / GlobalParams.numFolds;
double index = 0;
for(String user_id : user_ids){
if(index < fold * numUsersInTest || index > (fold + 1) * numUsersInTest)
train.add(user_id);
else{
test.add(user_id);
}
index++;
}
}
public void readFile() throws FileNotFoundException{
BufferedReader br = new BufferedReader(new FileReader(new File("datasets/ml-1m/users.dat")));
for(String nextLine : br.lines().toArray(String[]::new)){
String[] line = nextLine.split("::");
User user = new User(line[0]);
user.gender = line[1];
user.age = line[2];
user.occupation = line[3];
users.put(line[0], user);
}
br = new BufferedReader(new FileReader(new File("datasets/ml-1m/movies.dat")));
for(String nextLine : br.lines().toArray(String[]::new)){
String[] line = nextLine.split("::");
Movie movie = new Movie(line[0]);
for(String genre : line[2].split(",")){
movie.genre.put(genre, "true");
}
movies.put(line[0], movie);
}
br = new BufferedReader(new FileReader(new File("datasets/ml-1m/ratings.dat")));
for(String nextLine : br.lines().toArray(String[]::new)){
String[] line = nextLine.split("::");
users.get(line[0]).moviesRated.put(line[1], "yes");
users.get(line[0]).moviesRatedVector.addElement(line[1]);
movies.get(line[1]).ratedBy.put(line[0], "yes");
}
}
public void learnModel(){
//This version has two numeric latent properties and one hidden layer. The final version used in the paper has two hidden layers.
HashMap<String, HashMap<String, String>> data = new HashMap<String, HashMap<String, String>>();
String targetPRV = "Gender";
String targetValue = "M";
String[] genres = {"Action", "Drama"};
String[] occupations = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"};
String[] ages = {"1", "18", "25", "35", "45", "50", "56"};
String[] rates = {"yes"};
for(String genre : genres){
data.put(genre, new HashMap<String, String>());
}
data.put("Age", new HashMap<String, String>());
data.put("Gender", new HashMap<String, String>());
data.put("Occupation", new HashMap<String, String>());
data.put("Rate", new HashMap<String, String>());
data.put("RatePrime", new HashMap<String, String>());
data.put("FeatSim", new HashMap<String, String>());
for(String movie_id : movies.keySet()){
for(String genre : genres){
data.get(genre).put(movie_id, movies.get(movie_id).genre.getOrDefault(genre, "false"));
}
}
for(String key : this.similar.keySet()){
data.get("FeatSim").put(key, this.similar.get(key));
}
double probTargetClass = 0.0;
for(String user_id : train){
if(users.get(user_id).gender.equals(targetValue))
probTargetClass++;
data.get("Age").put(user_id, users.get(user_id).age);
data.get("Gender").put(user_id, users.get(user_id).gender);
data.get("Occupation").put(user_id, users.get(user_id).occupation);
for(String movie_id : users.get(user_id).moviesRated.keySet()){
data.get("Rate").put(user_id + "," + movie_id, users.get(user_id).moviesRated.get(movie_id));
data.get("RatePrime").put(user_id + "," + movie_id, users.get(user_id).moviesRated.get(movie_id));
}
}
probTargetClass /= train.size();
Set<String> movie_ids = movies.keySet();
Set<String> user_ids = users.keySet();
LogVar m = new LogVar("m", movie_ids.toArray(new String[movie_ids.size()]), "movie");
LogVar m_prime = new LogVar("m_prime", movie_ids.toArray(new String[movie_ids.size()]), "movie");
LogVar p = new LogVar("p", user_ids.toArray(new String[user_ids.size()]), "people");
PRV rate = new PRV("Rate", new LogVar[]{p, m}, "observed_input");
PRV rate_prime = new PRV("RatePrime", new LogVar[]{p, m_prime}, "observed_input");
PRV[] genre_prvs = new PRV[genres.length];
for(int i = 0; i < genre_prvs.length; i++)
genre_prvs[i] = new PRV(genres[i], new LogVar[]{m}, "observed_input");
PRV gender = new PRV("Gender", new LogVar[]{p}, "observed_input");
PRV age = new PRV("Age", new LogVar[]{p}, "observed_input");
PRV occupation = new PRV("Occupation", new LogVar[]{p}, "observed_input");
PRV feat1_m = new PRV("Feat1_m", new LogVar[]{m}, "unobserved_input");
data.put("Feat1_m", feat1_m.randomValues());
PRV feat2_m = new PRV("Feat2_m", new LogVar[]{m}, "unobserved_input");
data.put("Feat2_m", feat2_m.randomValues());
PRV[][] rates_genres_prvs = new PRV[rates.length][genres.length];
PRV[] hidden_input1_prvs = new PRV[rates.length];
PRV[] hidden_input2_prvs = new PRV[rates.length];
for(int i = 0; i < rates.length; i++){
for(int j = 0; j < genres.length; j++){
rates_genres_prvs[i][j] = new PRV("H" + i + "_" + j, new LogVar[]{p}, "hidden");
}
hidden_input1_prvs[i] = new PRV("HI1_" + i, new LogVar[]{p}, "hidden");
hidden_input2_prvs[i] = new PRV("HI2_" + i, new LogVar[]{p}, "hidden");
}
WeightedFormula base = new WeightedFormula(new Literal[]{}, 1);
WeightedFormula[][] rates_genres_wfs = new WeightedFormula[rates.length][genres.length];
WeightedFormula[] hidden_input1_wfs = new WeightedFormula[rates.length];
WeightedFormula[] hidden_input2_wfs = new WeightedFormula[rates.length];
WeightedFormula[][] hidden_layer1_rates_genres_wfs = new WeightedFormula[rates.length][genres.length];
WeightedFormula[] hidden_layer1_hidden_input1_wfs = new WeightedFormula[rates.length];
WeightedFormula[] hidden_layer1_hidden_input2_wfs = new WeightedFormula[rates.length];
for(int i = 0; i < rates.length; i++){
for(int j = 0; j < genres.length; j++){
rates_genres_wfs[i][j] = new WeightedFormula(new Literal[]{rate.lit(rates[i]), genre_prvs[j].lit("true")}, 1);
hidden_layer1_rates_genres_wfs[i][j] = new WeightedFormula(new Literal[]{rates_genres_prvs[i][j].lit("NA!")}, 1);
}
hidden_input1_wfs[i] = new WeightedFormula(new Literal[]{rate.lit(rates[i]), feat1_m.lit("NA!")}, 1);
hidden_input2_wfs[i] = new WeightedFormula(new Literal[]{rate.lit(rates[i]), feat2_m.lit("NA!")}, 1);
hidden_layer1_hidden_input1_wfs[i] = new WeightedFormula(new Literal[]{hidden_input1_prvs[i].lit("NA!")}, 1);
hidden_layer1_hidden_input2_wfs[i] = new WeightedFormula(new Literal[]{hidden_input2_prvs[i].lit("NA!")}, 1);
}
WeightedFormula[] occupation_wfs = new WeightedFormula[occupations.length];
for(int i = 0; i < occupation_wfs.length; i++){
occupation_wfs[i] = new WeightedFormula(new Literal[]{occupation.lit(occupations[i])}, 1);
}
WeightedFormula[] age_wfs = new WeightedFormula[ages.length];
for(int i = 0; i < age_wfs.length; i++){
age_wfs[i] = new WeightedFormula(new Literal[]{age.lit(ages[i])}, 1);
}
RelNeuron[][] rates_genres_rns = new RelNeuron[rates.length][genres.length];
for(int i = 0; i < rates.length; i++){
for(int j = 0; j < genres.length; j++){
rates_genres_rns[i][j] = new RelNeuron(rates_genres_prvs[i][j], new WeightedFormula[]{rates_genres_wfs[i][j], base});
}
}
RelNeuron[] hidden_input1_rns = new RelNeuron[rates.length];
for(int i = 0; i < rates.length; i++){
hidden_input1_rns[i] = new RelNeuron(hidden_input1_prvs[i], new WeightedFormula[]{hidden_input1_wfs[i], base});
}
RelNeuron[] hidden_input2_rns = new RelNeuron[rates.length];
for(int i = 0; i < rates.length; i++){
hidden_input2_rns[i] = new RelNeuron(hidden_input2_prvs[i], new WeightedFormula[]{hidden_input2_wfs[i], base});
}
int num_hidden_inputs = 2;
WeightedFormula[] gender_wfs = new WeightedFormula[1 + occupation_wfs.length + age_wfs.length + rates.length * genres.length + num_hidden_inputs * rates.length];
int index = 0;
gender_wfs[index++] = new WeightedFormula(base);
for(int i = 0; i < occupation_wfs.length; i++)
gender_wfs[index++] = occupation_wfs[i];
for(int i = 0; i < age_wfs.length; i++)
gender_wfs[index++] = age_wfs[i];
for(int i = 0; i < rates.length; i++)
for(int j = 0; j < genres.length; j++)
gender_wfs[index++] = hidden_layer1_rates_genres_wfs[i][j];
for(int i = 0; i < hidden_input1_wfs.length; i++)
gender_wfs[index++] = hidden_layer1_hidden_input1_wfs[i];
for(int i = 0; i < hidden_input2_wfs.length; i++)
gender_wfs[index++] = hidden_layer1_hidden_input2_wfs[i];
RelNeuron gender_rn = new RelNeuron(gender, gender_wfs);
RelNeuron[] layer1_rns = new RelNeuron[rates.length * genres.length + num_hidden_inputs * rates.length];
index = 0;
for(int i = 0; i < rates.length; i++)
for(int j = 0; j < genres.length; j++)
layer1_rns[index++] = rates_genres_rns[i][j];
for(int i = 0; i < rates.length; i++)
layer1_rns[index++] = hidden_input1_rns[i];
for(int i = 0; i < rates.length; i++)
layer1_rns[index++] = hidden_input2_rns[i];
Layer linear_layer1 = new LinearLayer(layer1_rns);
Layer sig_layer1 = new SigmoidLayer();
Layer linear_layer2 = new LinearLayer(new RelNeuron[]{gender_rn});
Layer sig_layer2 = new SigmoidLayer();
Layer sum_sqr_error_layer = new SumSquaredErrorLayer(targetValue);
RNN rnn = new RNN(new Layer[]{linear_layer1, sig_layer1, linear_layer2, sig_layer2, sum_sqr_error_layer});
double train_error = rnn.train(data, data.get(targetPRV));
System.out.println("The final error on train data: " + train_error);
//calculating the performance on train data
System.out.println("Performance on train data");
HashMap<String, String> predictions = rnn.test(data).get(targetPRV);
Measures measures = new Measures(data.get(targetPRV), predictions, targetValue);
System.out.println("Accuracy: " + measures.accuracy(0.5));
System.out.println("MAE: " + measures.MAE());
System.out.println("MSE: " + measures.MSE());
System.out.println("ACLL: " + measures.ACLL());
//calculating the performance on test data
GlobalParams.learningStatus = "test";
System.out.println("Performance on test data");
predictions = new HashMap<String, String>();
HashMap<String, String> targets = new HashMap<String, String>();
//Adding n user in each run
System.out.println(test.size());
for(int i = 0; i < test.size(); i += GlobalParams.testBatch){
for(int j = i; j < i + GlobalParams.testBatch && j < test.size(); j++){
targets.put(test.get(j), users.get(test.get(j)).gender);
}
for(int j = i; j < i + GlobalParams.testBatch && j < test.size(); j++){
data.get("Gender").put(test.get(j), users.get(test.get(j)).gender);
data.get("Age").put(test.get(j), users.get(test.get(j)).age);
data.get("Occupation").put(test.get(j), users.get(test.get(j)).occupation);
for(String movie_id : users.get(test.get(j)).moviesRated.keySet()){
data.get("Rate").put(test.get(j) + "," + movie_id, users.get(test.get(j)).moviesRated.get(movie_id));
}
}
HashMap<String, String> rnn_preds = rnn.test(data).get(targetPRV);
for(int j = i; j < i + GlobalParams.testBatch && j < test.size(); j++){
double userPred = Double.parseDouble(rnn_preds.get(test.get(j)));
userPred = GlobalParams.lambdaForMean * userPred + (1 - GlobalParams.lambdaForMean) * probTargetClass;
predictions.put(test.get(j), "" + userPred);
}
for(int j = i; j < i + GlobalParams.testBatch && j < test.size(); j++){
data.get("Gender").remove(test.get(j));
data.get("Age").remove(test.get(j));
data.get("Occupation").remove(test.get(j));
for(String movie_id : users.get(test.get(j)).moviesRated.keySet()){
data.get("Rate").remove(test.get(j) + "," + movie_id);
}
}
}
measures = new Measures(targets, predictions, targetValue);
System.out.println("Accuracy with 0.5 boundary: " + measures.accuracy(0.5));
System.out.println("MAE: " + measures.MAE());
System.out.println("MSE: " + measures.MSE());
System.out.println("ACLL: " + measures.ACLL());
// This part of the code was used for the experiment on extrapolating to unseen cases and addressing the population size issue
// int[] Qs = {75, 100};
// int[] Qs = {0, 1, 2, 3, 4, 5, 7, 10, 15, 20, 30, 40, 50, 75, 100, 125, 150, 200, 250, 300, 400, 500};
// for(int q = 0; q < Qs.length; q++){
// predictions = new HashMap<String, String>();
// targets = new HashMap<String, String>();
// for(int i = 0; i < test.size(); i += GlobalParams.testBatch){
// for(int j = i; j < i + GlobalParams.testBatch && j < test.size(); j++){
// targets.put(test.get(j), users.get(test.get(j)).gender);
// }
// for(int j = i; j < i + GlobalParams.testBatch && j < test.size(); j++){
// data.get("Gender").put(test.get(j), users.get(test.get(j)).gender);
// data.get("Age").put(test.get(j), users.get(test.get(j)).age);
// data.get("Occupation").put(test.get(j), users.get(test.get(j)).occupation);
// for(int k = 0; k < Qs[q] && k < users.get(test.get(j)).moviesRatedVector.size(); k++){
// String movie_id<SUF>
// data.get("Rate").put(test.get(j) + "," + movie_id, "yes");
// }
// // for(String movie_id : users.get(test.get(j)).moviesRated.keySet()){
// // data.get("Rate").put(test.get(j) + "," + movie_id, users.get(test.get(j)).moviesRated.get(movie_id));
// // }
// }
//
// HashMap<String, String> rnn_preds = rnn.test(data).get(targetPRV);
// for(int j = i; j < i + GlobalParams.testBatch && j < test.size(); j++){
// double userPred = Double.parseDouble(rnn_preds.get(test.get(j)));
// userPred = GlobalParams.lambdaForMean * userPred + (1 - GlobalParams.lambdaForMean) * 0.71;
// predictions.put(test.get(j), "" + userPred);
// }
//
// for(int j = i; j < i + GlobalParams.testBatch && j < test.size(); j++){
// data.get("Gender").remove(test.get(j));
// data.get("Age").remove(test.get(j));
// data.get("Occupation").remove(test.get(j));
// for(int k = 0; k < Qs[q] && k < users.get(test.get(j)).moviesRatedVector.size(); k++){
// String movie_id = users.get(test.get(j)).moviesRatedVector.elementAt(k);
// data.get("Rate").remove(test.get(j) + "," + movie_id);
// }
// // for(String movie_id : users.get(test.get(j)).moviesRated.keySet()){
// // data.get("Rate").remove(test.get(j) + "," + movie_id);
// // }
// }
// }
// System.out.println("Q = " + Qs[q]);
// measures = new Measures(targets, predictions, targetValue);
// System.out.println("Accuracy with 0.5 boundary: " + measures.accuracy(0.5));
// System.out.println("MSE: " + measures.MSE());
// System.out.println("ACLL: " + measures.ACLL());
// }
}
public static void main(String[] args) throws FileNotFoundException {
System.out.println("MovieLensGenderLarge");
for(int i = 0; i < GlobalParams.numRuns; i++){
MovieLensGender mlg = new MovieLensGender();
mlg.setHyperParams();
mlg.readFile();
mlg.createTrainTestForCV(0);
mlg.learnModel();
}
}
}
class User {
String id;
String age;
String gender;
String occupation;
HashMap<String, String> moviesRated;
Vector<String> moviesRatedVector;
public User(String id){
this.id = id;
moviesRated = new HashMap<String, String>();
moviesRatedVector = new Vector<String>();
}
}
class Movie {
String id;
HashMap<String, String> genre;
HashMap<String, String> ratedBy;
public Movie(String id){
this.id = id;
ratedBy = new HashMap<String, String>();
genre = new HashMap<String, String>();
}
} |
186674_2 | package nl.themelvin.minetopiaeconomy;
import lombok.Getter;
import nl.themelvin.minetopiaeconomy.commands.AbstractCommand;
import nl.themelvin.minetopiaeconomy.commands.BalancetopCommand;
import nl.themelvin.minetopiaeconomy.commands.MoneyCommand;
import nl.themelvin.minetopiaeconomy.commands.EconomyCommand;
import nl.themelvin.minetopiaeconomy.listeners.AbstractListener;
import nl.themelvin.minetopiaeconomy.listeners.JoinListener;
import nl.themelvin.minetopiaeconomy.listeners.LoginListener;
import nl.themelvin.minetopiaeconomy.listeners.QuitListener;
import nl.themelvin.minetopiaeconomy.messaging.PluginMessaging;
import nl.themelvin.minetopiaeconomy.messaging.incoming.BalanceMessageHandler;
import nl.themelvin.minetopiaeconomy.messaging.incoming.PlayerMessageHandler;
import nl.themelvin.minetopiaeconomy.messaging.outgoing.BalanceMessage;
import nl.themelvin.minetopiaeconomy.messaging.outgoing.PlayerMessage;
import nl.themelvin.minetopiaeconomy.models.Model;
import nl.themelvin.minetopiaeconomy.models.Profile;
import nl.themelvin.minetopiaeconomy.storage.DataSaver;
import nl.themelvin.minetopiaeconomy.utils.Configuration;
import nl.themelvin.minetopiaeconomy.utils.Logger;
import nl.themelvin.minetopiaeconomy.utils.VaultHook;
import nl.themelvin.minetopiaeconomy.vault.EconomyHandler;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static com.ea.async.Async.await;
import static nl.themelvin.minetopiaeconomy.utils.Logger.*;
public class MinetopiaEconomy extends JavaPlugin {
@Getter
private static Plugin plugin;
private static Configuration messages;
private static Configuration config;
@Getter
private static HashMap<UUID, Profile> onlineProfiles = new HashMap<>();
private Map<String, Class> commands = new HashMap<>();
@Override
public void onEnable() {
plugin = this;
// Log start
log(Severity.INFO, "MinetopiaEconomy v" + this.getDescription().getVersion() + " wordt nu gestart.");
long millis = System.currentTimeMillis();
// Setup config
config = new Configuration("config.yml");
messages = new Configuration("messages.yml");
// Create data folder
new File(this.getDataFolder() + "/data").mkdir();
// Setup MySQL / SQLite
String storageType = config.getString("storage");
if (!storageType.equalsIgnoreCase("mysql") && !storageType.equalsIgnoreCase("sqlite")) {
log(Severity.ERROR, "Je hebt geen geldig opslagtype ingevuld, plugin wordt uitgeschakeld.");
Bukkit.getPluginManager().disablePlugin(this);
return;
}
if (!Model.startPool()) {
Logger.log(Severity.ERROR, "Kon geen stabiele verbinding maken met de database, plugin wordt uitgeschakeld");
Bukkit.getPluginManager().disablePlugin(this);
return;
}
// Hook in Vault
if (Bukkit.getPluginManager().getPlugin("Vault") == null) {
log(Severity.WARNING, "Vault is niet in deze server geinstalleerd. Deze plugin werkt ook zonder Vault, maar dat is niet aangeraden.");
} else {
new VaultHook(EconomyHandler.class).hook();
}
// Register listeners
this.registerListener(LoginListener.class);
this.registerListener(JoinListener.class);
this.registerListener(QuitListener.class);
// Register commands
this.registerCommand("money", MoneyCommand.class);
this.registerCommand("balancetop", BalancetopCommand.class);
this.registerCommand("economy", EconomyCommand.class);
// Register plugin messaging
if (config.getBoolean("plugin-messaging")) {
if (!config.getString("storage").equalsIgnoreCase("mysql")) {
log(Severity.ERROR, "Je hebt plugin messaging aangezet, maar het opslagtype staat nog niet op MySQL. Plugin messaging (en dus live synchronisatie) kan alleen ingeschakeld worden wanneer het opslagtype MySQL is.");
Bukkit.getPluginManager().disablePlugin(this);
return;
}
this.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
this.getServer().getMessenger().registerIncomingPluginChannel(this, "BungeeCord", PluginMessaging.getInstance());
PluginMessaging messaging = PluginMessaging.getInstance();
messaging.register("playerAction", PlayerMessage.class, PlayerMessageHandler.class);
messaging.register("balanceChange", BalanceMessage.class, BalanceMessageHandler.class);
}
// Fake join for all online players
for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
AsyncPlayerPreLoginEvent preLogin = new AsyncPlayerPreLoginEvent(onlinePlayer.getName(), onlinePlayer.getAddress().getAddress(), onlinePlayer.getUniqueId());
new LoginListener(this).listen(preLogin);
PlayerJoinEvent joinEvent = new PlayerJoinEvent(onlinePlayer, null);
new JoinListener(this).listen(joinEvent);
}
// Save all data (async) every 5 minutes.
Bukkit.getScheduler().runTaskTimer(this, new DataSaver(), 5 /*min*/ * 60 /*sec*/ * 20 /*ticks*/, 5 /*min*/ * 60 /*sec*/ * 20 /*ticks*/);
// Log end
log(Severity.INFO, "Klaar! Bedankt voor het gebruiken van deze plugin, het duurde " + (System.currentTimeMillis() - millis) + "ms.");
}
@Override
public void onDisable() {
log(Severity.INFO, "Alle online spelers worden opgeslagen.");
// Save all online profiles
for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
PlayerQuitEvent quitEvent = new PlayerQuitEvent(onlinePlayer, null);
await(new QuitListener(this).listen(quitEvent));
}
// Close pool
Model.closePool();
log(Severity.INFO, "Uitgeschakeld! Bedankt voor het gebruiken van deze plugin.");
plugin = null;
}
/**
* Register command to command register.
*
* @param command Alias of the command
* @param clazz Cclass instance of the executor
*/
private void registerCommand(String command, Class<?> clazz) {
this.getCommand(command).setExecutor(this);
this.commands.put(command, clazz);
List<String> aliases = this.getCommand(command).getAliases();
for (String alias : aliases) {
this.commands.put(alias, clazz);
}
}
private void registerListener(Class<? extends AbstractListener> clazz) {
try {
Constructor<?> constructor = clazz.getConstructor(Plugin.class);
AbstractListener object = (AbstractListener) constructor.newInstance(this);
object.register();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) {
if (!this.commands.containsKey(alias)) {
return false;
}
try {
Class<?> clazz = this.commands.get(alias);
Constructor<?> constructor = clazz.getConstructor(CommandSender.class, String.class, String[].class);
AbstractCommand object = (AbstractCommand) constructor.newInstance(sender, alias, args);
object.execute();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static Configuration messages() {
return messages;
}
public static Configuration configuration() {
return config;
}
}
| MelvinSnijders/MinetopiaEconomy | src/main/java/nl/themelvin/minetopiaeconomy/MinetopiaEconomy.java | 2,332 | // Hook in Vault | line_comment | nl | package nl.themelvin.minetopiaeconomy;
import lombok.Getter;
import nl.themelvin.minetopiaeconomy.commands.AbstractCommand;
import nl.themelvin.minetopiaeconomy.commands.BalancetopCommand;
import nl.themelvin.minetopiaeconomy.commands.MoneyCommand;
import nl.themelvin.minetopiaeconomy.commands.EconomyCommand;
import nl.themelvin.minetopiaeconomy.listeners.AbstractListener;
import nl.themelvin.minetopiaeconomy.listeners.JoinListener;
import nl.themelvin.minetopiaeconomy.listeners.LoginListener;
import nl.themelvin.minetopiaeconomy.listeners.QuitListener;
import nl.themelvin.minetopiaeconomy.messaging.PluginMessaging;
import nl.themelvin.minetopiaeconomy.messaging.incoming.BalanceMessageHandler;
import nl.themelvin.minetopiaeconomy.messaging.incoming.PlayerMessageHandler;
import nl.themelvin.minetopiaeconomy.messaging.outgoing.BalanceMessage;
import nl.themelvin.minetopiaeconomy.messaging.outgoing.PlayerMessage;
import nl.themelvin.minetopiaeconomy.models.Model;
import nl.themelvin.minetopiaeconomy.models.Profile;
import nl.themelvin.minetopiaeconomy.storage.DataSaver;
import nl.themelvin.minetopiaeconomy.utils.Configuration;
import nl.themelvin.minetopiaeconomy.utils.Logger;
import nl.themelvin.minetopiaeconomy.utils.VaultHook;
import nl.themelvin.minetopiaeconomy.vault.EconomyHandler;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static com.ea.async.Async.await;
import static nl.themelvin.minetopiaeconomy.utils.Logger.*;
public class MinetopiaEconomy extends JavaPlugin {
@Getter
private static Plugin plugin;
private static Configuration messages;
private static Configuration config;
@Getter
private static HashMap<UUID, Profile> onlineProfiles = new HashMap<>();
private Map<String, Class> commands = new HashMap<>();
@Override
public void onEnable() {
plugin = this;
// Log start
log(Severity.INFO, "MinetopiaEconomy v" + this.getDescription().getVersion() + " wordt nu gestart.");
long millis = System.currentTimeMillis();
// Setup config
config = new Configuration("config.yml");
messages = new Configuration("messages.yml");
// Create data folder
new File(this.getDataFolder() + "/data").mkdir();
// Setup MySQL / SQLite
String storageType = config.getString("storage");
if (!storageType.equalsIgnoreCase("mysql") && !storageType.equalsIgnoreCase("sqlite")) {
log(Severity.ERROR, "Je hebt geen geldig opslagtype ingevuld, plugin wordt uitgeschakeld.");
Bukkit.getPluginManager().disablePlugin(this);
return;
}
if (!Model.startPool()) {
Logger.log(Severity.ERROR, "Kon geen stabiele verbinding maken met de database, plugin wordt uitgeschakeld");
Bukkit.getPluginManager().disablePlugin(this);
return;
}
// Hook in<SUF>
if (Bukkit.getPluginManager().getPlugin("Vault") == null) {
log(Severity.WARNING, "Vault is niet in deze server geinstalleerd. Deze plugin werkt ook zonder Vault, maar dat is niet aangeraden.");
} else {
new VaultHook(EconomyHandler.class).hook();
}
// Register listeners
this.registerListener(LoginListener.class);
this.registerListener(JoinListener.class);
this.registerListener(QuitListener.class);
// Register commands
this.registerCommand("money", MoneyCommand.class);
this.registerCommand("balancetop", BalancetopCommand.class);
this.registerCommand("economy", EconomyCommand.class);
// Register plugin messaging
if (config.getBoolean("plugin-messaging")) {
if (!config.getString("storage").equalsIgnoreCase("mysql")) {
log(Severity.ERROR, "Je hebt plugin messaging aangezet, maar het opslagtype staat nog niet op MySQL. Plugin messaging (en dus live synchronisatie) kan alleen ingeschakeld worden wanneer het opslagtype MySQL is.");
Bukkit.getPluginManager().disablePlugin(this);
return;
}
this.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
this.getServer().getMessenger().registerIncomingPluginChannel(this, "BungeeCord", PluginMessaging.getInstance());
PluginMessaging messaging = PluginMessaging.getInstance();
messaging.register("playerAction", PlayerMessage.class, PlayerMessageHandler.class);
messaging.register("balanceChange", BalanceMessage.class, BalanceMessageHandler.class);
}
// Fake join for all online players
for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
AsyncPlayerPreLoginEvent preLogin = new AsyncPlayerPreLoginEvent(onlinePlayer.getName(), onlinePlayer.getAddress().getAddress(), onlinePlayer.getUniqueId());
new LoginListener(this).listen(preLogin);
PlayerJoinEvent joinEvent = new PlayerJoinEvent(onlinePlayer, null);
new JoinListener(this).listen(joinEvent);
}
// Save all data (async) every 5 minutes.
Bukkit.getScheduler().runTaskTimer(this, new DataSaver(), 5 /*min*/ * 60 /*sec*/ * 20 /*ticks*/, 5 /*min*/ * 60 /*sec*/ * 20 /*ticks*/);
// Log end
log(Severity.INFO, "Klaar! Bedankt voor het gebruiken van deze plugin, het duurde " + (System.currentTimeMillis() - millis) + "ms.");
}
@Override
public void onDisable() {
log(Severity.INFO, "Alle online spelers worden opgeslagen.");
// Save all online profiles
for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
PlayerQuitEvent quitEvent = new PlayerQuitEvent(onlinePlayer, null);
await(new QuitListener(this).listen(quitEvent));
}
// Close pool
Model.closePool();
log(Severity.INFO, "Uitgeschakeld! Bedankt voor het gebruiken van deze plugin.");
plugin = null;
}
/**
* Register command to command register.
*
* @param command Alias of the command
* @param clazz Cclass instance of the executor
*/
private void registerCommand(String command, Class<?> clazz) {
this.getCommand(command).setExecutor(this);
this.commands.put(command, clazz);
List<String> aliases = this.getCommand(command).getAliases();
for (String alias : aliases) {
this.commands.put(alias, clazz);
}
}
private void registerListener(Class<? extends AbstractListener> clazz) {
try {
Constructor<?> constructor = clazz.getConstructor(Plugin.class);
AbstractListener object = (AbstractListener) constructor.newInstance(this);
object.register();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) {
if (!this.commands.containsKey(alias)) {
return false;
}
try {
Class<?> clazz = this.commands.get(alias);
Constructor<?> constructor = clazz.getConstructor(CommandSender.class, String.class, String[].class);
AbstractCommand object = (AbstractCommand) constructor.newInstance(sender, alias, args);
object.execute();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static Configuration messages() {
return messages;
}
public static Configuration configuration() {
return config;
}
}
|
161581_28 | /*
* Licensed by the author of Time4J-project.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership. The copyright owner
* 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 net.time4j;
import net.time4j.base.GregorianDate;
import net.time4j.base.GregorianMath;
import net.time4j.engine.ChronoCondition;
import net.time4j.engine.ChronoOperator;
import net.time4j.format.CalendarText;
import net.time4j.format.OutputContext;
import net.time4j.format.TextWidth;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.Locale;
/**
* <p>Enumeration of weekdays. </p>
*
* <p>Several methods with a {@code Weekmodel}-parameter support other
* week models, too. </p>
*
* @author Meno Hochschild
*/
/*[deutsch]
* <p>Wochentagsaufzählung. </p>
*
* <p>Verschiedene Methoden mit einem {@code Weekmodel}-Argument
* unterstützen zusätzlich andere Wochenmodelle. </p>
*
* @author Meno Hochschild
*/
public enum Weekday
implements ChronoCondition<GregorianDate>, ChronoOperator<PlainDate> {
//~ Statische Felder/Initialisierungen --------------------------------
/** Monday with the numerical ISO-value {@code 1}. */
/*[deutsch] Montag mit dem numerischen ISO-Wert {@code 1}. */
MONDAY,
/** Tuesday with the numerical ISO-value {@code 2}. */
/*[deutsch] Dienstag mit dem numerischen ISO-Wert {@code 2}. */
TUESDAY,
/** Wednesday with the numerical ISO-value {@code 3}. */
/*[deutsch] Mittwoch mit dem numerischen ISO-Wert {@code 3}. */
WEDNESDAY,
/** Thursday with the numerical ISO-value {@code 4}. */
/*[deutsch] Donnerstag mit dem numerischen ISO-Wert {@code 4}. */
THURSDAY,
/** Friday with the numerical ISO-value {@code 5}. */
/*[deutsch] Freitag mit dem numerischen ISO-Wert {@code 5}. */
FRIDAY,
/** Saturday with the numerical ISO-value {@code 6}. */
/*[deutsch] Samstag mit dem numerischen ISO-Wert {@code 6}. */
SATURDAY,
/** Sunday with the numerical ISO-value {@code 7}. */
/*[deutsch] Sonntag mit dem numerischen ISO-Wert {@code 7}. */
SUNDAY;
private static final Weekday[] ENUMS = Weekday.values(); // Cache
//~ Methoden ----------------------------------------------------------
/**
* <p>Gets the corresponding numerical ISO-value. </p>
*
* @return {@code monday=1, tuesday=2, wednesday=3, thursday=4, friday=5, saturday=6, sunday=7}
* @see #valueOf(int)
* @see Weekmodel#ISO
*/
/*[deutsch]
* <p>Liefert den korrespondierenden kalendarischen Integer-Wert
* entsprechend der ISO-8601-Norm. </p>
*
* @return {@code monday=1, tuesday=2, wednesday=3, thursday=4, friday=5, saturday=6, sunday=7}
* @see #valueOf(int)
* @see Weekmodel#ISO
*/
public int getValue() {
return (this.ordinal() + 1);
}
/**
* <p>Gets the numerical value corresponding to the rule of given
* week model on which day a week starts. </p>
*
* <p>In US, the rule is applied that weeks start with Sunday. If so then
* this method will yield {@code 1} for {@code Weekmodel.of(Locale.US)}
* (instead of the ISO-value {@code 7}). </p>
*
* @param model localized week model
* @return localized weekday number (1 - 7)
* @see Weekmodel#getFirstDayOfWeek()
* @see #values(Weekmodel)
* @see #valueOf(int, Weekmodel)
*/
/*[deutsch]
* <p>Liefert eine Wochentagsnummer passend zur im Modell enthaltenen
* Regel, mit welchem Tag eine Woche beginnt. </p>
*
* <p>Wird z.B. die in den USA übliche Regel angewandt, daß
* der erste Tag einer Woche der Sonntag sein soll, dann hat der Sonntag
* die Nummer 1 (statt 7 nach ISO-8601). </p>
*
* @param model localized week model
* @return localized weekday number (1 - 7)
* @see Weekmodel#getFirstDayOfWeek()
* @see #values(Weekmodel)
* @see #valueOf(int, Weekmodel)
*/
public int getValue(Weekmodel model) {
int shift = model.getFirstDayOfWeek().ordinal();
return ((7 + this.ordinal() - shift) % 7) + 1;
}
/**
* <p>Yields an array which is sorted corresponding to the rule of given
* week model on which day a week starts. </p>
*
* <p>The alternative method generated by compiler without any parameters
* creates an array sorted according to ISO-8601-standard. This method
* is an overloaded variation where sorting is adjusted. </p>
*
* @param model localized week model
* @return new weekday array
* @see Weekmodel#getFirstDayOfWeek()
* @see #getValue(Weekmodel)
* @see #valueOf(int, Weekmodel)
*/
/*[deutsch]
* <p>Liefert ein Array, das passend zur im Model enthaltenen Regel
* sortiert ist, mit welchem Tag eine Woche beginnt. </p>
*
* <p>Die vom Java-Compiler generierte {@code values()}-Methode ohne
* Argument richtet sich nach dem ISO-8601-Wochenmodell. Diese Methode
* ist die überladene Variante, in der die Sortierung angepasst
* ist. </p>
*
* @param model localized week model
* @return new weekday array
* @see Weekmodel#getFirstDayOfWeek()
* @see #getValue(Weekmodel)
* @see #valueOf(int, Weekmodel)
*/
public static Weekday[] values(Weekmodel model) {
Weekday[] enums = new Weekday[7];
Weekday wd = model.getFirstDayOfWeek();
for (int i = 0; i < 7; i++) {
enums[i] = wd;
wd = wd.next();
}
return enums;
}
/**
* <p>Gets the enum-constant which corresponds to the given numerical
* value. </p>
*
* @param dayOfWeek (monday=1, tuesday=2, wednesday=3, thursday=4,
* friday=5, saturday=6, sunday=7)
* @return weekday as enum
* @throws IllegalArgumentException if the argument is out of range
* @see #getValue()
* @see Weekmodel#ISO
*/
/*[deutsch]
* <p>Liefert die zum kalendarischen Integer-Wert passende
* Enum-Konstante entsprechend der ISO-8601-Norm. </p>
*
* @param dayOfWeek (monday=1, tuesday=2, wednesday=3, thursday=4,
* friday=5, saturday=6, sunday=7)
* @return weekday as enum
* @throws IllegalArgumentException if the argument is out of range
* @see #getValue()
* @see Weekmodel#ISO
*/
public static Weekday valueOf(int dayOfWeek) {
if ((dayOfWeek < 1) || (dayOfWeek > 7)) {
throw new IllegalArgumentException("Out of range: " + dayOfWeek);
}
return ENUMS[dayOfWeek - 1];
}
/**
* <p>Gets the enum-constant which corresponds to the given localized
* numerical value taking into account given week model. </p>
*
* @param dayOfWeek localized weekday number (1 - 7)
* @param model localized week model
* @return weekday as enum
* @throws IllegalArgumentException if the int-argument is out of range
* @see Weekmodel#getFirstDayOfWeek()
* @see #values(Weekmodel)
* @see #getValue(Weekmodel)
*/
/*[deutsch]
* <p>Liefert die zum kalendarischen Integer-Wert passende
* Enum-Konstante passend zum angegebenen Wochenmodell. </p>
*
* @param dayOfWeek localized weekday number (1 - 7)
* @param model localized week model
* @return weekday as enum
* @throws IllegalArgumentException if the int-argument is out of range
* @see Weekmodel#getFirstDayOfWeek()
* @see #values(Weekmodel)
* @see #getValue(Weekmodel)
*/
public static Weekday valueOf(
int dayOfWeek,
Weekmodel model
) {
if (
(dayOfWeek < 1)
|| (dayOfWeek > 7)
) {
throw new IllegalArgumentException(
"Weekday out of range: " + dayOfWeek);
}
int shift = model.getFirstDayOfWeek().ordinal();
return ENUMS[(dayOfWeek - 1 + shift) % 7];
}
/**
* <p>Gets the weekday corresponding to given gregorian date. </p>
*
* <p>The proleptic gregorian calendar as defined in ISO-8601 is the
* calculation basis. That means the current leap year rule is even
* applied for dates before the introduction of gregorian calendar. </p>
*
* @param year proleptic iso year
* @param monthOfYear gregorian month
* @param dayOfMonth day of month (1 - 31)
* @return weekday
* @throws IllegalArgumentException if the day is out of range
*/
/*[deutsch]
* <p>Liefert den Wochentag zum angegebenen Datum. </p>
*
* <p>Grundlage ist der gregorianische Kalender proleptisch für
* alle Zeiten ohne Kalenderwechsel angewandt. Es wird also so getan,
* als ob der gregorianische Kalender schon vor dem 15. Oktober 1582
* existiert hätte, so wie im ISO-8601-Format vorgesehen. </p>
*
* @param year proleptic iso year
* @param monthOfYear gregorian month
* @param dayOfMonth day of month (1 - 31)
* @return weekday
* @throws IllegalArgumentException if the day is out of range
*/
public static Weekday valueOf(
int year,
Month monthOfYear,
int dayOfMonth
) {
return Weekday.valueOf(
GregorianMath.getDayOfWeek(
year,
monthOfYear.getValue(),
dayOfMonth
)
);
}
/**
* <p>Rolls to the next day of week. </p>
*
* <p>The result is Monday if this method is applied on Sunday. </p>
*
* @return next weekday
*/
/*[deutsch]
* <p>Ermittelt den nächsten Wochentag. </p>
*
* <p>Auf den Sonntag angewandt ist das Ergebnis der Montag. </p>
*
* @return next weekday
*/
public Weekday next() {
return this.roll(1);
}
/**
* <p>Rolls to the previous day of week. </p>
*
* <p>The result is Sunday if this method is applied on Monday. </p>
*
* @return previous weekday
*/
/*[deutsch]
* <p>Ermittelt den vorherigen Wochentag. </p>
*
* <p>Auf den Montag angewandt ist das Ergebnis der Sonntag. </p>
*
* @return previous weekday
*/
public Weekday previous() {
return this.roll(-1);
}
/**
* <p>Rolls this day of week by given amount of days. </p>
*
* @param days count of days (maybe negative)
* @return result of rolling operation
*/
/*[deutsch]
* <p>Rollt um die angegebene Anzahl von Tagen vor oder zurück. </p>
*
* @param days count of days (maybe negative)
* @return result of rolling operation
*/
public Weekday roll(int days) {
return Weekday.valueOf((this.ordinal() + (days % 7 + 7)) % 7 + 1);
}
/**
* <p>Equivalent to the expression
* {@code getDisplayName(locale, TextWidth.WIDE, OutputContext.FORMAT)}.
* </p>
*
* @param locale language setting
* @return descriptive text (long form, never {@code null})
* @see #getDisplayName(Locale, TextWidth, OutputContext)
*/
/*[deutsch]
* <p>Entspricht dem Ausdruck
* {@code getDisplayName(locale, TextWidth.WIDE, OutputContext.FORMAT)}.
* </p>
*
* @param locale language setting
* @return descriptive text (long form, never {@code null})
* @see #getDisplayName(Locale, TextWidth, OutputContext)
*/
public String getDisplayName(Locale locale) {
return this.getDisplayName(
locale, TextWidth.WIDE, OutputContext.FORMAT);
}
/**
* <p>Gets the description text dependent on the locale and style
* parameters. </p>
*
* <p>The second argument controls the width of description while the
* third argument is only relevant for languages which make a difference
* between stand-alone forms and embedded text forms (does not matter in
* English). </p>
*
* @param locale language setting
* @param width text width
* @param context output context
* @return descriptive text for given locale and style (never {@code null})
*/
/*[deutsch]
* <p>Liefert den sprachabhängigen Beschreibungstext. </p>
*
* <p>Über das zweite Argument kann gesteuert werden, ob eine kurze
* oder eine lange Form des Beschreibungstexts ausgegeben werden soll. Das
* ist besonders sinnvoll in Benutzeroberflächen, wo zwischen der
* Beschriftung und der detaillierten Erläuterung einer graphischen
* Komponente unterschieden wird. Das dritte Argument ist in Sprachen von
* Belang, die verschiedene grammatikalische Formen für die Ausgabe
* als alleinstehend oder eingebettet in formatierten Text kennen. </p>
*
* @param locale language setting
* @param width text width
* @param context output context
* @return descriptive text for given locale and style (never {@code null})
*/
public String getDisplayName(
Locale locale,
TextWidth width,
OutputContext context
) {
return CalendarText.getIsoInstance(locale).getWeekdays(width, context).print(this);
}
/**
* <p>Tries to interprete given text as day-of-week. </p>
*
* @param text the text to be parsed
* @param locale language setting
* @param width expected text width
* @param context expected output context
* @return the parsed day of week if successful
* @throws ParseException if parsing fails
* @see #getDisplayName(Locale, TextWidth, OutputContext)
* @since 3.33/4.28
*/
/*[deutsch]
* <p>Versucht, den angegebenen Text als Wochentag zu interpretieren. </p>
*
* @param text the text to be parsed
* @param locale language setting
* @param width expected text width
* @param context expected output context
* @return the parsed day of week if successful
* @throws ParseException if parsing fails
* @see #getDisplayName(Locale, TextWidth, OutputContext)
* @since 3.33/4.28
*/
public static Weekday parse(
CharSequence text,
Locale locale,
TextWidth width,
OutputContext context
) throws ParseException {
ParsePosition pp = new ParsePosition(0);
Weekday wd = CalendarText.getIsoInstance(locale).getWeekdays(width, context).parse(text, pp, Weekday.class);
if (wd == null) {
throw new ParseException("Cannot parse: " + text, pp.getErrorIndex());
} else {
return wd;
}
}
@Override
public boolean test(GregorianDate context) {
int y = context.getYear();
int m = context.getMonth();
int dom = context.getDayOfMonth();
return (GregorianMath.getDayOfWeek(y, m, dom) == this.getValue());
}
@Override
public PlainDate apply(PlainDate date) {
return date.with(PlainDate.DAY_OF_WEEK, this);
}
}
| MenoData/Time4A | time4j-android/src/main/java/net/time4j/Weekday.java | 4,912 | /*[deutsch]
* <p>Liefert die zum kalendarischen Integer-Wert passende
* Enum-Konstante passend zum angegebenen Wochenmodell. </p>
*
* @param dayOfWeek localized weekday number (1 - 7)
* @param model localized week model
* @return weekday as enum
* @throws IllegalArgumentException if the int-argument is out of range
* @see Weekmodel#getFirstDayOfWeek()
* @see #values(Weekmodel)
* @see #getValue(Weekmodel)
*/ | block_comment | nl | /*
* Licensed by the author of Time4J-project.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership. The copyright owner
* 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 net.time4j;
import net.time4j.base.GregorianDate;
import net.time4j.base.GregorianMath;
import net.time4j.engine.ChronoCondition;
import net.time4j.engine.ChronoOperator;
import net.time4j.format.CalendarText;
import net.time4j.format.OutputContext;
import net.time4j.format.TextWidth;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.Locale;
/**
* <p>Enumeration of weekdays. </p>
*
* <p>Several methods with a {@code Weekmodel}-parameter support other
* week models, too. </p>
*
* @author Meno Hochschild
*/
/*[deutsch]
* <p>Wochentagsaufzählung. </p>
*
* <p>Verschiedene Methoden mit einem {@code Weekmodel}-Argument
* unterstützen zusätzlich andere Wochenmodelle. </p>
*
* @author Meno Hochschild
*/
public enum Weekday
implements ChronoCondition<GregorianDate>, ChronoOperator<PlainDate> {
//~ Statische Felder/Initialisierungen --------------------------------
/** Monday with the numerical ISO-value {@code 1}. */
/*[deutsch] Montag mit dem numerischen ISO-Wert {@code 1}. */
MONDAY,
/** Tuesday with the numerical ISO-value {@code 2}. */
/*[deutsch] Dienstag mit dem numerischen ISO-Wert {@code 2}. */
TUESDAY,
/** Wednesday with the numerical ISO-value {@code 3}. */
/*[deutsch] Mittwoch mit dem numerischen ISO-Wert {@code 3}. */
WEDNESDAY,
/** Thursday with the numerical ISO-value {@code 4}. */
/*[deutsch] Donnerstag mit dem numerischen ISO-Wert {@code 4}. */
THURSDAY,
/** Friday with the numerical ISO-value {@code 5}. */
/*[deutsch] Freitag mit dem numerischen ISO-Wert {@code 5}. */
FRIDAY,
/** Saturday with the numerical ISO-value {@code 6}. */
/*[deutsch] Samstag mit dem numerischen ISO-Wert {@code 6}. */
SATURDAY,
/** Sunday with the numerical ISO-value {@code 7}. */
/*[deutsch] Sonntag mit dem numerischen ISO-Wert {@code 7}. */
SUNDAY;
private static final Weekday[] ENUMS = Weekday.values(); // Cache
//~ Methoden ----------------------------------------------------------
/**
* <p>Gets the corresponding numerical ISO-value. </p>
*
* @return {@code monday=1, tuesday=2, wednesday=3, thursday=4, friday=5, saturday=6, sunday=7}
* @see #valueOf(int)
* @see Weekmodel#ISO
*/
/*[deutsch]
* <p>Liefert den korrespondierenden kalendarischen Integer-Wert
* entsprechend der ISO-8601-Norm. </p>
*
* @return {@code monday=1, tuesday=2, wednesday=3, thursday=4, friday=5, saturday=6, sunday=7}
* @see #valueOf(int)
* @see Weekmodel#ISO
*/
public int getValue() {
return (this.ordinal() + 1);
}
/**
* <p>Gets the numerical value corresponding to the rule of given
* week model on which day a week starts. </p>
*
* <p>In US, the rule is applied that weeks start with Sunday. If so then
* this method will yield {@code 1} for {@code Weekmodel.of(Locale.US)}
* (instead of the ISO-value {@code 7}). </p>
*
* @param model localized week model
* @return localized weekday number (1 - 7)
* @see Weekmodel#getFirstDayOfWeek()
* @see #values(Weekmodel)
* @see #valueOf(int, Weekmodel)
*/
/*[deutsch]
* <p>Liefert eine Wochentagsnummer passend zur im Modell enthaltenen
* Regel, mit welchem Tag eine Woche beginnt. </p>
*
* <p>Wird z.B. die in den USA übliche Regel angewandt, daß
* der erste Tag einer Woche der Sonntag sein soll, dann hat der Sonntag
* die Nummer 1 (statt 7 nach ISO-8601). </p>
*
* @param model localized week model
* @return localized weekday number (1 - 7)
* @see Weekmodel#getFirstDayOfWeek()
* @see #values(Weekmodel)
* @see #valueOf(int, Weekmodel)
*/
public int getValue(Weekmodel model) {
int shift = model.getFirstDayOfWeek().ordinal();
return ((7 + this.ordinal() - shift) % 7) + 1;
}
/**
* <p>Yields an array which is sorted corresponding to the rule of given
* week model on which day a week starts. </p>
*
* <p>The alternative method generated by compiler without any parameters
* creates an array sorted according to ISO-8601-standard. This method
* is an overloaded variation where sorting is adjusted. </p>
*
* @param model localized week model
* @return new weekday array
* @see Weekmodel#getFirstDayOfWeek()
* @see #getValue(Weekmodel)
* @see #valueOf(int, Weekmodel)
*/
/*[deutsch]
* <p>Liefert ein Array, das passend zur im Model enthaltenen Regel
* sortiert ist, mit welchem Tag eine Woche beginnt. </p>
*
* <p>Die vom Java-Compiler generierte {@code values()}-Methode ohne
* Argument richtet sich nach dem ISO-8601-Wochenmodell. Diese Methode
* ist die überladene Variante, in der die Sortierung angepasst
* ist. </p>
*
* @param model localized week model
* @return new weekday array
* @see Weekmodel#getFirstDayOfWeek()
* @see #getValue(Weekmodel)
* @see #valueOf(int, Weekmodel)
*/
public static Weekday[] values(Weekmodel model) {
Weekday[] enums = new Weekday[7];
Weekday wd = model.getFirstDayOfWeek();
for (int i = 0; i < 7; i++) {
enums[i] = wd;
wd = wd.next();
}
return enums;
}
/**
* <p>Gets the enum-constant which corresponds to the given numerical
* value. </p>
*
* @param dayOfWeek (monday=1, tuesday=2, wednesday=3, thursday=4,
* friday=5, saturday=6, sunday=7)
* @return weekday as enum
* @throws IllegalArgumentException if the argument is out of range
* @see #getValue()
* @see Weekmodel#ISO
*/
/*[deutsch]
* <p>Liefert die zum kalendarischen Integer-Wert passende
* Enum-Konstante entsprechend der ISO-8601-Norm. </p>
*
* @param dayOfWeek (monday=1, tuesday=2, wednesday=3, thursday=4,
* friday=5, saturday=6, sunday=7)
* @return weekday as enum
* @throws IllegalArgumentException if the argument is out of range
* @see #getValue()
* @see Weekmodel#ISO
*/
public static Weekday valueOf(int dayOfWeek) {
if ((dayOfWeek < 1) || (dayOfWeek > 7)) {
throw new IllegalArgumentException("Out of range: " + dayOfWeek);
}
return ENUMS[dayOfWeek - 1];
}
/**
* <p>Gets the enum-constant which corresponds to the given localized
* numerical value taking into account given week model. </p>
*
* @param dayOfWeek localized weekday number (1 - 7)
* @param model localized week model
* @return weekday as enum
* @throws IllegalArgumentException if the int-argument is out of range
* @see Weekmodel#getFirstDayOfWeek()
* @see #values(Weekmodel)
* @see #getValue(Weekmodel)
*/
/*[deutsch]
<SUF>*/
public static Weekday valueOf(
int dayOfWeek,
Weekmodel model
) {
if (
(dayOfWeek < 1)
|| (dayOfWeek > 7)
) {
throw new IllegalArgumentException(
"Weekday out of range: " + dayOfWeek);
}
int shift = model.getFirstDayOfWeek().ordinal();
return ENUMS[(dayOfWeek - 1 + shift) % 7];
}
/**
* <p>Gets the weekday corresponding to given gregorian date. </p>
*
* <p>The proleptic gregorian calendar as defined in ISO-8601 is the
* calculation basis. That means the current leap year rule is even
* applied for dates before the introduction of gregorian calendar. </p>
*
* @param year proleptic iso year
* @param monthOfYear gregorian month
* @param dayOfMonth day of month (1 - 31)
* @return weekday
* @throws IllegalArgumentException if the day is out of range
*/
/*[deutsch]
* <p>Liefert den Wochentag zum angegebenen Datum. </p>
*
* <p>Grundlage ist der gregorianische Kalender proleptisch für
* alle Zeiten ohne Kalenderwechsel angewandt. Es wird also so getan,
* als ob der gregorianische Kalender schon vor dem 15. Oktober 1582
* existiert hätte, so wie im ISO-8601-Format vorgesehen. </p>
*
* @param year proleptic iso year
* @param monthOfYear gregorian month
* @param dayOfMonth day of month (1 - 31)
* @return weekday
* @throws IllegalArgumentException if the day is out of range
*/
public static Weekday valueOf(
int year,
Month monthOfYear,
int dayOfMonth
) {
return Weekday.valueOf(
GregorianMath.getDayOfWeek(
year,
monthOfYear.getValue(),
dayOfMonth
)
);
}
/**
* <p>Rolls to the next day of week. </p>
*
* <p>The result is Monday if this method is applied on Sunday. </p>
*
* @return next weekday
*/
/*[deutsch]
* <p>Ermittelt den nächsten Wochentag. </p>
*
* <p>Auf den Sonntag angewandt ist das Ergebnis der Montag. </p>
*
* @return next weekday
*/
public Weekday next() {
return this.roll(1);
}
/**
* <p>Rolls to the previous day of week. </p>
*
* <p>The result is Sunday if this method is applied on Monday. </p>
*
* @return previous weekday
*/
/*[deutsch]
* <p>Ermittelt den vorherigen Wochentag. </p>
*
* <p>Auf den Montag angewandt ist das Ergebnis der Sonntag. </p>
*
* @return previous weekday
*/
public Weekday previous() {
return this.roll(-1);
}
/**
* <p>Rolls this day of week by given amount of days. </p>
*
* @param days count of days (maybe negative)
* @return result of rolling operation
*/
/*[deutsch]
* <p>Rollt um die angegebene Anzahl von Tagen vor oder zurück. </p>
*
* @param days count of days (maybe negative)
* @return result of rolling operation
*/
public Weekday roll(int days) {
return Weekday.valueOf((this.ordinal() + (days % 7 + 7)) % 7 + 1);
}
/**
* <p>Equivalent to the expression
* {@code getDisplayName(locale, TextWidth.WIDE, OutputContext.FORMAT)}.
* </p>
*
* @param locale language setting
* @return descriptive text (long form, never {@code null})
* @see #getDisplayName(Locale, TextWidth, OutputContext)
*/
/*[deutsch]
* <p>Entspricht dem Ausdruck
* {@code getDisplayName(locale, TextWidth.WIDE, OutputContext.FORMAT)}.
* </p>
*
* @param locale language setting
* @return descriptive text (long form, never {@code null})
* @see #getDisplayName(Locale, TextWidth, OutputContext)
*/
public String getDisplayName(Locale locale) {
return this.getDisplayName(
locale, TextWidth.WIDE, OutputContext.FORMAT);
}
/**
* <p>Gets the description text dependent on the locale and style
* parameters. </p>
*
* <p>The second argument controls the width of description while the
* third argument is only relevant for languages which make a difference
* between stand-alone forms and embedded text forms (does not matter in
* English). </p>
*
* @param locale language setting
* @param width text width
* @param context output context
* @return descriptive text for given locale and style (never {@code null})
*/
/*[deutsch]
* <p>Liefert den sprachabhängigen Beschreibungstext. </p>
*
* <p>Über das zweite Argument kann gesteuert werden, ob eine kurze
* oder eine lange Form des Beschreibungstexts ausgegeben werden soll. Das
* ist besonders sinnvoll in Benutzeroberflächen, wo zwischen der
* Beschriftung und der detaillierten Erläuterung einer graphischen
* Komponente unterschieden wird. Das dritte Argument ist in Sprachen von
* Belang, die verschiedene grammatikalische Formen für die Ausgabe
* als alleinstehend oder eingebettet in formatierten Text kennen. </p>
*
* @param locale language setting
* @param width text width
* @param context output context
* @return descriptive text for given locale and style (never {@code null})
*/
public String getDisplayName(
Locale locale,
TextWidth width,
OutputContext context
) {
return CalendarText.getIsoInstance(locale).getWeekdays(width, context).print(this);
}
/**
* <p>Tries to interprete given text as day-of-week. </p>
*
* @param text the text to be parsed
* @param locale language setting
* @param width expected text width
* @param context expected output context
* @return the parsed day of week if successful
* @throws ParseException if parsing fails
* @see #getDisplayName(Locale, TextWidth, OutputContext)
* @since 3.33/4.28
*/
/*[deutsch]
* <p>Versucht, den angegebenen Text als Wochentag zu interpretieren. </p>
*
* @param text the text to be parsed
* @param locale language setting
* @param width expected text width
* @param context expected output context
* @return the parsed day of week if successful
* @throws ParseException if parsing fails
* @see #getDisplayName(Locale, TextWidth, OutputContext)
* @since 3.33/4.28
*/
public static Weekday parse(
CharSequence text,
Locale locale,
TextWidth width,
OutputContext context
) throws ParseException {
ParsePosition pp = new ParsePosition(0);
Weekday wd = CalendarText.getIsoInstance(locale).getWeekdays(width, context).parse(text, pp, Weekday.class);
if (wd == null) {
throw new ParseException("Cannot parse: " + text, pp.getErrorIndex());
} else {
return wd;
}
}
@Override
public boolean test(GregorianDate context) {
int y = context.getYear();
int m = context.getMonth();
int dom = context.getDayOfMonth();
return (GregorianMath.getDayOfWeek(y, m, dom) == this.getValue());
}
@Override
public PlainDate apply(PlainDate date) {
return date.with(PlainDate.DAY_OF_WEEK, this);
}
}
|
48835_20 | /*
* -----------------------------------------------------------------------
* Copyright © 2013-2018 Meno Hochschild, <http://www.menodata.de/>
* -----------------------------------------------------------------------
* This file (Weekday.java) is part of project Time4J.
*
* Time4J is free software: You can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 2.1 of the License, or
* (at your option) any later version.
*
* Time4J 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 Time4J. If not, see <http://www.gnu.org/licenses/>.
* -----------------------------------------------------------------------
*/
package net.time4j;
import net.time4j.base.GregorianDate;
import net.time4j.base.GregorianMath;
import net.time4j.engine.ChronoCondition;
import net.time4j.engine.ChronoOperator;
import net.time4j.engine.ThreetenAdapter;
import net.time4j.format.CalendarText;
import net.time4j.format.OutputContext;
import net.time4j.format.TextWidth;
import java.text.ParseException;
import java.text.ParsePosition;
import java.time.DayOfWeek;
import java.util.Locale;
/**
* <p>Enumeration of weekdays. </p>
*
* <p>Several methods with a {@code Weekmodel}-parameter support other
* week models, too. </p>
*
* @author Meno Hochschild
*/
/*[deutsch]
* <p>Wochentagsaufzählung. </p>
*
* <p>Verschiedene Methoden mit einem {@code Weekmodel}-Argument
* unterstützen zusätzlich andere Wochenmodelle. </p>
*
* @author Meno Hochschild
*/
public enum Weekday
implements ChronoCondition<GregorianDate>, ChronoOperator<PlainDate>, ThreetenAdapter {
//~ Statische Felder/Initialisierungen --------------------------------
/** Monday with the numerical ISO-value {@code 1}. */
/*[deutsch] Montag mit dem numerischen ISO-Wert {@code 1}. */
MONDAY,
/** Tuesday with the numerical ISO-value {@code 2}. */
/*[deutsch] Dienstag mit dem numerischen ISO-Wert {@code 2}. */
TUESDAY,
/** Wednesday with the numerical ISO-value {@code 3}. */
/*[deutsch] Mittwoch mit dem numerischen ISO-Wert {@code 3}. */
WEDNESDAY,
/** Thursday with the numerical ISO-value {@code 4}. */
/*[deutsch] Donnerstag mit dem numerischen ISO-Wert {@code 4}. */
THURSDAY,
/** Friday with the numerical ISO-value {@code 5}. */
/*[deutsch] Freitag mit dem numerischen ISO-Wert {@code 5}. */
FRIDAY,
/** Saturday with the numerical ISO-value {@code 6}. */
/*[deutsch] Samstag mit dem numerischen ISO-Wert {@code 6}. */
SATURDAY,
/** Sunday with the numerical ISO-value {@code 7}. */
/*[deutsch] Sonntag mit dem numerischen ISO-Wert {@code 7}. */
SUNDAY;
private static final Weekday[] ENUMS = Weekday.values(); // Cache
//~ Methoden ----------------------------------------------------------
/**
* <p>Gets the corresponding numerical ISO-value. </p>
*
* @return {@code monday=1, tuesday=2, wednesday=3, thursday=4, friday=5, saturday=6, sunday=7}
* @see #valueOf(int)
* @see Weekmodel#ISO
*/
/*[deutsch]
* <p>Liefert den korrespondierenden kalendarischen Integer-Wert
* entsprechend der ISO-8601-Norm. </p>
*
* @return {@code monday=1, tuesday=2, wednesday=3, thursday=4, friday=5, saturday=6, sunday=7}
* @see #valueOf(int)
* @see Weekmodel#ISO
*/
public int getValue() {
return (this.ordinal() + 1);
}
/**
* <p>Gets the numerical value corresponding to the rule of given
* week model on which day a week starts. </p>
*
* <p>In US, the rule is applied that weeks start with Sunday. If so then
* this method will yield {@code 1} for {@code Weekmodel.of(Locale.US)}
* (instead of the ISO-value {@code 7}). </p>
*
* @param model localized week model
* @return localized weekday number (1 - 7)
* @see Weekmodel#getFirstDayOfWeek()
* @see #values(Weekmodel)
* @see #valueOf(int, Weekmodel)
*/
/*[deutsch]
* <p>Liefert eine Wochentagsnummer passend zur im Modell enthaltenen
* Regel, mit welchem Tag eine Woche beginnt. </p>
*
* <p>Wird z.B. die in den USA übliche Regel angewandt, daß
* der erste Tag einer Woche der Sonntag sein soll, dann hat der Sonntag
* die Nummer 1 (statt 7 nach ISO-8601). </p>
*
* @param model localized week model
* @return localized weekday number (1 - 7)
* @see Weekmodel#getFirstDayOfWeek()
* @see #values(Weekmodel)
* @see #valueOf(int, Weekmodel)
*/
public int getValue(Weekmodel model) {
int shift = model.getFirstDayOfWeek().ordinal();
return ((7 + this.ordinal() - shift) % 7) + 1;
}
/**
* <p>Yields an array which is sorted corresponding to the rule of given
* week model on which day a week starts. </p>
*
* <p>The alternative method generated by compiler without any parameters
* creates an array sorted according to ISO-8601-standard. This method
* is an overloaded variation where sorting is adjusted. </p>
*
* @param model localized week model
* @return new weekday array
* @see Weekmodel#getFirstDayOfWeek()
* @see #getValue(Weekmodel)
* @see #valueOf(int, Weekmodel)
*/
/*[deutsch]
* <p>Liefert ein Array, das passend zur im Model enthaltenen Regel
* sortiert ist, mit welchem Tag eine Woche beginnt. </p>
*
* <p>Die vom Java-Compiler generierte {@code values()}-Methode ohne
* Argument richtet sich nach dem ISO-8601-Wochenmodell. Diese Methode
* ist die überladene Variante, in der die Sortierung angepasst
* ist. </p>
*
* @param model localized week model
* @return new weekday array
* @see Weekmodel#getFirstDayOfWeek()
* @see #getValue(Weekmodel)
* @see #valueOf(int, Weekmodel)
*/
public static Weekday[] values(Weekmodel model) {
Weekday[] enums = new Weekday[7];
Weekday wd = model.getFirstDayOfWeek();
for (int i = 0; i < 7; i++) {
enums[i] = wd;
wd = wd.next();
}
return enums;
}
/**
* <p>Gets the enum-constant which corresponds to the given numerical
* value. </p>
*
* @param dayOfWeek (monday=1, tuesday=2, wednesday=3, thursday=4,
* friday=5, saturday=6, sunday=7)
* @return weekday as enum
* @throws IllegalArgumentException if the argument is out of range
* @see #getValue()
* @see Weekmodel#ISO
*/
/*[deutsch]
* <p>Liefert die zum kalendarischen Integer-Wert passende
* Enum-Konstante entsprechend der ISO-8601-Norm. </p>
*
* @param dayOfWeek (monday=1, tuesday=2, wednesday=3, thursday=4,
* friday=5, saturday=6, sunday=7)
* @return weekday as enum
* @throws IllegalArgumentException if the argument is out of range
* @see #getValue()
* @see Weekmodel#ISO
*/
public static Weekday valueOf(int dayOfWeek) {
if ((dayOfWeek < 1) || (dayOfWeek > 7)) {
throw new IllegalArgumentException("Out of range: " + dayOfWeek);
}
return ENUMS[dayOfWeek - 1];
}
/**
* <p>Gets the enum-constant which corresponds to the given localized
* numerical value taking into account given week model. </p>
*
* @param dayOfWeek localized weekday number (1 - 7)
* @param model localized week model
* @return weekday as enum
* @throws IllegalArgumentException if the int-argument is out of range
* @see Weekmodel#getFirstDayOfWeek()
* @see #values(Weekmodel)
* @see #getValue(Weekmodel)
*/
/*[deutsch]
* <p>Liefert die zum kalendarischen Integer-Wert passende
* Enum-Konstante passend zum angegebenen Wochenmodell. </p>
*
* @param dayOfWeek localized weekday number (1 - 7)
* @param model localized week model
* @return weekday as enum
* @throws IllegalArgumentException if the int-argument is out of range
* @see Weekmodel#getFirstDayOfWeek()
* @see #values(Weekmodel)
* @see #getValue(Weekmodel)
*/
public static Weekday valueOf(
int dayOfWeek,
Weekmodel model
) {
if (
(dayOfWeek < 1)
|| (dayOfWeek > 7)
) {
throw new IllegalArgumentException(
"Weekday out of range: " + dayOfWeek);
}
int shift = model.getFirstDayOfWeek().ordinal();
return ENUMS[(dayOfWeek - 1 + shift) % 7];
}
/**
* <p>Gets the weekday corresponding to given gregorian date. </p>
*
* <p>The proleptic gregorian calendar as defined in ISO-8601 is the
* calculation basis. That means the current leap year rule is even
* applied for dates before the introduction of gregorian calendar. </p>
*
* @param year proleptic iso year
* @param monthOfYear gregorian month
* @param dayOfMonth day of month (1 - 31)
* @return weekday
* @throws IllegalArgumentException if the day is out of range
*/
/*[deutsch]
* <p>Liefert den Wochentag zum angegebenen Datum. </p>
*
* <p>Grundlage ist der gregorianische Kalender proleptisch für
* alle Zeiten ohne Kalenderwechsel angewandt. Es wird also so getan,
* als ob der gregorianische Kalender schon vor dem 15. Oktober 1582
* existiert hätte, so wie im ISO-8601-Format vorgesehen. </p>
*
* @param year proleptic iso year
* @param monthOfYear gregorian month
* @param dayOfMonth day of month (1 - 31)
* @return weekday
* @throws IllegalArgumentException if the day is out of range
*/
public static Weekday valueOf(
int year,
Month monthOfYear,
int dayOfMonth
) {
return Weekday.valueOf(
GregorianMath.getDayOfWeek(
year,
monthOfYear.getValue(),
dayOfMonth
)
);
}
/**
* <p>Rolls to the next day of week. </p>
*
* <p>The result is Monday if this method is applied on Sunday. </p>
*
* @return next weekday
*/
/*[deutsch]
* <p>Ermittelt den nächsten Wochentag. </p>
*
* <p>Auf den Sonntag angewandt ist das Ergebnis der Montag. </p>
*
* @return next weekday
*/
public Weekday next() {
int index = this.ordinal() + 1;
if (index == 7) {
index = 0;
}
return ENUMS[index];
}
/**
* <p>Rolls to the previous day of week. </p>
*
* <p>The result is Sunday if this method is applied on Monday. </p>
*
* @return previous weekday
*/
/*[deutsch]
* <p>Ermittelt den vorherigen Wochentag. </p>
*
* <p>Auf den Montag angewandt ist das Ergebnis der Sonntag. </p>
*
* @return previous weekday
*/
public Weekday previous() {
return this.roll(-1);
}
/**
* <p>Rolls this day of week by given amount of days. </p>
*
* @param days count of days (maybe negative)
* @return result of rolling operation
*/
/*[deutsch]
* <p>Rollt um die angegebene Anzahl von Tagen vor oder zurück. </p>
*
* @param days count of days (maybe negative)
* @return result of rolling operation
*/
public Weekday roll(int days) {
return Weekday.valueOf((this.ordinal() + (days % 7 + 7)) % 7 + 1);
}
/**
* <p>Equivalent to the expression
* {@code getDisplayName(locale, TextWidth.WIDE, OutputContext.FORMAT)}.
* </p>
*
* @param locale language setting
* @return descriptive text (long form, never {@code null})
* @see #getDisplayName(Locale, TextWidth, OutputContext)
*/
/*[deutsch]
* <p>Entspricht dem Ausdruck
* {@code getDisplayName(locale, TextWidth.WIDE, OutputContext.FORMAT)}.
* </p>
*
* @param locale language setting
* @return descriptive text (long form, never {@code null})
* @see #getDisplayName(Locale, TextWidth, OutputContext)
*/
public String getDisplayName(Locale locale) {
return this.getDisplayName(
locale, TextWidth.WIDE, OutputContext.FORMAT);
}
/**
* <p>Gets the description text dependent on the locale and style
* parameters. </p>
*
* <p>The second argument controls the width of description while the
* third argument is only relevant for languages which make a difference
* between stand-alone forms and embedded text forms (does not matter in
* English). </p>
*
* @param locale language setting
* @param width text width
* @param context output context
* @return descriptive text for given locale and style (never {@code null})
*/
/*[deutsch]
* <p>Liefert den sprachabhängigen Beschreibungstext. </p>
*
* <p>Über das zweite Argument kann gesteuert werden, ob eine kurze
* oder eine lange Form des Beschreibungstexts ausgegeben werden soll. Das
* ist besonders sinnvoll in Benutzeroberflächen, wo zwischen der
* Beschriftung und der detaillierten Erläuterung einer graphischen
* Komponente unterschieden wird. Das dritte Argument ist in Sprachen von
* Belang, die verschiedene grammatikalische Formen für die Ausgabe
* als alleinstehend oder eingebettet in formatierten Text kennen. </p>
*
* @param locale language setting
* @param width text width
* @param context output context
* @return descriptive text for given locale and style (never {@code null})
*/
public String getDisplayName(
Locale locale,
TextWidth width,
OutputContext context
) {
return CalendarText.getIsoInstance(locale).getWeekdays(width, context).print(this);
}
/**
* <p>Tries to interprete given text as day-of-week. </p>
*
* @param text the text to be parsed
* @param locale language setting
* @param width expected text width
* @param context expected output context
* @return the parsed day of week if successful
* @throws ParseException if parsing fails
* @see #getDisplayName(Locale, TextWidth, OutputContext)
* @since 3.33/4.28
*/
/*[deutsch]
* <p>Versucht, den angegebenen Text als Wochentag zu interpretieren. </p>
*
* @param text the text to be parsed
* @param locale language setting
* @param width expected text width
* @param context expected output context
* @return the parsed day of week if successful
* @throws ParseException if parsing fails
* @see #getDisplayName(Locale, TextWidth, OutputContext)
* @since 3.33/4.28
*/
public static Weekday parse(
CharSequence text,
Locale locale,
TextWidth width,
OutputContext context
) throws ParseException {
ParsePosition pp = new ParsePosition(0);
Weekday wd = CalendarText.getIsoInstance(locale).getWeekdays(width, context).parse(text, pp, Weekday.class);
if (wd == null) {
throw new ParseException("Cannot parse: " + text, pp.getErrorIndex());
} else {
return wd;
}
}
@Override
public boolean test(GregorianDate context) {
int y = context.getYear();
int m = context.getMonth();
int dom = context.getDayOfMonth();
return (GregorianMath.getDayOfWeek(y, m, dom) == this.getValue());
}
/**
* <p>Conversion to the {@code java.time}-equivalent. </p>
*
* @return DayOfWeek
* @see #from(DayOfWeek)
* @since 4.28
*/
/*[deutsch]
* <p>Konversion zum {@code java.time}-Äquivalent. </p>
*
* @return DayOfWeek
* @see #from(DayOfWeek)
* @since 4.28
*/
@Override
public DayOfWeek toTemporalAccessor() {
return DayOfWeek.of(this.getValue());
}
/**
* <p>Conversion from the {@code java.time}-equivalent. </p>
*
* @param dayOfWeek the day of week to be converted
* @return Weekday
* @see #toTemporalAccessor()
* @since 4.28
*/
/*[deutsch]
* <p>Konversion vom {@code java.time}-Äquivalent. </p>
*
* @param dayOfWeek the day of week to be converted
* @return Weekday
* @see #toTemporalAccessor()
* @since 4.28
*/
public static Weekday from(DayOfWeek dayOfWeek) {
return Weekday.valueOf(dayOfWeek.getValue());
}
@Override
public PlainDate apply(PlainDate date) {
return date.with(PlainDate.DAY_OF_WEEK, this);
}
}
| MenoData/Time4J | base/src/main/java/net/time4j/Weekday.java | 5,408 | /*[deutsch]
* <p>Liefert den korrespondierenden kalendarischen Integer-Wert
* entsprechend der ISO-8601-Norm. </p>
*
* @return {@code monday=1, tuesday=2, wednesday=3, thursday=4, friday=5, saturday=6, sunday=7}
* @see #valueOf(int)
* @see Weekmodel#ISO
*/ | block_comment | nl | /*
* -----------------------------------------------------------------------
* Copyright © 2013-2018 Meno Hochschild, <http://www.menodata.de/>
* -----------------------------------------------------------------------
* This file (Weekday.java) is part of project Time4J.
*
* Time4J is free software: You can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 2.1 of the License, or
* (at your option) any later version.
*
* Time4J 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 Time4J. If not, see <http://www.gnu.org/licenses/>.
* -----------------------------------------------------------------------
*/
package net.time4j;
import net.time4j.base.GregorianDate;
import net.time4j.base.GregorianMath;
import net.time4j.engine.ChronoCondition;
import net.time4j.engine.ChronoOperator;
import net.time4j.engine.ThreetenAdapter;
import net.time4j.format.CalendarText;
import net.time4j.format.OutputContext;
import net.time4j.format.TextWidth;
import java.text.ParseException;
import java.text.ParsePosition;
import java.time.DayOfWeek;
import java.util.Locale;
/**
* <p>Enumeration of weekdays. </p>
*
* <p>Several methods with a {@code Weekmodel}-parameter support other
* week models, too. </p>
*
* @author Meno Hochschild
*/
/*[deutsch]
* <p>Wochentagsaufzählung. </p>
*
* <p>Verschiedene Methoden mit einem {@code Weekmodel}-Argument
* unterstützen zusätzlich andere Wochenmodelle. </p>
*
* @author Meno Hochschild
*/
public enum Weekday
implements ChronoCondition<GregorianDate>, ChronoOperator<PlainDate>, ThreetenAdapter {
//~ Statische Felder/Initialisierungen --------------------------------
/** Monday with the numerical ISO-value {@code 1}. */
/*[deutsch] Montag mit dem numerischen ISO-Wert {@code 1}. */
MONDAY,
/** Tuesday with the numerical ISO-value {@code 2}. */
/*[deutsch] Dienstag mit dem numerischen ISO-Wert {@code 2}. */
TUESDAY,
/** Wednesday with the numerical ISO-value {@code 3}. */
/*[deutsch] Mittwoch mit dem numerischen ISO-Wert {@code 3}. */
WEDNESDAY,
/** Thursday with the numerical ISO-value {@code 4}. */
/*[deutsch] Donnerstag mit dem numerischen ISO-Wert {@code 4}. */
THURSDAY,
/** Friday with the numerical ISO-value {@code 5}. */
/*[deutsch] Freitag mit dem numerischen ISO-Wert {@code 5}. */
FRIDAY,
/** Saturday with the numerical ISO-value {@code 6}. */
/*[deutsch] Samstag mit dem numerischen ISO-Wert {@code 6}. */
SATURDAY,
/** Sunday with the numerical ISO-value {@code 7}. */
/*[deutsch] Sonntag mit dem numerischen ISO-Wert {@code 7}. */
SUNDAY;
private static final Weekday[] ENUMS = Weekday.values(); // Cache
//~ Methoden ----------------------------------------------------------
/**
* <p>Gets the corresponding numerical ISO-value. </p>
*
* @return {@code monday=1, tuesday=2, wednesday=3, thursday=4, friday=5, saturday=6, sunday=7}
* @see #valueOf(int)
* @see Weekmodel#ISO
*/
/*[deutsch]
<SUF>*/
public int getValue() {
return (this.ordinal() + 1);
}
/**
* <p>Gets the numerical value corresponding to the rule of given
* week model on which day a week starts. </p>
*
* <p>In US, the rule is applied that weeks start with Sunday. If so then
* this method will yield {@code 1} for {@code Weekmodel.of(Locale.US)}
* (instead of the ISO-value {@code 7}). </p>
*
* @param model localized week model
* @return localized weekday number (1 - 7)
* @see Weekmodel#getFirstDayOfWeek()
* @see #values(Weekmodel)
* @see #valueOf(int, Weekmodel)
*/
/*[deutsch]
* <p>Liefert eine Wochentagsnummer passend zur im Modell enthaltenen
* Regel, mit welchem Tag eine Woche beginnt. </p>
*
* <p>Wird z.B. die in den USA übliche Regel angewandt, daß
* der erste Tag einer Woche der Sonntag sein soll, dann hat der Sonntag
* die Nummer 1 (statt 7 nach ISO-8601). </p>
*
* @param model localized week model
* @return localized weekday number (1 - 7)
* @see Weekmodel#getFirstDayOfWeek()
* @see #values(Weekmodel)
* @see #valueOf(int, Weekmodel)
*/
public int getValue(Weekmodel model) {
int shift = model.getFirstDayOfWeek().ordinal();
return ((7 + this.ordinal() - shift) % 7) + 1;
}
/**
* <p>Yields an array which is sorted corresponding to the rule of given
* week model on which day a week starts. </p>
*
* <p>The alternative method generated by compiler without any parameters
* creates an array sorted according to ISO-8601-standard. This method
* is an overloaded variation where sorting is adjusted. </p>
*
* @param model localized week model
* @return new weekday array
* @see Weekmodel#getFirstDayOfWeek()
* @see #getValue(Weekmodel)
* @see #valueOf(int, Weekmodel)
*/
/*[deutsch]
* <p>Liefert ein Array, das passend zur im Model enthaltenen Regel
* sortiert ist, mit welchem Tag eine Woche beginnt. </p>
*
* <p>Die vom Java-Compiler generierte {@code values()}-Methode ohne
* Argument richtet sich nach dem ISO-8601-Wochenmodell. Diese Methode
* ist die überladene Variante, in der die Sortierung angepasst
* ist. </p>
*
* @param model localized week model
* @return new weekday array
* @see Weekmodel#getFirstDayOfWeek()
* @see #getValue(Weekmodel)
* @see #valueOf(int, Weekmodel)
*/
public static Weekday[] values(Weekmodel model) {
Weekday[] enums = new Weekday[7];
Weekday wd = model.getFirstDayOfWeek();
for (int i = 0; i < 7; i++) {
enums[i] = wd;
wd = wd.next();
}
return enums;
}
/**
* <p>Gets the enum-constant which corresponds to the given numerical
* value. </p>
*
* @param dayOfWeek (monday=1, tuesday=2, wednesday=3, thursday=4,
* friday=5, saturday=6, sunday=7)
* @return weekday as enum
* @throws IllegalArgumentException if the argument is out of range
* @see #getValue()
* @see Weekmodel#ISO
*/
/*[deutsch]
* <p>Liefert die zum kalendarischen Integer-Wert passende
* Enum-Konstante entsprechend der ISO-8601-Norm. </p>
*
* @param dayOfWeek (monday=1, tuesday=2, wednesday=3, thursday=4,
* friday=5, saturday=6, sunday=7)
* @return weekday as enum
* @throws IllegalArgumentException if the argument is out of range
* @see #getValue()
* @see Weekmodel#ISO
*/
public static Weekday valueOf(int dayOfWeek) {
if ((dayOfWeek < 1) || (dayOfWeek > 7)) {
throw new IllegalArgumentException("Out of range: " + dayOfWeek);
}
return ENUMS[dayOfWeek - 1];
}
/**
* <p>Gets the enum-constant which corresponds to the given localized
* numerical value taking into account given week model. </p>
*
* @param dayOfWeek localized weekday number (1 - 7)
* @param model localized week model
* @return weekday as enum
* @throws IllegalArgumentException if the int-argument is out of range
* @see Weekmodel#getFirstDayOfWeek()
* @see #values(Weekmodel)
* @see #getValue(Weekmodel)
*/
/*[deutsch]
* <p>Liefert die zum kalendarischen Integer-Wert passende
* Enum-Konstante passend zum angegebenen Wochenmodell. </p>
*
* @param dayOfWeek localized weekday number (1 - 7)
* @param model localized week model
* @return weekday as enum
* @throws IllegalArgumentException if the int-argument is out of range
* @see Weekmodel#getFirstDayOfWeek()
* @see #values(Weekmodel)
* @see #getValue(Weekmodel)
*/
public static Weekday valueOf(
int dayOfWeek,
Weekmodel model
) {
if (
(dayOfWeek < 1)
|| (dayOfWeek > 7)
) {
throw new IllegalArgumentException(
"Weekday out of range: " + dayOfWeek);
}
int shift = model.getFirstDayOfWeek().ordinal();
return ENUMS[(dayOfWeek - 1 + shift) % 7];
}
/**
* <p>Gets the weekday corresponding to given gregorian date. </p>
*
* <p>The proleptic gregorian calendar as defined in ISO-8601 is the
* calculation basis. That means the current leap year rule is even
* applied for dates before the introduction of gregorian calendar. </p>
*
* @param year proleptic iso year
* @param monthOfYear gregorian month
* @param dayOfMonth day of month (1 - 31)
* @return weekday
* @throws IllegalArgumentException if the day is out of range
*/
/*[deutsch]
* <p>Liefert den Wochentag zum angegebenen Datum. </p>
*
* <p>Grundlage ist der gregorianische Kalender proleptisch für
* alle Zeiten ohne Kalenderwechsel angewandt. Es wird also so getan,
* als ob der gregorianische Kalender schon vor dem 15. Oktober 1582
* existiert hätte, so wie im ISO-8601-Format vorgesehen. </p>
*
* @param year proleptic iso year
* @param monthOfYear gregorian month
* @param dayOfMonth day of month (1 - 31)
* @return weekday
* @throws IllegalArgumentException if the day is out of range
*/
public static Weekday valueOf(
int year,
Month monthOfYear,
int dayOfMonth
) {
return Weekday.valueOf(
GregorianMath.getDayOfWeek(
year,
monthOfYear.getValue(),
dayOfMonth
)
);
}
/**
* <p>Rolls to the next day of week. </p>
*
* <p>The result is Monday if this method is applied on Sunday. </p>
*
* @return next weekday
*/
/*[deutsch]
* <p>Ermittelt den nächsten Wochentag. </p>
*
* <p>Auf den Sonntag angewandt ist das Ergebnis der Montag. </p>
*
* @return next weekday
*/
public Weekday next() {
int index = this.ordinal() + 1;
if (index == 7) {
index = 0;
}
return ENUMS[index];
}
/**
* <p>Rolls to the previous day of week. </p>
*
* <p>The result is Sunday if this method is applied on Monday. </p>
*
* @return previous weekday
*/
/*[deutsch]
* <p>Ermittelt den vorherigen Wochentag. </p>
*
* <p>Auf den Montag angewandt ist das Ergebnis der Sonntag. </p>
*
* @return previous weekday
*/
public Weekday previous() {
return this.roll(-1);
}
/**
* <p>Rolls this day of week by given amount of days. </p>
*
* @param days count of days (maybe negative)
* @return result of rolling operation
*/
/*[deutsch]
* <p>Rollt um die angegebene Anzahl von Tagen vor oder zurück. </p>
*
* @param days count of days (maybe negative)
* @return result of rolling operation
*/
public Weekday roll(int days) {
return Weekday.valueOf((this.ordinal() + (days % 7 + 7)) % 7 + 1);
}
/**
* <p>Equivalent to the expression
* {@code getDisplayName(locale, TextWidth.WIDE, OutputContext.FORMAT)}.
* </p>
*
* @param locale language setting
* @return descriptive text (long form, never {@code null})
* @see #getDisplayName(Locale, TextWidth, OutputContext)
*/
/*[deutsch]
* <p>Entspricht dem Ausdruck
* {@code getDisplayName(locale, TextWidth.WIDE, OutputContext.FORMAT)}.
* </p>
*
* @param locale language setting
* @return descriptive text (long form, never {@code null})
* @see #getDisplayName(Locale, TextWidth, OutputContext)
*/
public String getDisplayName(Locale locale) {
return this.getDisplayName(
locale, TextWidth.WIDE, OutputContext.FORMAT);
}
/**
* <p>Gets the description text dependent on the locale and style
* parameters. </p>
*
* <p>The second argument controls the width of description while the
* third argument is only relevant for languages which make a difference
* between stand-alone forms and embedded text forms (does not matter in
* English). </p>
*
* @param locale language setting
* @param width text width
* @param context output context
* @return descriptive text for given locale and style (never {@code null})
*/
/*[deutsch]
* <p>Liefert den sprachabhängigen Beschreibungstext. </p>
*
* <p>Über das zweite Argument kann gesteuert werden, ob eine kurze
* oder eine lange Form des Beschreibungstexts ausgegeben werden soll. Das
* ist besonders sinnvoll in Benutzeroberflächen, wo zwischen der
* Beschriftung und der detaillierten Erläuterung einer graphischen
* Komponente unterschieden wird. Das dritte Argument ist in Sprachen von
* Belang, die verschiedene grammatikalische Formen für die Ausgabe
* als alleinstehend oder eingebettet in formatierten Text kennen. </p>
*
* @param locale language setting
* @param width text width
* @param context output context
* @return descriptive text for given locale and style (never {@code null})
*/
public String getDisplayName(
Locale locale,
TextWidth width,
OutputContext context
) {
return CalendarText.getIsoInstance(locale).getWeekdays(width, context).print(this);
}
/**
* <p>Tries to interprete given text as day-of-week. </p>
*
* @param text the text to be parsed
* @param locale language setting
* @param width expected text width
* @param context expected output context
* @return the parsed day of week if successful
* @throws ParseException if parsing fails
* @see #getDisplayName(Locale, TextWidth, OutputContext)
* @since 3.33/4.28
*/
/*[deutsch]
* <p>Versucht, den angegebenen Text als Wochentag zu interpretieren. </p>
*
* @param text the text to be parsed
* @param locale language setting
* @param width expected text width
* @param context expected output context
* @return the parsed day of week if successful
* @throws ParseException if parsing fails
* @see #getDisplayName(Locale, TextWidth, OutputContext)
* @since 3.33/4.28
*/
public static Weekday parse(
CharSequence text,
Locale locale,
TextWidth width,
OutputContext context
) throws ParseException {
ParsePosition pp = new ParsePosition(0);
Weekday wd = CalendarText.getIsoInstance(locale).getWeekdays(width, context).parse(text, pp, Weekday.class);
if (wd == null) {
throw new ParseException("Cannot parse: " + text, pp.getErrorIndex());
} else {
return wd;
}
}
@Override
public boolean test(GregorianDate context) {
int y = context.getYear();
int m = context.getMonth();
int dom = context.getDayOfMonth();
return (GregorianMath.getDayOfWeek(y, m, dom) == this.getValue());
}
/**
* <p>Conversion to the {@code java.time}-equivalent. </p>
*
* @return DayOfWeek
* @see #from(DayOfWeek)
* @since 4.28
*/
/*[deutsch]
* <p>Konversion zum {@code java.time}-Äquivalent. </p>
*
* @return DayOfWeek
* @see #from(DayOfWeek)
* @since 4.28
*/
@Override
public DayOfWeek toTemporalAccessor() {
return DayOfWeek.of(this.getValue());
}
/**
* <p>Conversion from the {@code java.time}-equivalent. </p>
*
* @param dayOfWeek the day of week to be converted
* @return Weekday
* @see #toTemporalAccessor()
* @since 4.28
*/
/*[deutsch]
* <p>Konversion vom {@code java.time}-Äquivalent. </p>
*
* @param dayOfWeek the day of week to be converted
* @return Weekday
* @see #toTemporalAccessor()
* @since 4.28
*/
public static Weekday from(DayOfWeek dayOfWeek) {
return Weekday.valueOf(dayOfWeek.getValue());
}
@Override
public PlainDate apply(PlainDate date) {
return date.with(PlainDate.DAY_OF_WEEK, this);
}
}
|
Subsets and Splits