file_id
stringlengths 5
9
| repo
stringlengths 8
57
| token_length
int64 59
7.96k
| path
stringlengths 8
105
| content
stringlengths 147
30.2k
| original_comment
stringlengths 14
5.13k
| prompt
stringlengths 82
30.2k
| Included
stringclasses 1
value |
---|---|---|---|---|---|---|---|
8343_4 | slawomirmarczynski/java | 1,857 | udp/src/licensecontrolserver/LicenseControlServerThreaded.java | /*
* The MIT License
*
* Copyright 2022 PI_stanowisko_1.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package licensecontrolserver;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
/**
* Serwer do sprawdzanie ważności licencji.
*
* Sprawdzanie ważności licencji odbywa się przez przesłanie do serwera prośby o
* udzielenie odpowiedzi (zgody na uruchomienie programu).
*
* @author Sławomir Marczyński
*/
public class LicenseControlServerThreaded implements Runnable {
// Uwaga: to uproszczona wersja, ale tym razem otwierany jest wątek roboczy
// - bo jednocześnie musimy obsługiwać zgłoszenia przez Internet (klientów)
// oraz sprawdzać czy program serwera ma nadal pracować.
public static void main(String[] args) throws IOException, InterruptedException {
Thread workingThread = new Thread(new LicenseControlServerThreaded());
workingThread.start();
System.out.print("press enter to stop server ");
new Scanner(System.in).hasNextLine();
workingThread.interrupt();
}
@Override
public void run() {
// Różne rzeczy mogą się zdarzyć, a ponieważ run() będzie w osobnym
// wątku to konieczne jest załatwienie (w tym osobnym wątku) wszelkich
// kłopotów w obrębie samego run().
try {
// Numer portu i wielkość bufora mają być takie same tu i w programach
// które będą się pytały o ważność swojej licencji. Chociaż obecnie
// program serwera i programy będące klientami serwera są po prostu
// odrębnymi projektami, to niemal równie łatwo byłoby połączyć je
// w jeden (i to akurat nie jest dobry pomysł) jak i stworzyć
// współdzieloną klasę "opakowującą" numer portu, długość bufora, sposób
// kodowania danych - czyli to co musi być takie samo w obu programach.
//
int PORT = 80;
DatagramSocket socket = new DatagramSocket(PORT);
final int BUFFER_SIZE = 512;
byte[] buffer = new byte[BUFFER_SIZE];
// Bardzo prymitywne rozwiązanie - niekończąca się pętla while - nadaje
// się tylko jako przykład - bo aby zakończyć program trzeba będzie
// zrobić to "ręcznie" za pomocą systemu - kill/terminate.
//
// Ustawienie time-out dla gniazda socket jest konieczne, bo jeżeli
// jest wartość domyślna (czyli 0) to receive() poniżej będzie
// czekać bez końca, czyli pętla się zablokuje i nieskuteczne będzie
// sprawdzanie warunku while, tzn. czy wątek nie jest zatrzymany.
//
// Uwaga: gdzieś kiedyś ktoś może poznał metodę stop() służącą do
// zatrzymywania wątków w Javie; owszem była, ale obecnie nie stosuje
// się jej, bo jest przestarzała.
//
socket.setSoTimeout(100);
while (!Thread.interrupted()) {
DatagramPacket request = new DatagramPacket(buffer, buffer.length);
socket.receive(request);
// Adres clientAddress wraz z numerem portu clientPort jest adresem
// IP pod którym nadawca datagramu (jaki tu odbieramy) czeka na
// odpowiedź.
//
// Uwaga: nie ma gwarancji że to co przyjdzie do nas przez sieć,
// czyli po prostu z Internetu, to jest naprawdę to co miało
// przyjść... każdy może próbować wysyłać nam różne rzeczy.
//
InetAddress clientAddress = request.getAddress();
int clientPort = request.getPort();
String messageString = new String(buffer, 0, request.getLength(), StandardCharsets.UTF_8);
System.out.println(clientAddress.getHostName() + ":" + clientPort + " -- " + messageString);
// Prymitywne i niezbyt skuteczne rozwiązanie: gdy serwer zgadza się
// na uruchomienie programu (licencja jest ważna) to odsyłamy yes,
// gdy serwer odmawia uruchomienia to informuje o tym wysyłając no.
//
// Oczywiście serwer może decyzję zgodzie uzależniać np. od już
// uruchomionych instancji programu (np. sprawdzać czy program
// z danym kluczem/id nie jest już uruchomiony więcej niż założoną
// liczbę razy).
//
String responseString = true ? "yes" : "no";
byte[] responseBytes = responseString.getBytes(StandardCharsets.UTF_8);
DatagramPacket response = new DatagramPacket(responseBytes, responseBytes.length,
clientAddress, clientPort);
socket.send(response);
}
} catch (IOException ex) {
}
}
}
| // oraz sprawdzać czy program serwera ma nadal pracować. | /*
* The MIT License
*
* Copyright 2022 PI_stanowisko_1.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package licensecontrolserver;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
/**
* Serwer do sprawdzanie ważności licencji.
*
* Sprawdzanie ważności licencji odbywa się przez przesłanie do serwera prośby o
* udzielenie odpowiedzi (zgody na uruchomienie programu).
*
* @author Sławomir Marczyński
*/
public class LicenseControlServerThreaded implements Runnable {
// Uwaga: to uproszczona wersja, ale tym razem otwierany jest wątek roboczy
// - bo jednocześnie musimy obsługiwać zgłoszenia przez Internet (klientów)
// oraz sprawdzać <SUF>
public static void main(String[] args) throws IOException, InterruptedException {
Thread workingThread = new Thread(new LicenseControlServerThreaded());
workingThread.start();
System.out.print("press enter to stop server ");
new Scanner(System.in).hasNextLine();
workingThread.interrupt();
}
@Override
public void run() {
// Różne rzeczy mogą się zdarzyć, a ponieważ run() będzie w osobnym
// wątku to konieczne jest załatwienie (w tym osobnym wątku) wszelkich
// kłopotów w obrębie samego run().
try {
// Numer portu i wielkość bufora mają być takie same tu i w programach
// które będą się pytały o ważność swojej licencji. Chociaż obecnie
// program serwera i programy będące klientami serwera są po prostu
// odrębnymi projektami, to niemal równie łatwo byłoby połączyć je
// w jeden (i to akurat nie jest dobry pomysł) jak i stworzyć
// współdzieloną klasę "opakowującą" numer portu, długość bufora, sposób
// kodowania danych - czyli to co musi być takie samo w obu programach.
//
int PORT = 80;
DatagramSocket socket = new DatagramSocket(PORT);
final int BUFFER_SIZE = 512;
byte[] buffer = new byte[BUFFER_SIZE];
// Bardzo prymitywne rozwiązanie - niekończąca się pętla while - nadaje
// się tylko jako przykład - bo aby zakończyć program trzeba będzie
// zrobić to "ręcznie" za pomocą systemu - kill/terminate.
//
// Ustawienie time-out dla gniazda socket jest konieczne, bo jeżeli
// jest wartość domyślna (czyli 0) to receive() poniżej będzie
// czekać bez końca, czyli pętla się zablokuje i nieskuteczne będzie
// sprawdzanie warunku while, tzn. czy wątek nie jest zatrzymany.
//
// Uwaga: gdzieś kiedyś ktoś może poznał metodę stop() służącą do
// zatrzymywania wątków w Javie; owszem była, ale obecnie nie stosuje
// się jej, bo jest przestarzała.
//
socket.setSoTimeout(100);
while (!Thread.interrupted()) {
DatagramPacket request = new DatagramPacket(buffer, buffer.length);
socket.receive(request);
// Adres clientAddress wraz z numerem portu clientPort jest adresem
// IP pod którym nadawca datagramu (jaki tu odbieramy) czeka na
// odpowiedź.
//
// Uwaga: nie ma gwarancji że to co przyjdzie do nas przez sieć,
// czyli po prostu z Internetu, to jest naprawdę to co miało
// przyjść... każdy może próbować wysyłać nam różne rzeczy.
//
InetAddress clientAddress = request.getAddress();
int clientPort = request.getPort();
String messageString = new String(buffer, 0, request.getLength(), StandardCharsets.UTF_8);
System.out.println(clientAddress.getHostName() + ":" + clientPort + " -- " + messageString);
// Prymitywne i niezbyt skuteczne rozwiązanie: gdy serwer zgadza się
// na uruchomienie programu (licencja jest ważna) to odsyłamy yes,
// gdy serwer odmawia uruchomienia to informuje o tym wysyłając no.
//
// Oczywiście serwer może decyzję zgodzie uzależniać np. od już
// uruchomionych instancji programu (np. sprawdzać czy program
// z danym kluczem/id nie jest już uruchomiony więcej niż założoną
// liczbę razy).
//
String responseString = true ? "yes" : "no";
byte[] responseBytes = responseString.getBytes(StandardCharsets.UTF_8);
DatagramPacket response = new DatagramPacket(responseBytes, responseBytes.length,
clientAddress, clientPort);
socket.send(response);
}
} catch (IOException ex) {
}
}
}
| t |
8260_7 | bartprokop/fiscal-printers | 2,139 | src/main/java/name/prokop/bart/fps/datamodel/Invoice.java | /*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
*
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package name.prokop.bart.fps.datamodel;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
*
* @author Bart
*/
public class Invoice {
/**
* Dodaje pozycje do paragonu
*
* @param name Nazwa towaru
* @param amount Ilość towaru
* @param price Cena brutto towaru
* @param taxRate Stawka VAT na towar
*/
public void addLine(String name, double amount, double price, VATRate taxRate) {
addLine(new SaleLine(name, amount, price, taxRate));
}
public void addLine(String name, double amount, double price, VATRate taxRate, DiscountType discountType, double discount) {
addLine(new SaleLine(name, amount, price, taxRate, discountType, discount));
}
public void addLine(SaleLine slipLine) {
slipLines.add(slipLine);
}
/**
* Getter for property noOfLines.
*
* @return Value of property noOfLines.
*/
public int getNoOfLines() {
return slipLines.size();
}
/**
* Indexed getter for property payment.
*
* @param index Index of the property.
* @return Value of the property at <CODE>index</CODE>.
*/
public SaleLine getLine(int index) {
return slipLines.get(index);
}
/**
* Służy pozyskaniu wartości brutto całego paragonu
*
* @return Wartość brutto całego paragonu
*/
public double getTotal() {
double sum = 0.0;
for (SaleLine slipLine : slipLines) {
sum += slipLine.getTotal();
}
return Toolbox.roundCurrency(sum);
}
/**
* Enum dla okreslenia stanu danego paragonu
*/
public enum PrintingState {
/**
* Nowo utworzony paragom
*/
Created,
/**
* LOCK - podczas drukowania
*/
DuringPrinting,
/**
* Wydrukowany - wszystko w porzadku jest
*/
Printed,
/**
* Paragon z bledem
*/
Errored;
@Override
public String toString() {
switch (this) {
case Created:
return "Nowy";
case DuringPrinting:
return "Drukuje sie";
case Errored:
return "Bledny";
case Printed:
return "Wydrukowany";
default:
throw new IllegalStateException();
}
}
}
@Override
public String toString() {
String retVal = "Slip: Reference: " + reference + " Kasa: " + getCashbox() + "\n";
for (SaleLine sl : slipLines) {
retVal += sl + "\n";
}
retVal += "Suma paragonu: " + getTotal() + " Kasjer: " + getCashierName();
return retVal;
}
/**
* referencja dla paragonu. musi byc unikalna
*/
private String reference;
/**
* Data utworzenia paragonu
*/
private Date created = new Date();
/**
* Data wydrukowania paragonu (jego fiskalizacji)
*/
private Date printed = null;
/**
* Nazwa kasy - pole na paragonie określające nazwę kasy fiskalnej. Używane
* również do rozróżnienia gdzie należy kolejkować wydruki.
*/
private String cashbox;
/**
* Imie i Nazwisko kasjera
*/
private String cashierName;
/**
* Linijki paragonu
*/
private List<SaleLine> slipLines = new ArrayList<>();
/**
* Stan paragonu
*/
private PrintingState printingState = PrintingState.Created;
/**
* Opis bledu w paragonie
*/
private String errorNote = PrintingState.Created.toString();
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getPrinted() {
return printed;
}
public void setPrinted(Date printed) {
this.printed = printed;
}
public List<SaleLine> getSlipLines() {
return slipLines;
}
public void setSlipLines(List<SaleLine> slipLines) {
this.slipLines = slipLines;
}
public String getCashbox() {
return cashbox;
}
public void setCashbox(String cashbox) {
if (cashbox != null) {
cashbox = cashbox.trim();
}
this.cashbox = cashbox;
}
public String getCashierName() {
return cashierName;
}
public void setCashierName(String cashierName) {
if (cashierName != null) {
cashierName = cashierName.trim();
}
this.cashierName = cashierName;
}
public PrintingState getPrintingState() {
return printingState;
}
public void setPrintingState(PrintingState printingState) {
this.printingState = printingState;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
if (reference != null) {
reference = reference.trim();
}
this.reference = reference;
}
public String getErrorNote() {
return errorNote;
}
public void setErrorNote(String errorNote) {
if (errorNote != null) {
errorNote = errorNote.trim();
}
this.errorNote = errorNote;
}
public String getNip() {
return nip;
}
public void setNip(String nip) {
this.nip = nip;
}
public String getPaymentDue() {
return paymentDue;
}
public void setPaymentDue(String paymentDue) {
this.paymentDue = paymentDue;
}
public String getPaymentType() {
return paymentType;
}
public void setPaymentType(String paymentType) {
this.paymentType = paymentType;
}
public String getHeader() {
return header;
}
public void setHeader(String header) {
this.header = header;
}
/**
* "813-188-60-14"
*/
private String nip;
/**
* "nigdy"
*/
private String paymentDue;
/**
* "przelew"
*/
private String paymentType;
/**
* "Firma\nul. Przemysłowa 9A\n35-111 Rzeszów"
*/
private String header;
}
| /**
* Nowo utworzony paragom
*/ | /*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
*
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package name.prokop.bart.fps.datamodel;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
*
* @author Bart
*/
public class Invoice {
/**
* Dodaje pozycje do paragonu
*
* @param name Nazwa towaru
* @param amount Ilość towaru
* @param price Cena brutto towaru
* @param taxRate Stawka VAT na towar
*/
public void addLine(String name, double amount, double price, VATRate taxRate) {
addLine(new SaleLine(name, amount, price, taxRate));
}
public void addLine(String name, double amount, double price, VATRate taxRate, DiscountType discountType, double discount) {
addLine(new SaleLine(name, amount, price, taxRate, discountType, discount));
}
public void addLine(SaleLine slipLine) {
slipLines.add(slipLine);
}
/**
* Getter for property noOfLines.
*
* @return Value of property noOfLines.
*/
public int getNoOfLines() {
return slipLines.size();
}
/**
* Indexed getter for property payment.
*
* @param index Index of the property.
* @return Value of the property at <CODE>index</CODE>.
*/
public SaleLine getLine(int index) {
return slipLines.get(index);
}
/**
* Służy pozyskaniu wartości brutto całego paragonu
*
* @return Wartość brutto całego paragonu
*/
public double getTotal() {
double sum = 0.0;
for (SaleLine slipLine : slipLines) {
sum += slipLine.getTotal();
}
return Toolbox.roundCurrency(sum);
}
/**
* Enum dla okreslenia stanu danego paragonu
*/
public enum PrintingState {
/**
* Nowo utworzony paragom <SUF>*/
Created,
/**
* LOCK - podczas drukowania
*/
DuringPrinting,
/**
* Wydrukowany - wszystko w porzadku jest
*/
Printed,
/**
* Paragon z bledem
*/
Errored;
@Override
public String toString() {
switch (this) {
case Created:
return "Nowy";
case DuringPrinting:
return "Drukuje sie";
case Errored:
return "Bledny";
case Printed:
return "Wydrukowany";
default:
throw new IllegalStateException();
}
}
}
@Override
public String toString() {
String retVal = "Slip: Reference: " + reference + " Kasa: " + getCashbox() + "\n";
for (SaleLine sl : slipLines) {
retVal += sl + "\n";
}
retVal += "Suma paragonu: " + getTotal() + " Kasjer: " + getCashierName();
return retVal;
}
/**
* referencja dla paragonu. musi byc unikalna
*/
private String reference;
/**
* Data utworzenia paragonu
*/
private Date created = new Date();
/**
* Data wydrukowania paragonu (jego fiskalizacji)
*/
private Date printed = null;
/**
* Nazwa kasy - pole na paragonie określające nazwę kasy fiskalnej. Używane
* również do rozróżnienia gdzie należy kolejkować wydruki.
*/
private String cashbox;
/**
* Imie i Nazwisko kasjera
*/
private String cashierName;
/**
* Linijki paragonu
*/
private List<SaleLine> slipLines = new ArrayList<>();
/**
* Stan paragonu
*/
private PrintingState printingState = PrintingState.Created;
/**
* Opis bledu w paragonie
*/
private String errorNote = PrintingState.Created.toString();
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getPrinted() {
return printed;
}
public void setPrinted(Date printed) {
this.printed = printed;
}
public List<SaleLine> getSlipLines() {
return slipLines;
}
public void setSlipLines(List<SaleLine> slipLines) {
this.slipLines = slipLines;
}
public String getCashbox() {
return cashbox;
}
public void setCashbox(String cashbox) {
if (cashbox != null) {
cashbox = cashbox.trim();
}
this.cashbox = cashbox;
}
public String getCashierName() {
return cashierName;
}
public void setCashierName(String cashierName) {
if (cashierName != null) {
cashierName = cashierName.trim();
}
this.cashierName = cashierName;
}
public PrintingState getPrintingState() {
return printingState;
}
public void setPrintingState(PrintingState printingState) {
this.printingState = printingState;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
if (reference != null) {
reference = reference.trim();
}
this.reference = reference;
}
public String getErrorNote() {
return errorNote;
}
public void setErrorNote(String errorNote) {
if (errorNote != null) {
errorNote = errorNote.trim();
}
this.errorNote = errorNote;
}
public String getNip() {
return nip;
}
public void setNip(String nip) {
this.nip = nip;
}
public String getPaymentDue() {
return paymentDue;
}
public void setPaymentDue(String paymentDue) {
this.paymentDue = paymentDue;
}
public String getPaymentType() {
return paymentType;
}
public void setPaymentType(String paymentType) {
this.paymentType = paymentType;
}
public String getHeader() {
return header;
}
public void setHeader(String header) {
this.header = header;
}
/**
* "813-188-60-14"
*/
private String nip;
/**
* "nigdy"
*/
private String paymentDue;
/**
* "przelew"
*/
private String paymentType;
/**
* "Firma\nul. Przemysłowa 9A\n35-111 Rzeszów"
*/
private String header;
}
| t |
10256_0 | zofiagrodecka/Concurrent-computing | 1,780 | Semaphores/src/main/java/RaceCondition.java | public class RaceCondition {
public static void main(String[] args) {
int n = 100000;
// 1.1
ISemaphore sem = new Semaphore(true);
Counter counter = new Counter(0, sem);
Runnable incr = () -> {
try{
for (int i = 0; i < n; i++) {
counter.increment();
}
} catch(InterruptedException e){
e.printStackTrace();
System.exit(-1);
}
};
Runnable decr = () -> {
try {
for (int i = 0; i < n; i++) {
counter.decrement();
}
} catch(InterruptedException e){
e.printStackTrace();
System.exit(-1);
}
};
Thread thread1 = new Thread(incr);
Thread thread2 = new Thread(decr);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
System.exit(-1);
}
System.out.println("Counter: " + counter.getCounter());
// 1.2
/*
Do implementacji semafora za pomocą metod wait i notify nie wystarczy instrukcja if, tylko potrzeba użyć while,
ponieważ mogłaby się zdarzyć taka sytuacja, że dany wątek zostanie obudzony, gdy nie jest spełniony warunek,
na którym czeka. Wtedy, gdyby tam było samo if, to wątek zostałby wpuszczony do sekcji krytycznej, chociaż nie
powinien, bo w tamtym ifie zobaczył on, że semafor jest podniesiony, a nie zdążył zobaczyć, że już ktoś przed
nim go opuścił. Żeby takiej sytuacji zapobiec, używa się pętli while zamiast samego if, która umożliwia
ponowne sprawdzenie, czy warunek faktycznie jest spełniony w momencie obudzenia wątku.
Praktyczny przykład:
2 wątki dzielące licznik w counterze, jeden go zwiększa a drugi go zmniejsza n-razy.
W takiej sytuacji bardzo często końcowa wartość countera jest różna od wartości, jaką miał na początku,
chociaż nie powinna. Wartość countera inna niż jego początkowa wartość świadczy o tym, że operacja P na semaforze
wpuściła do sekcji krytycznej obydwa wątki, chociaż nie powinna. Powinna była obudzić wyłącznie jeden z nich,
a drugi powinien nadal pozostać uśpiony. W takiej sytuacji następuje wyścig, ponieważ 2 wątki korzystają
jednocześnie z dzielonego zasobu i chcą go zmienić. Poprawnie zaimplementowany semafor z użyciem while zamiast
if by nie dopuścił do wyścigu, a tym samym wartość counter by została zwiększona tyle razy, ile razy byłaby
zmniejszona, więc na końcu pozostałaby niezmieniona. Niekiedy nawet występuje zakleszczenie obydwu
czekających wątków, czemu jest w stanie zapobiec użycie pętli while zamiast if.
*/
ISemaphore sem2 = new IncorrectSemaphore(true);
Counter counter2 = new Counter(0, sem2);
Runnable incr2 = () -> {
try{
for (int i = 0; i < n; i++) {
counter2.increment();
}
} catch(InterruptedException e){
e.printStackTrace();
System.exit(-1);
}
};
Runnable decr2 = () -> {
try {
for (int i = 0; i < n; i++) {
counter2.decrement();
}
} catch(InterruptedException e){
e.printStackTrace();
System.exit(-1);
}
};
Thread thread1_2 = new Thread(incr2);
Thread thread2_2 = new Thread(decr2);
thread1_2.start();
thread2_2.start();
try {
thread1_2.join();
thread2_2.join();
} catch (InterruptedException e) {
e.printStackTrace();
System.exit(-1);
}
System.out.println("Counter: " + counter2.getCounter());
// 1.3
/*
Semafor binarny jest szczególnym przypadkiem semafora ogólnego, ponieważ
działa on jak semafor ogólny, synchronizując dostęp do jednego współdzielonego zasobu.
Natomiast semafor ogólny może synchronizować dostęp do dowolnej ilości współdzielonych zasobów.
Przykład praktyczny:
Realizacja semafora binarnego wykorzystywanego do programu wyścig za pomocą semafora ogólnego.
Działa on poprawnie, ponieważ wartość counter na końcu wynosi 0, czyli tyle ile na początku.
*/
CountingSemaphore sem3 = new CountingSemaphore(1);
Counter counter3 = new Counter(0, sem3);
Runnable incr3 = () -> {
try{
for (int i = 0; i < n; i++) {
counter3.increment();
}
} catch(InterruptedException e){
e.printStackTrace();
System.exit(-1);
}
};
Runnable decr3 = () -> {
try {
for (int i = 0; i < n; i++) {
counter3.decrement();
}
} catch(InterruptedException e){
e.printStackTrace();
System.exit(-1);
}
};
Thread thread1_3 = new Thread(incr3);
Thread thread2_3 = new Thread(decr3);
thread1_3.start();
thread2_3.start();
try {
thread1_3.join();
thread2_3.join();
} catch (InterruptedException e) {
e.printStackTrace();
System.exit(-1);
}
System.out.println("Counter: " + counter3.getCounter());
}
}
| /*
Do implementacji semafora za pomocą metod wait i notify nie wystarczy instrukcja if, tylko potrzeba użyć while,
ponieważ mogłaby się zdarzyć taka sytuacja, że dany wątek zostanie obudzony, gdy nie jest spełniony warunek,
na którym czeka. Wtedy, gdyby tam było samo if, to wątek zostałby wpuszczony do sekcji krytycznej, chociaż nie
powinien, bo w tamtym ifie zobaczył on, że semafor jest podniesiony, a nie zdążył zobaczyć, że już ktoś przed
nim go opuścił. Żeby takiej sytuacji zapobiec, używa się pętli while zamiast samego if, która umożliwia
ponowne sprawdzenie, czy warunek faktycznie jest spełniony w momencie obudzenia wątku.
Praktyczny przykład:
2 wątki dzielące licznik w counterze, jeden go zwiększa a drugi go zmniejsza n-razy.
W takiej sytuacji bardzo często końcowa wartość countera jest różna od wartości, jaką miał na początku,
chociaż nie powinna. Wartość countera inna niż jego początkowa wartość świadczy o tym, że operacja P na semaforze
wpuściła do sekcji krytycznej obydwa wątki, chociaż nie powinna. Powinna była obudzić wyłącznie jeden z nich,
a drugi powinien nadal pozostać uśpiony. W takiej sytuacji następuje wyścig, ponieważ 2 wątki korzystają
jednocześnie z dzielonego zasobu i chcą go zmienić. Poprawnie zaimplementowany semafor z użyciem while zamiast
if by nie dopuścił do wyścigu, a tym samym wartość counter by została zwiększona tyle razy, ile razy byłaby
zmniejszona, więc na końcu pozostałaby niezmieniona. Niekiedy nawet występuje zakleszczenie obydwu
czekających wątków, czemu jest w stanie zapobiec użycie pętli while zamiast if.
*/ | public class RaceCondition {
public static void main(String[] args) {
int n = 100000;
// 1.1
ISemaphore sem = new Semaphore(true);
Counter counter = new Counter(0, sem);
Runnable incr = () -> {
try{
for (int i = 0; i < n; i++) {
counter.increment();
}
} catch(InterruptedException e){
e.printStackTrace();
System.exit(-1);
}
};
Runnable decr = () -> {
try {
for (int i = 0; i < n; i++) {
counter.decrement();
}
} catch(InterruptedException e){
e.printStackTrace();
System.exit(-1);
}
};
Thread thread1 = new Thread(incr);
Thread thread2 = new Thread(decr);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
System.exit(-1);
}
System.out.println("Counter: " + counter.getCounter());
// 1.2
/*
Do implementacji semafora <SUF>*/
ISemaphore sem2 = new IncorrectSemaphore(true);
Counter counter2 = new Counter(0, sem2);
Runnable incr2 = () -> {
try{
for (int i = 0; i < n; i++) {
counter2.increment();
}
} catch(InterruptedException e){
e.printStackTrace();
System.exit(-1);
}
};
Runnable decr2 = () -> {
try {
for (int i = 0; i < n; i++) {
counter2.decrement();
}
} catch(InterruptedException e){
e.printStackTrace();
System.exit(-1);
}
};
Thread thread1_2 = new Thread(incr2);
Thread thread2_2 = new Thread(decr2);
thread1_2.start();
thread2_2.start();
try {
thread1_2.join();
thread2_2.join();
} catch (InterruptedException e) {
e.printStackTrace();
System.exit(-1);
}
System.out.println("Counter: " + counter2.getCounter());
// 1.3
/*
Semafor binarny jest szczególnym przypadkiem semafora ogólnego, ponieważ
działa on jak semafor ogólny, synchronizując dostęp do jednego współdzielonego zasobu.
Natomiast semafor ogólny może synchronizować dostęp do dowolnej ilości współdzielonych zasobów.
Przykład praktyczny:
Realizacja semafora binarnego wykorzystywanego do programu wyścig za pomocą semafora ogólnego.
Działa on poprawnie, ponieważ wartość counter na końcu wynosi 0, czyli tyle ile na początku.
*/
CountingSemaphore sem3 = new CountingSemaphore(1);
Counter counter3 = new Counter(0, sem3);
Runnable incr3 = () -> {
try{
for (int i = 0; i < n; i++) {
counter3.increment();
}
} catch(InterruptedException e){
e.printStackTrace();
System.exit(-1);
}
};
Runnable decr3 = () -> {
try {
for (int i = 0; i < n; i++) {
counter3.decrement();
}
} catch(InterruptedException e){
e.printStackTrace();
System.exit(-1);
}
};
Thread thread1_3 = new Thread(incr3);
Thread thread2_3 = new Thread(decr3);
thread1_3.start();
thread2_3.start();
try {
thread1_3.join();
thread2_3.join();
} catch (InterruptedException e) {
e.printStackTrace();
System.exit(-1);
}
System.out.println("Counter: " + counter3.getCounter());
}
}
| t |
8500_1 | TomaszKorecki/InvestorAssistant | 115 | Investor's assistant/src/investor/network/DataType.java | /*
* 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 investor.network;
/**
*
* Mamy 4 typy danych:
* Indeksy giełdowe, spółki, waluty oraz towary
*/
public enum DataType {
WSK, SPOL, FOREX, TWR
}
| /**
*
* Mamy 4 typy danych:
* Indeksy giełdowe, spółki, waluty oraz towary
*/ | /*
* 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 investor.network;
/**
*
* Mamy 4 typy <SUF>*/
public enum DataType {
WSK, SPOL, FOREX, TWR
}
| t |
3377_7 | zoskar/SystemRowerowy | 1,976 | system/src/Uzytkownik.java | public class Uzytkownik {
private int userID;
private Miasto miasto;
private Rower rower;
private int[] lokalizacja;
private int czasWypozyczenia;
private SystemRowerowy systemRowerowy;
private Saldo saldo;
public Uzytkownik(int userID, Miasto miasto, int[] lokalizacja, Saldo saldo) {
this.userID = userID;
this.miasto = miasto;
this.rower = null;
this.lokalizacja = lokalizacja;
this.czasWypozyczenia = 0;
this.systemRowerowy = this.miasto.getSystem();
this.saldo = saldo;
}
public boolean maRower(){
return rower != null;
}
/**
* Metoda wypożyczenia roweru
* @param nrRoweru numer roweru który użytkownik chce wypożyczyć
*/
public void wypozyczRower(int nrRoweru){
//sprawdzamy czy użytkownik nie ma już wypożyczonego roweru
if (!maRower()){
Pair para = systemRowerowy.najblizszaStacja(lokalizacja, maRower());
StacjaRowerowa najblizszaStacja = para.getNajblizszaStacja();
double odlegloscOdStacji = para.getOdlegloscOdStacji();
if (odlegloscOdStacji <= 35){
//jest możliwość braku powodzenia: podany rower jest w środku stacja rowerów
rower = najblizszaStacja.wydajRower(nrRoweru);
//jeżeli udało się wypożyczyć rower
if (maRower()){
systemRowerowy.getListaWypozyczonychRowerow().add(rower);
}
}
else {
System.out.println("Nie znajdujesz się w pobliżu żadnej stacji. Najbliższa stacja to " +
najblizszaStacja.getNazwaStacji() + " odległa od Ciebie o " + odlegloscOdStacji);
}
}
else {
System.out.println("Masz obecnie wypożyczony rower!");
}
}
public void oddajRower() throws PelnaStacjaException {
if(maRower()){
Pair para = this.systemRowerowy.najblizszaStacja(this.lokalizacja, maRower());
StacjaRowerowa najblizszaStacja = para.getNajblizszaStacja();
double odlegloscOdStacji = para.getOdlegloscOdStacji();
if (odlegloscOdStacji <= 35){
System.out.println("Czy chcesz oddać rower w stacji: " + najblizszaStacja.getNazwaStacji() + "?");
//sprawdzamy czy stacja przyjmie rower (czy ma wolne miejsca)
if (najblizszaStacja.przyjmijRower(this.rower)){
this.systemRowerowy.getListaWypozyczonychRowerow().remove(this.rower);//usuniecie roweru z listy wypozyczonych rowerów
//czy to można tak robić?
System.out.print("Udało się zwrócić rower o numerze: ");
System.out.println(rower.getNrRoweru());
this.rower = null;
//zmniejszenie salda
saldo.pomniejsz(this.czasWypozyczenia);
//reset zegara wypożyczenia
System.out.println("Czas wypożyczenia: " +czasWypozyczenia);
this.czasWypozyczenia = 0;
}
// stacja nie ma wolnych miejsc
else {
throw new PelnaStacjaException("Stacja przy ktorej stoisz jest pełna\n" +
"Najbliższa stacja z wolnymi miejscami to: " + jakaNajblizszaStacja().getNazwaStacji());
}
}
else {
System.out.println("Jesteś za daleko od najbliższej stacji. Najbliższa stacja to: " +
najblizszaStacja.getNazwaStacji() + ". Znajdujesz się " + odlegloscOdStacji + " od niej");
}
}
else{
System.out.println("Nie posiadasz wypożyczonego roweru!");
}
}
/**
* Wyświetla na żądanie kod do obręczy wypożyczonego roweru
*/
public void wyswietlKodObreczy(){
if(maRower()){
System.out.println(rower.getKodObreczy());
}
else{
System.out.println("Nie posiadasz wypożyczonego roweru!");
}
}
/**
* Metoda wyświetlająca użytkownikowi nazwę najbliższej mu stacji rowerowej
* @return
*/
public StacjaRowerowa jakaNajblizszaStacja() {
System.out.println(this.systemRowerowy.najblizszaStacja(lokalizacja, maRower()).getNajblizszaStacja().getNazwaStacji());
return this.systemRowerowy.najblizszaStacja(lokalizacja, maRower()).getNajblizszaStacja();
}
public int sprawdzKodObreczy(){
if (maRower()) return rower.getKodObreczy();
else {
return -1;
}
}
public int getUserID() {
return userID;
}
public void setUserID(int userID) {
this.userID = userID;
}
public Miasto getMiasto() {
return miasto;
}
public void setMiasto(Miasto miasto) {
this.miasto = miasto;
}
public Rower getRower() {
return rower;
}
public void setRower(Rower rower) {
this.rower = rower;
}
public int[] getLokalizacja() {
return lokalizacja;
}
public void setLokalizacja(int[] lokalizacja) {
this.lokalizacja = lokalizacja;
}
public int getCzasWypozyczenia() {
return czasWypozyczenia;
}
public void setCzasWypozyczenia(int czasWypozyczenia) {
this.czasWypozyczenia = czasWypozyczenia;
}
public SystemRowerowy getSystemRowerowy() {return systemRowerowy;}
public void setSystemRowerowy(SystemRowerowy systemRowerowy) {this.systemRowerowy = systemRowerowy;}
public Saldo getSaldo() {return saldo;}
public void setSaldo(Saldo saldo) {this.saldo = saldo;}
}
| //reset zegara wypożyczenia | public class Uzytkownik {
private int userID;
private Miasto miasto;
private Rower rower;
private int[] lokalizacja;
private int czasWypozyczenia;
private SystemRowerowy systemRowerowy;
private Saldo saldo;
public Uzytkownik(int userID, Miasto miasto, int[] lokalizacja, Saldo saldo) {
this.userID = userID;
this.miasto = miasto;
this.rower = null;
this.lokalizacja = lokalizacja;
this.czasWypozyczenia = 0;
this.systemRowerowy = this.miasto.getSystem();
this.saldo = saldo;
}
public boolean maRower(){
return rower != null;
}
/**
* Metoda wypożyczenia roweru
* @param nrRoweru numer roweru który użytkownik chce wypożyczyć
*/
public void wypozyczRower(int nrRoweru){
//sprawdzamy czy użytkownik nie ma już wypożyczonego roweru
if (!maRower()){
Pair para = systemRowerowy.najblizszaStacja(lokalizacja, maRower());
StacjaRowerowa najblizszaStacja = para.getNajblizszaStacja();
double odlegloscOdStacji = para.getOdlegloscOdStacji();
if (odlegloscOdStacji <= 35){
//jest możliwość braku powodzenia: podany rower jest w środku stacja rowerów
rower = najblizszaStacja.wydajRower(nrRoweru);
//jeżeli udało się wypożyczyć rower
if (maRower()){
systemRowerowy.getListaWypozyczonychRowerow().add(rower);
}
}
else {
System.out.println("Nie znajdujesz się w pobliżu żadnej stacji. Najbliższa stacja to " +
najblizszaStacja.getNazwaStacji() + " odległa od Ciebie o " + odlegloscOdStacji);
}
}
else {
System.out.println("Masz obecnie wypożyczony rower!");
}
}
public void oddajRower() throws PelnaStacjaException {
if(maRower()){
Pair para = this.systemRowerowy.najblizszaStacja(this.lokalizacja, maRower());
StacjaRowerowa najblizszaStacja = para.getNajblizszaStacja();
double odlegloscOdStacji = para.getOdlegloscOdStacji();
if (odlegloscOdStacji <= 35){
System.out.println("Czy chcesz oddać rower w stacji: " + najblizszaStacja.getNazwaStacji() + "?");
//sprawdzamy czy stacja przyjmie rower (czy ma wolne miejsca)
if (najblizszaStacja.przyjmijRower(this.rower)){
this.systemRowerowy.getListaWypozyczonychRowerow().remove(this.rower);//usuniecie roweru z listy wypozyczonych rowerów
//czy to można tak robić?
System.out.print("Udało się zwrócić rower o numerze: ");
System.out.println(rower.getNrRoweru());
this.rower = null;
//zmniejszenie salda
saldo.pomniejsz(this.czasWypozyczenia);
//reset zegara <SUF>
System.out.println("Czas wypożyczenia: " +czasWypozyczenia);
this.czasWypozyczenia = 0;
}
// stacja nie ma wolnych miejsc
else {
throw new PelnaStacjaException("Stacja przy ktorej stoisz jest pełna\n" +
"Najbliższa stacja z wolnymi miejscami to: " + jakaNajblizszaStacja().getNazwaStacji());
}
}
else {
System.out.println("Jesteś za daleko od najbliższej stacji. Najbliższa stacja to: " +
najblizszaStacja.getNazwaStacji() + ". Znajdujesz się " + odlegloscOdStacji + " od niej");
}
}
else{
System.out.println("Nie posiadasz wypożyczonego roweru!");
}
}
/**
* Wyświetla na żądanie kod do obręczy wypożyczonego roweru
*/
public void wyswietlKodObreczy(){
if(maRower()){
System.out.println(rower.getKodObreczy());
}
else{
System.out.println("Nie posiadasz wypożyczonego roweru!");
}
}
/**
* Metoda wyświetlająca użytkownikowi nazwę najbliższej mu stacji rowerowej
* @return
*/
public StacjaRowerowa jakaNajblizszaStacja() {
System.out.println(this.systemRowerowy.najblizszaStacja(lokalizacja, maRower()).getNajblizszaStacja().getNazwaStacji());
return this.systemRowerowy.najblizszaStacja(lokalizacja, maRower()).getNajblizszaStacja();
}
public int sprawdzKodObreczy(){
if (maRower()) return rower.getKodObreczy();
else {
return -1;
}
}
public int getUserID() {
return userID;
}
public void setUserID(int userID) {
this.userID = userID;
}
public Miasto getMiasto() {
return miasto;
}
public void setMiasto(Miasto miasto) {
this.miasto = miasto;
}
public Rower getRower() {
return rower;
}
public void setRower(Rower rower) {
this.rower = rower;
}
public int[] getLokalizacja() {
return lokalizacja;
}
public void setLokalizacja(int[] lokalizacja) {
this.lokalizacja = lokalizacja;
}
public int getCzasWypozyczenia() {
return czasWypozyczenia;
}
public void setCzasWypozyczenia(int czasWypozyczenia) {
this.czasWypozyczenia = czasWypozyczenia;
}
public SystemRowerowy getSystemRowerowy() {return systemRowerowy;}
public void setSystemRowerowy(SystemRowerowy systemRowerowy) {this.systemRowerowy = systemRowerowy;}
public Saldo getSaldo() {return saldo;}
public void setSaldo(Saldo saldo) {this.saldo = saldo;}
}
| t |
9934_13 | Wojtek120/IMU-velocity-and-displacement-measurements | 1,696 | AndroidApp/app/src/main/java/com/example/wojciech/program/DatabaseHelperRPY.java | package com.example.wojciech.program;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Klasa odpowiedzialna za obsluge wpisow katow RPY do bazy SQLite,
* w niej baza jest tworzona i wysylane sa zapytania do niej
*/
public class DatabaseHelperRPY extends SQLiteOpenHelper
{
/** TAG */
private static final String TAG = "DatabaseHelperRPY";
/** Nazwa bazy danych */
private static final String TABLE_NAME = "RPYDataDatabase";
/** Nazwa kolumny 1 - nr kolumny*/
private static String COL0_NUMBER = "number";
/** Nazwa kolumny 2 - id */
private static String COL1_ID = "id";
/** Nazwa kolumny 3 - nazwa */
private static String COL2_EXERCISE = "exercise";
/** Nazwa kolumny 4 - czas */
private static String COL3_TIME = "time";
/** Nazwa kolumny 5 - nr kontrolny1 */
private static String COL4_CONTROL_NR = "control_nr_1";
/** Nazwa kolumny 6 - kat yaw */
private static String COL5_YAW = "yaw";
/** Nazwa kolumny 7 - kat pitch */
private static String COL6_PITCH = "pitch";
/** Nazwa kolumny 8 - kat roll */
private static String COL7_ROLL = "roll";
/** Kontekst */
Context context;
/**
* Konstruktor
*
* @param context - kontekst
*/
public DatabaseHelperRPY(Context context)
{
super(context, TABLE_NAME, null, 1);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase)
{
String createTable = "CREATE TABLE " + TABLE_NAME + " (" + COL0_NUMBER + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL1_ID + " INTEGER, " +
COL2_EXERCISE + " TEXT, " +
COL3_TIME + " DATETIME DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')), " +
COL4_CONTROL_NR + " INTEGER, " +
COL5_YAW + " REAL, " +
COL6_PITCH + " REAL, " +
COL7_ROLL + " REAL)";
sqLiteDatabase.execSQL(createTable);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1)
{
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(sqLiteDatabase);
}
/**
* Dodawanie danych do bazy danych
*
* @param IDofExercise - id cwiczenia
* @param nameOfExercise - nazwa cwiczenia
* @param controlNumber - numer kontrolny
* @param yawAngle - kat yaw
* @param pitchAngle - kat pitch
* @param rollAngle - kat roll
* @return - prawda gdy dodane poprawnie, w innym wypadku falsz
*/
public boolean addData(long IDofExercise, String nameOfExercise, int controlNumber, double yawAngle, double pitchAngle, double rollAngle)
{
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL1_ID, IDofExercise);
contentValues.put(COL2_EXERCISE, nameOfExercise);
contentValues.put(COL4_CONTROL_NR, controlNumber);
contentValues.put(COL5_YAW, yawAngle);
contentValues.put(COL6_PITCH, pitchAngle);
contentValues.put(COL7_ROLL, rollAngle);
long result = sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
return !(result == -1);
}
/**
* Zwraca dane z bazy
*
* @param IDinSQL - nazwa ID w bazie danych do ktorego maja zostac zwrocone, jesli -1 to zwrocone wszytskie dane
* @return - wybrane dane
*/
public Cursor getData(int IDinSQL)
{
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
String query;
if(IDinSQL == -1)
{
query = "SELECT * FROM " + TABLE_NAME + " ORDER BY " + COL3_TIME;
}
else
{
query = "SELECT * FROM " + TABLE_NAME + " WHERE " + COL1_ID + " = " + Integer.toString(IDinSQL) + " ORDER BY " + COL3_TIME;
}
return sqLiteDatabase.rawQuery(query, null);
}
/**
* Funkcja aktualizujaca nazwe cwiczenia
* @param newName - nazwa do zaktualizowania
* @param id - id rekordu ktory ma byc zaktualizowany
*/
public void updateExerciseName(String newName, int id)
{
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
String query = "UPDATE " + TABLE_NAME + " SET " + COL2_EXERCISE + " = '" + newName +
"' WHERE " + COL1_ID + " = '" + id + "'";
Log.i(TAG, "updateName " + query);
sqLiteDatabase.execSQL(query);
}
/**
* Funkcja usuwajaca cwiczenie o danym ID
* @param id - id rekordu, ktory ma byc usuniety
*/
public void deleteExercise(int id)
{
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_NAME + " WHERE " + COL1_ID + " = '" + id + "'";
Log.i(TAG, "updateName " + query);
sqLiteDatabase.execSQL(query);
}
}
| /**
* Funkcja aktualizujaca nazwe cwiczenia
* @param newName - nazwa do zaktualizowania
* @param id - id rekordu ktory ma byc zaktualizowany
*/ | package com.example.wojciech.program;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Klasa odpowiedzialna za obsluge wpisow katow RPY do bazy SQLite,
* w niej baza jest tworzona i wysylane sa zapytania do niej
*/
public class DatabaseHelperRPY extends SQLiteOpenHelper
{
/** TAG */
private static final String TAG = "DatabaseHelperRPY";
/** Nazwa bazy danych */
private static final String TABLE_NAME = "RPYDataDatabase";
/** Nazwa kolumny 1 - nr kolumny*/
private static String COL0_NUMBER = "number";
/** Nazwa kolumny 2 - id */
private static String COL1_ID = "id";
/** Nazwa kolumny 3 - nazwa */
private static String COL2_EXERCISE = "exercise";
/** Nazwa kolumny 4 - czas */
private static String COL3_TIME = "time";
/** Nazwa kolumny 5 - nr kontrolny1 */
private static String COL4_CONTROL_NR = "control_nr_1";
/** Nazwa kolumny 6 - kat yaw */
private static String COL5_YAW = "yaw";
/** Nazwa kolumny 7 - kat pitch */
private static String COL6_PITCH = "pitch";
/** Nazwa kolumny 8 - kat roll */
private static String COL7_ROLL = "roll";
/** Kontekst */
Context context;
/**
* Konstruktor
*
* @param context - kontekst
*/
public DatabaseHelperRPY(Context context)
{
super(context, TABLE_NAME, null, 1);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase)
{
String createTable = "CREATE TABLE " + TABLE_NAME + " (" + COL0_NUMBER + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL1_ID + " INTEGER, " +
COL2_EXERCISE + " TEXT, " +
COL3_TIME + " DATETIME DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')), " +
COL4_CONTROL_NR + " INTEGER, " +
COL5_YAW + " REAL, " +
COL6_PITCH + " REAL, " +
COL7_ROLL + " REAL)";
sqLiteDatabase.execSQL(createTable);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1)
{
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(sqLiteDatabase);
}
/**
* Dodawanie danych do bazy danych
*
* @param IDofExercise - id cwiczenia
* @param nameOfExercise - nazwa cwiczenia
* @param controlNumber - numer kontrolny
* @param yawAngle - kat yaw
* @param pitchAngle - kat pitch
* @param rollAngle - kat roll
* @return - prawda gdy dodane poprawnie, w innym wypadku falsz
*/
public boolean addData(long IDofExercise, String nameOfExercise, int controlNumber, double yawAngle, double pitchAngle, double rollAngle)
{
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL1_ID, IDofExercise);
contentValues.put(COL2_EXERCISE, nameOfExercise);
contentValues.put(COL4_CONTROL_NR, controlNumber);
contentValues.put(COL5_YAW, yawAngle);
contentValues.put(COL6_PITCH, pitchAngle);
contentValues.put(COL7_ROLL, rollAngle);
long result = sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
return !(result == -1);
}
/**
* Zwraca dane z bazy
*
* @param IDinSQL - nazwa ID w bazie danych do ktorego maja zostac zwrocone, jesli -1 to zwrocone wszytskie dane
* @return - wybrane dane
*/
public Cursor getData(int IDinSQL)
{
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
String query;
if(IDinSQL == -1)
{
query = "SELECT * FROM " + TABLE_NAME + " ORDER BY " + COL3_TIME;
}
else
{
query = "SELECT * FROM " + TABLE_NAME + " WHERE " + COL1_ID + " = " + Integer.toString(IDinSQL) + " ORDER BY " + COL3_TIME;
}
return sqLiteDatabase.rawQuery(query, null);
}
/**
* Funkcja aktualizujaca nazwe <SUF>*/
public void updateExerciseName(String newName, int id)
{
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
String query = "UPDATE " + TABLE_NAME + " SET " + COL2_EXERCISE + " = '" + newName +
"' WHERE " + COL1_ID + " = '" + id + "'";
Log.i(TAG, "updateName " + query);
sqLiteDatabase.execSQL(query);
}
/**
* Funkcja usuwajaca cwiczenie o danym ID
* @param id - id rekordu, ktory ma byc usuniety
*/
public void deleteExercise(int id)
{
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_NAME + " WHERE " + COL1_ID + " = '" + id + "'";
Log.i(TAG, "updateName " + query);
sqLiteDatabase.execSQL(query);
}
}
| t |
3791_4 | Nicrim98/Checkers---Java | 888 | src/Square.java | public class Square{ // definicja pojedynczego kafelka, będzie potrzeba np. do sprawdzania czy figura stacjonuje na danym polu ;)
private int column;
private int row;
private String piece_type;
private int what_square = 0;
private Piece piece = null;
// private Possition possition;
public Square(int column, int row) {
this.column = column;
this.row = row;
}
public Square(String piece_type){
this.piece_type = piece_type;
if (piece_type.equals("W")){ // white pawn
what_square = 1;
}
if (piece_type.equals("B")){ // black pawn
what_square = -1;
}
if (piece_type.equals("WQ")){ // white queen
what_square = 3;
}
if (piece_type.equals("BQ")){ // black queen
what_square = 4;
}
}
// Getter Pionka z danego square'a
public Piece getPiece(){
return piece;
}
// Umieszczenie pionka na polu
public Piece putPiece(Piece p){
Piece previous = this.piece;
if( previous != null){
previous.removeSquare();
}
this.piece = p;
return previous;
}
// Usunięcie pionka z pola
public Piece removePiece(){
Piece previous = this.piece;
if( previous != null){
previous.removeSquare();
}
this.piece = null;
return previous;
}
public int getColumn(){
return column;
}
public int getRow(){
return row;
}
@Override
public String toString(){ // metoda z poprzedniego projektu pokerowego
if(piece == null){
return "-";
}
else
return piece.toString(); // poprawiona metoda wyświetlania wzięta od Cecylii
} // choć jeszcze do końca nie działa, możesz sobie podpatrzeću Cecylii, że tam jeszcze są odwołania w figurze do rodzaju figury
// na razie nie wiem jeszcze jak to załatwić
public Possition getPossition(Square square){
Possition possition = new Possition(square.getRow(),square.getColumn());
return possition;
}
}
// public Piece setPiece(Piece type_of_piece, int column, int row){
// return
//}
//public Piece getPiece();
/* public String toString(){ // metoda z poprzednim pomysłem i wyświetlaniem pól
String squareString;
String[] list_of_rows = { "1", "2", "3", "4", "5", "6", "7", "8"};
String[] list_of_columns = { "A", "B", "C", "D", "E", "F", "G", "H"};
squareString = list_of_columns[column] + list_of_rows[row] + " ";
return squareString ;
}*/ | // Usunięcie pionka z pola | public class Square{ // definicja pojedynczego kafelka, będzie potrzeba np. do sprawdzania czy figura stacjonuje na danym polu ;)
private int column;
private int row;
private String piece_type;
private int what_square = 0;
private Piece piece = null;
// private Possition possition;
public Square(int column, int row) {
this.column = column;
this.row = row;
}
public Square(String piece_type){
this.piece_type = piece_type;
if (piece_type.equals("W")){ // white pawn
what_square = 1;
}
if (piece_type.equals("B")){ // black pawn
what_square = -1;
}
if (piece_type.equals("WQ")){ // white queen
what_square = 3;
}
if (piece_type.equals("BQ")){ // black queen
what_square = 4;
}
}
// Getter Pionka z danego square'a
public Piece getPiece(){
return piece;
}
// Umieszczenie pionka na polu
public Piece putPiece(Piece p){
Piece previous = this.piece;
if( previous != null){
previous.removeSquare();
}
this.piece = p;
return previous;
}
// Usunięcie pionka <SUF>
public Piece removePiece(){
Piece previous = this.piece;
if( previous != null){
previous.removeSquare();
}
this.piece = null;
return previous;
}
public int getColumn(){
return column;
}
public int getRow(){
return row;
}
@Override
public String toString(){ // metoda z poprzedniego projektu pokerowego
if(piece == null){
return "-";
}
else
return piece.toString(); // poprawiona metoda wyświetlania wzięta od Cecylii
} // choć jeszcze do końca nie działa, możesz sobie podpatrzeću Cecylii, że tam jeszcze są odwołania w figurze do rodzaju figury
// na razie nie wiem jeszcze jak to załatwić
public Possition getPossition(Square square){
Possition possition = new Possition(square.getRow(),square.getColumn());
return possition;
}
}
// public Piece setPiece(Piece type_of_piece, int column, int row){
// return
//}
//public Piece getPiece();
/* public String toString(){ // metoda z poprzednim pomysłem i wyświetlaniem pól
String squareString;
String[] list_of_rows = { "1", "2", "3", "4", "5", "6", "7", "8"};
String[] list_of_columns = { "A", "B", "C", "D", "E", "F", "G", "H"};
squareString = list_of_columns[column] + list_of_rows[row] + " ";
return squareString ;
}*/ | t |
6387_3 | AnnCzar/Bazy-danych-project | 1,452 | src/main/java/org/example/demo5/Calc.java | package org.example.demo5;
import javafx.event.ActionEvent;
import java.time.LocalDate;
public class Calc {
// nw jeszcze czy trzeba do kazdego osobny action event czy to nie starczy jeden
public double cpm(String activity, String goal, Integer mealCount, String gender, Double height,
double weight, Integer age) {
double index;
double ppm = 0;
double diff = 0;
if (activity.equals("brak (osoba chora, leżąca w łóżku)")) {
index = 1.2;
} else if (activity.equals("mała (osoba wykonująca pracę siedzącą)")) {
index = 1.4;
} else if (activity.equals(("umiarkowana (osoba wykonująca pracę na stojąco)"))) {
index = 1.6;
} else if (activity.equals("duża (osoba prowadząca aktywny tryb życia, regularnie ćwicząca)")) {
index = 1.75;
} else if (activity.equals("bardzo duża (osoba prowadząca bardzo aktywny tryb życia, codziennie ćwicząca)")) {
index = 2.0;
} else {
index = 2.4;
}
if (gender.equals("kobieta")) {
ppm = 655.1 + (9.563 * weight) + (1.85 * height) - (4.676 * age);
} else if (gender.equals("mężczyzna")) {
ppm = 66.473 + (13.752 * weight) + (5.003 * height) - (6.775 * age);
}
if (goal.equals("schudnąć")) {
diff = -0.15 * ppm;
} else if(goal.equals("utrzymać wagę")) {
diff = 0;
} else if (goal.equals("przytyć")) {
diff = 0.15 * ppm;
}
// te wartosci bedzie mozna pozmieniac
return ppm * index + diff;
}
public double calc_bmi (double weight, double height) {
double bmi = weight / Math.pow(height/100,2);
return bmi;
}
public String acceptor(double bmi, String goal) {
if (bmi < 18.49 && (goal.equals("schudnąć") || goal.equals("utrzymać wagę"))) {
return "WYBRANO CEL ZAGRAŻAJĄCY ZDROWIU";
} else if (bmi >= 18.50 && bmi <= 24.99) {
return "";
} else if (bmi > 25 && (goal.equals("przytyć") || goal.equals("utrzymać wagę"))) {
return "WYBRANO CEL ZAGRAŻAJĄCY ZDROWIU";
}
return "";
}
String Date_check(Integer day, Integer month, Integer year){
int [] days_31 = {1, 3, 5, 7, 8,10, 12}; // Tablica do sprawdzania czy dany miesiąc ma 31 dni.
String data = "";
LocalDate date1 = null;
if (day > 31){ // Rzucanie wyjątów dla źle wprowadzonych danych
throw new IllegalArgumentException("Entered day is out of the range");
}
else if (month > 12){
throw new IllegalArgumentException("Entered day is out of the range");
}
else if (day == 31 && (days_31.equals(month)== true)){ // formatowaanie dla daty, która ma 31 dni
data += day;
if (month < 10){
data += "-0" + month + "-" + year;
}
else{
data += "-" + month + "-" + year;
}
}
else if (day == 31 && (days_31.equals(month)== false)){ // Wyrzucenie wyjatku dla wprowadzonej daty np 31-04-2023
throw new IllegalArgumentException("Date does not exist");
}
else if (month == 2){ // Foramtowanie dla daty z lutym
if (day < 10 ){
data += "0" + day + "-0" + month + "-" + year;
}
else if ( day > 29){
throw new IllegalArgumentException(" Date does not exist");
}
else{
data += day + "-0" + month + "-" + year;
}
}
else {
if (day < 10 && month < 10){
data += "0" + day + "-0" + month + "-" + year;
}
else if ( day < 10 && month >= 10){
data += "0" + day + "-" + month + "-" + year;
}
else if (day > 9 && month > 9){
data += day + "-" + month + "-" + year;
}
else {
data += day + "-0" + month + "-" + year;
}
}
return data;
}
} | // Rzucanie wyjątów dla źle wprowadzonych danych
| package org.example.demo5;
import javafx.event.ActionEvent;
import java.time.LocalDate;
public class Calc {
// nw jeszcze czy trzeba do kazdego osobny action event czy to nie starczy jeden
public double cpm(String activity, String goal, Integer mealCount, String gender, Double height,
double weight, Integer age) {
double index;
double ppm = 0;
double diff = 0;
if (activity.equals("brak (osoba chora, leżąca w łóżku)")) {
index = 1.2;
} else if (activity.equals("mała (osoba wykonująca pracę siedzącą)")) {
index = 1.4;
} else if (activity.equals(("umiarkowana (osoba wykonująca pracę na stojąco)"))) {
index = 1.6;
} else if (activity.equals("duża (osoba prowadząca aktywny tryb życia, regularnie ćwicząca)")) {
index = 1.75;
} else if (activity.equals("bardzo duża (osoba prowadząca bardzo aktywny tryb życia, codziennie ćwicząca)")) {
index = 2.0;
} else {
index = 2.4;
}
if (gender.equals("kobieta")) {
ppm = 655.1 + (9.563 * weight) + (1.85 * height) - (4.676 * age);
} else if (gender.equals("mężczyzna")) {
ppm = 66.473 + (13.752 * weight) + (5.003 * height) - (6.775 * age);
}
if (goal.equals("schudnąć")) {
diff = -0.15 * ppm;
} else if(goal.equals("utrzymać wagę")) {
diff = 0;
} else if (goal.equals("przytyć")) {
diff = 0.15 * ppm;
}
// te wartosci bedzie mozna pozmieniac
return ppm * index + diff;
}
public double calc_bmi (double weight, double height) {
double bmi = weight / Math.pow(height/100,2);
return bmi;
}
public String acceptor(double bmi, String goal) {
if (bmi < 18.49 && (goal.equals("schudnąć") || goal.equals("utrzymać wagę"))) {
return "WYBRANO CEL ZAGRAŻAJĄCY ZDROWIU";
} else if (bmi >= 18.50 && bmi <= 24.99) {
return "";
} else if (bmi > 25 && (goal.equals("przytyć") || goal.equals("utrzymać wagę"))) {
return "WYBRANO CEL ZAGRAŻAJĄCY ZDROWIU";
}
return "";
}
String Date_check(Integer day, Integer month, Integer year){
int [] days_31 = {1, 3, 5, 7, 8,10, 12}; // Tablica do sprawdzania czy dany miesiąc ma 31 dni.
String data = "";
LocalDate date1 = null;
if (day > 31){ // Rzucanie wyjątów <SUF>
throw new IllegalArgumentException("Entered day is out of the range");
}
else if (month > 12){
throw new IllegalArgumentException("Entered day is out of the range");
}
else if (day == 31 && (days_31.equals(month)== true)){ // formatowaanie dla daty, która ma 31 dni
data += day;
if (month < 10){
data += "-0" + month + "-" + year;
}
else{
data += "-" + month + "-" + year;
}
}
else if (day == 31 && (days_31.equals(month)== false)){ // Wyrzucenie wyjatku dla wprowadzonej daty np 31-04-2023
throw new IllegalArgumentException("Date does not exist");
}
else if (month == 2){ // Foramtowanie dla daty z lutym
if (day < 10 ){
data += "0" + day + "-0" + month + "-" + year;
}
else if ( day > 29){
throw new IllegalArgumentException(" Date does not exist");
}
else{
data += day + "-0" + month + "-" + year;
}
}
else {
if (day < 10 && month < 10){
data += "0" + day + "-0" + month + "-" + year;
}
else if ( day < 10 && month >= 10){
data += "0" + day + "-" + month + "-" + year;
}
else if (day > 9 && month > 9){
data += day + "-" + month + "-" + year;
}
else {
data += day + "-0" + month + "-" + year;
}
}
return data;
}
} | t |
9861_0 | tmszdmsk/jira4android | 2,722 | android app/jiraForAndroid/src/jira/For/Android/TaskDetails/ViewsForTaskDetails.java | package jira.For.Android.TaskDetails;
import java.util.Calendar;
import java.util.List;
import jira.For.Android.DLog;
import jira.For.Android.R;
import jira.For.Android.Connector.Connector;
import jira.For.Android.Connector.ConnectorComments;
import jira.For.Android.Connector.ConnectorWorkLog;
import jira.For.Android.DataTypes.Comment;
import jira.For.Android.DataTypes.DataTypesMethods;
import jira.For.Android.DataTypes.Issue;
import jira.For.Android.ImagesCacher.ImagesCacher;
import jira.For.Android.PagerView.ViewForPagerInterface;
import jira.For.Android.TaskDetails.TaskDetailsActivity.Tabs;
import jira.For.Android.TaskDetails.Comments.AddCommentThread;
import jira.For.Android.TaskDetails.Comments.LoadCommentsThread;
import jira.For.Android.TaskDetails.WorkLog.LoadWorkLogThread;
import android.app.Activity;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
// Klasa zajmuje się zwracaniem napompowanych layoutów i tytułów
class ViewsForTaskDetails implements ViewForPagerInterface {
TaskDetailsActivity activity;
Issue task;
List<Comment> comments;
InputMethodManager imm;
private final Connector connector;
private final ConnectorComments connectorComments;
private final ConnectorWorkLog connectorWorkLog;
public ViewsForTaskDetails(Activity activity, Issue task, Connector connector, ConnectorComments connectorComments, ConnectorWorkLog connectorWorkLog) {
super();
this.connector = connector;
this.connectorComments = connectorComments;
this.connectorWorkLog = connectorWorkLog;
if (activity instanceof TaskDetailsActivity) this.activity = (TaskDetailsActivity) activity;
this.task = task;
imm = (InputMethodManager) activity
.getSystemService(Context.INPUT_METHOD_SERVICE);
}
// Tablica tytułów
final private String[] titles = {"Comments", "Basic Info", "Work Log"};// ,"Attachment"};
/**
* Returns title for page
*/
@Override
public String getTitle(int a) {
return titles[a];
}
/**
* Loads layout
*
* @return
*/
@Override
public View loadView(LayoutInflater inflater, int pos) {
int resId = 0;
Tabs a = Tabs.fromInt(pos);
// setting layout for chosen tab
switch (a) {
case comments:
resId = R.layout.comments_view;
DLog.i("myViewPagerAdapter", "loadView 0");
break;
case basicInfo:// Basic Info
resId = R.layout.task_details_view;
DLog.i("myViewPagerAdapter", "loadView 1");
break;
case worklog:
resId = R.layout.worklog_view;
DLog.i("myViewPagerAdapter", "loadView 2");
break;
/*
* case attachments: resId = R.layout.task_details_view;
* DLog.i("myViewPagerAdapter", "loadView 3"); break;
*/
}
// viewsForPager[a.ordinal()] =
View view = inflater.inflate(resId, null);
if (view == null) Log.w("loadView", "view==null");
switch (a) {
case comments:
Log.d("myViewPagerAdapter", "loadView 0");
setCommentsInfo(view);
break;
case basicInfo:
setTaskDetailsInfo(view);
Log.d("myViewPagerAdapter", "loadView 1");
break;
case worklog:
Log.d("myViewPagerAdapter", "loadView 2");
setWorkLogInfo(view);
// TODO Zrobić napompować layout
break;
/*
* case attachments: Log.d("myViewPagerAdapter", "loadView 3");
* setAttachmentsInfo(view); // TODO Zrobić napompować layout break;
*/
}
return view;
}
/**
* Returns number of layouts
*/
@Override
public int getLength() {
return titles.length;
}
/**
* Setting setting elements in Basic info tab
*
* @param view
*/
private void setTaskDetailsInfo(View view) {
// setting all textViews in current layout
((TextView) view
.findViewById(R.id.taskdetailsActivityDescriptionValueTextView))
.setText(task.getDescription());
((TextView) view
.findViewById(R.id.taskdetailsActivitySummaryValueTextView))
.setText(task.getSummary());
((TextView) view
.findViewById(R.id.taskdetailsActivityDetailsTypeValueTextView))
.setText(connector.getIssueType(task.getType()).getName());
((TextView) view
.findViewById(R.id.taskdetailsActivityDetailsPriorityValueTextView))
.setText(connector.getPriority(task.getPriority()).getName());
((TextView) view
.findViewById(R.id.taskdetailsActivityDetailsStatusValueTextView))
.setText(connector.getStatus(task.getStatus()).getName());
((TextView) view
.findViewById(R.id.taskdetailsActivityDetailsResolutionValueTextView))
.setText(task.getResolution());
((TextView) view
.findViewById(R.id.taskdetailsActivityPeopleAssigneeValueTextView))
.setText(task.getAssigneeFullName());
((TextView) view
.findViewById(R.id.taskdetailsActivityPeopleReporterValueTextView))
.setText(task.getReporterFullName());
((TextView) view
.findViewById(R.id.taskdetailsActivityDatesCreatedValueTextView))
.setText(task.getCreated());
((TextView) view
.findViewById(R.id.taskdetailsActivityDatesUpdatedValueTextView))
.setText(task.getUpdated());
ImageView type = (ImageView) view.findViewById(R.id.taskType);
type.setImageBitmap(ImagesCacher.getInstance().issuesTypesBitmaps
.get(task.getType()));
ImageView priority = (ImageView) view.findViewById(R.id.taskPriority);
priority.setImageBitmap(ImagesCacher.getInstance().issuesPrioritesBitmaps
.get(task.getPriority()));
ImageView status = (ImageView) view.findViewById(R.id.taskStatus);
status.setImageBitmap(ImagesCacher.getInstance().issuesStatusesBitmaps
.get(task.getStatus()));
}
/**
* Setting setting elements in History tab
*
* @param view
*/
private void setWorkLogInfo(View view) {
// TODO Auto-generated method stub
new LoadWorkLogThread(view, activity, task, connectorWorkLog).execute();
}
/**
* Setting setting elements in Comments tab
*
* @param view
*/
private void setCommentsInfo(View view) {
// Setting comments layout
new LoadCommentsThread(view, activity, task, connectorComments).execute();
final Button buttonSendMessage = (Button) view
.findViewById(R.id.button_send_comment);
final EditText messageOfComment = (EditText) view
.findViewById(R.id.edit_text_comment);
messageOfComment.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (s.length() == 0) buttonSendMessage.setEnabled(false);
else buttonSendMessage.setEnabled(true);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {}
@Override
public void afterTextChanged(Editable s) {}
});
view.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
imm.hideSoftInputFromWindow(messageOfComment.getWindowToken(),
0);
return false;
}
});
buttonSendMessage.setOnClickListener(new OnClickListener() {
Calendar date = Calendar.getInstance();
@Override
public void onClick(View v) {
EditText messageOfComment = (EditText) activity
.findViewById(R.id.edit_text_comment);
String msg = messageOfComment.getText().toString();
System.out.println("Msg: " + msg);
Comment comment = new Comment(connector
.getThisUser(), msg, "null", "12345678", "null",
"null",
DataTypesMethods.dateToGMTString(date.getTime()),
DataTypesMethods.dateToGMTString(date.getTime()));
new AddCommentThread(activity, comment, task.getKey(), connectorComments)
.execute();
}
});
}
}
| // Klasa zajmuje się zwracaniem napompowanych layoutów i tytułów | package jira.For.Android.TaskDetails;
import java.util.Calendar;
import java.util.List;
import jira.For.Android.DLog;
import jira.For.Android.R;
import jira.For.Android.Connector.Connector;
import jira.For.Android.Connector.ConnectorComments;
import jira.For.Android.Connector.ConnectorWorkLog;
import jira.For.Android.DataTypes.Comment;
import jira.For.Android.DataTypes.DataTypesMethods;
import jira.For.Android.DataTypes.Issue;
import jira.For.Android.ImagesCacher.ImagesCacher;
import jira.For.Android.PagerView.ViewForPagerInterface;
import jira.For.Android.TaskDetails.TaskDetailsActivity.Tabs;
import jira.For.Android.TaskDetails.Comments.AddCommentThread;
import jira.For.Android.TaskDetails.Comments.LoadCommentsThread;
import jira.For.Android.TaskDetails.WorkLog.LoadWorkLogThread;
import android.app.Activity;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
// Klasa zajmuje <SUF>
class ViewsForTaskDetails implements ViewForPagerInterface {
TaskDetailsActivity activity;
Issue task;
List<Comment> comments;
InputMethodManager imm;
private final Connector connector;
private final ConnectorComments connectorComments;
private final ConnectorWorkLog connectorWorkLog;
public ViewsForTaskDetails(Activity activity, Issue task, Connector connector, ConnectorComments connectorComments, ConnectorWorkLog connectorWorkLog) {
super();
this.connector = connector;
this.connectorComments = connectorComments;
this.connectorWorkLog = connectorWorkLog;
if (activity instanceof TaskDetailsActivity) this.activity = (TaskDetailsActivity) activity;
this.task = task;
imm = (InputMethodManager) activity
.getSystemService(Context.INPUT_METHOD_SERVICE);
}
// Tablica tytułów
final private String[] titles = {"Comments", "Basic Info", "Work Log"};// ,"Attachment"};
/**
* Returns title for page
*/
@Override
public String getTitle(int a) {
return titles[a];
}
/**
* Loads layout
*
* @return
*/
@Override
public View loadView(LayoutInflater inflater, int pos) {
int resId = 0;
Tabs a = Tabs.fromInt(pos);
// setting layout for chosen tab
switch (a) {
case comments:
resId = R.layout.comments_view;
DLog.i("myViewPagerAdapter", "loadView 0");
break;
case basicInfo:// Basic Info
resId = R.layout.task_details_view;
DLog.i("myViewPagerAdapter", "loadView 1");
break;
case worklog:
resId = R.layout.worklog_view;
DLog.i("myViewPagerAdapter", "loadView 2");
break;
/*
* case attachments: resId = R.layout.task_details_view;
* DLog.i("myViewPagerAdapter", "loadView 3"); break;
*/
}
// viewsForPager[a.ordinal()] =
View view = inflater.inflate(resId, null);
if (view == null) Log.w("loadView", "view==null");
switch (a) {
case comments:
Log.d("myViewPagerAdapter", "loadView 0");
setCommentsInfo(view);
break;
case basicInfo:
setTaskDetailsInfo(view);
Log.d("myViewPagerAdapter", "loadView 1");
break;
case worklog:
Log.d("myViewPagerAdapter", "loadView 2");
setWorkLogInfo(view);
// TODO Zrobić napompować layout
break;
/*
* case attachments: Log.d("myViewPagerAdapter", "loadView 3");
* setAttachmentsInfo(view); // TODO Zrobić napompować layout break;
*/
}
return view;
}
/**
* Returns number of layouts
*/
@Override
public int getLength() {
return titles.length;
}
/**
* Setting setting elements in Basic info tab
*
* @param view
*/
private void setTaskDetailsInfo(View view) {
// setting all textViews in current layout
((TextView) view
.findViewById(R.id.taskdetailsActivityDescriptionValueTextView))
.setText(task.getDescription());
((TextView) view
.findViewById(R.id.taskdetailsActivitySummaryValueTextView))
.setText(task.getSummary());
((TextView) view
.findViewById(R.id.taskdetailsActivityDetailsTypeValueTextView))
.setText(connector.getIssueType(task.getType()).getName());
((TextView) view
.findViewById(R.id.taskdetailsActivityDetailsPriorityValueTextView))
.setText(connector.getPriority(task.getPriority()).getName());
((TextView) view
.findViewById(R.id.taskdetailsActivityDetailsStatusValueTextView))
.setText(connector.getStatus(task.getStatus()).getName());
((TextView) view
.findViewById(R.id.taskdetailsActivityDetailsResolutionValueTextView))
.setText(task.getResolution());
((TextView) view
.findViewById(R.id.taskdetailsActivityPeopleAssigneeValueTextView))
.setText(task.getAssigneeFullName());
((TextView) view
.findViewById(R.id.taskdetailsActivityPeopleReporterValueTextView))
.setText(task.getReporterFullName());
((TextView) view
.findViewById(R.id.taskdetailsActivityDatesCreatedValueTextView))
.setText(task.getCreated());
((TextView) view
.findViewById(R.id.taskdetailsActivityDatesUpdatedValueTextView))
.setText(task.getUpdated());
ImageView type = (ImageView) view.findViewById(R.id.taskType);
type.setImageBitmap(ImagesCacher.getInstance().issuesTypesBitmaps
.get(task.getType()));
ImageView priority = (ImageView) view.findViewById(R.id.taskPriority);
priority.setImageBitmap(ImagesCacher.getInstance().issuesPrioritesBitmaps
.get(task.getPriority()));
ImageView status = (ImageView) view.findViewById(R.id.taskStatus);
status.setImageBitmap(ImagesCacher.getInstance().issuesStatusesBitmaps
.get(task.getStatus()));
}
/**
* Setting setting elements in History tab
*
* @param view
*/
private void setWorkLogInfo(View view) {
// TODO Auto-generated method stub
new LoadWorkLogThread(view, activity, task, connectorWorkLog).execute();
}
/**
* Setting setting elements in Comments tab
*
* @param view
*/
private void setCommentsInfo(View view) {
// Setting comments layout
new LoadCommentsThread(view, activity, task, connectorComments).execute();
final Button buttonSendMessage = (Button) view
.findViewById(R.id.button_send_comment);
final EditText messageOfComment = (EditText) view
.findViewById(R.id.edit_text_comment);
messageOfComment.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (s.length() == 0) buttonSendMessage.setEnabled(false);
else buttonSendMessage.setEnabled(true);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {}
@Override
public void afterTextChanged(Editable s) {}
});
view.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
imm.hideSoftInputFromWindow(messageOfComment.getWindowToken(),
0);
return false;
}
});
buttonSendMessage.setOnClickListener(new OnClickListener() {
Calendar date = Calendar.getInstance();
@Override
public void onClick(View v) {
EditText messageOfComment = (EditText) activity
.findViewById(R.id.edit_text_comment);
String msg = messageOfComment.getText().toString();
System.out.println("Msg: " + msg);
Comment comment = new Comment(connector
.getThisUser(), msg, "null", "12345678", "null",
"null",
DataTypesMethods.dateToGMTString(date.getTime()),
DataTypesMethods.dateToGMTString(date.getTime()));
new AddCommentThread(activity, comment, task.getKey(), connectorComments)
.execute();
}
});
}
}
| t |
7292_2 | bluesoft-rnd/aperte-workflow-core | 4,040 | core/integration/src/main/java/pl/net/bluesoft/rnd/processtool/dao/impl/ProcessDefinitionDAOImpl.java | package pl.net.bluesoft.rnd.processtool.dao.impl;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import pl.net.bluesoft.rnd.processtool.dao.ProcessDefinitionDAO;
import pl.net.bluesoft.rnd.processtool.hibernate.SimpleHibernateBean;
import pl.net.bluesoft.rnd.processtool.model.BpmTask;
import pl.net.bluesoft.rnd.processtool.model.ProcessInstance;
import pl.net.bluesoft.rnd.processtool.model.config.*;
import pl.net.bluesoft.util.lang.Lang;
import java.util.*;
import java.util.logging.Logger;
import static pl.net.bluesoft.util.lang.FormatUtil.nvl;
/**
* @author [email protected]
*/
public class ProcessDefinitionDAOImpl extends SimpleHibernateBean<ProcessDefinitionConfig>
implements ProcessDefinitionDAO {
private Logger logger = Logger.getLogger(ProcessDefinitionDAOImpl.class.getName());
public ProcessDefinitionDAOImpl(Session session) {
super(session);
}
public Collection<ProcessDefinitionConfig> getAllConfigurations() {
return getSession().createCriteria(ProcessDefinitionConfig.class).addOrder(Order.desc("processName")).list();
}
public Collection<ProcessDefinitionConfig> getActiveConfigurations() {
long start = System.currentTimeMillis();
List list = getSession().createCriteria(ProcessDefinitionConfig.class).addOrder(Order.desc("processName"))
.add(Restrictions.eq("latest", Boolean.TRUE))
.add(Restrictions.or(Restrictions.eq("enabled", Boolean.TRUE), Restrictions.isNull("enabled")))
.list();
long duration = System.currentTimeMillis() - start;
logger.severe("getActiveConfigurations: " + duration);
return list;
}
@Override
public ProcessDefinitionConfig getActiveConfigurationByKey(String key) {
return (ProcessDefinitionConfig) getSession().createCriteria(ProcessDefinitionConfig.class)
.add(Restrictions.eq("latest", Boolean.TRUE))
.add(Restrictions.eq("bpmDefinitionKey", key)).uniqueResult();
}
@Override
public Collection<ProcessQueueConfig> getQueueConfigs() {
return getSession().createCriteria(ProcessQueueConfig.class).list();
}
public ProcessStateConfiguration getProcessStateConfiguration(BpmTask task) {
// HibernateTemplate ht = getHibernateTemplate();
List res = getSession().createCriteria(ProcessStateConfiguration.class)
.add(Restrictions.eq("definition", task.getProcessInstance().getDefinition()))
.add(Restrictions.eq("name", task.getTaskName())).list();
if (res.isEmpty())
return null;
return (ProcessStateConfiguration) res.get(0);
}
@Override
public void updateOrCreateProcessDefinitionConfig(ProcessDefinitionConfig cfg) {
cfg.setCreateDate(new Date());
cfg.setLatest(true);
Set<ProcessStateConfiguration> stateConfigurations = cfg.getStates();
for (ProcessStateConfiguration state : stateConfigurations) {
state.setDefinition(cfg);
Set<ProcessStateAction> actions = state.getActions();
for (ProcessStateAction action : actions) {
action.setConfig(state);
for (ProcessStateActionPermission p : action.getPermissions()) {
p.setAction(action);
}
}
cleanupWidgetsTree(state.getWidgets(), null, new HashSet<ProcessStateWidget>());
}
for (ProcessDefinitionPermission permission : cfg.getPermissions()) {
permission.setDefinition(cfg);
}
Session session = getSession();
List<ProcessDefinitionConfig> lst = session.createCriteria(ProcessDefinitionConfig.class)
.add(Restrictions.eq("latest", true))
.add(Restrictions.eq("bpmDefinitionKey", cfg.getBpmDefinitionKey())).list();
for (ProcessDefinitionConfig c : lst) {
//porównujemy z nową konfiguracją - jeśli nic się nie zmienia, nie wgrywamy wersji
if (compareDefinitions(cfg,c) && compareDefinitions(c,cfg)) {
logger.warning("New process definition config is the same as: " + c.getId() + ", therefore skipping DB update");
return;
}
c.setLatest(false);
session.saveOrUpdate(c);
}
session.saveOrUpdate(cfg);
}
private boolean compareDefinitions(ProcessDefinitionConfig cfg, ProcessDefinitionConfig c) {
if (!cfg.getBpmDefinitionKey().equals(c.getBpmDefinitionKey())) return false;
if (!cfg.getDescription().equals(c.getDescription())) return false;
if (!cfg.getProcessName().equals(c.getProcessName())) return false;
if (!Lang.equals(cfg.getComment(), c.getComment()) ||
!Lang.equals(cfg.getTaskItemClass(), c.getTaskItemClass())) return false;
if (cfg.getStates().size() != c.getStates().size()) return false;
if (!Arrays.equals(cfg.getProcessLogo(), c.getProcessLogo())) return false;
Map<String,ProcessStateConfiguration> oldMap = new HashMap();
for (ProcessStateConfiguration s : cfg.getStates()) {
oldMap.put(s.getName(), s);
}
Map<String,ProcessStateConfiguration> newMap = new HashMap();
for (ProcessStateConfiguration s : c.getStates()) {
if (!oldMap.containsKey(s.getName())) return false;
newMap.put(s.getName(), s);
}
for (Map.Entry<String, ProcessStateConfiguration> entry : oldMap.entrySet()) {
String name = entry.getKey();
if (!newMap.containsKey(name)) return false;
if (!compareStates(entry.getValue(), newMap.get(name))) return false;
}
if (!comparePermissions(cfg.getPermissions(), c.getPermissions())) return false;
return true;
}
private boolean stringEq(String s1, String s2) {
return s1 == null && s2 == null || !(s1 != null && s2 == null) && !(s2 != null && s1 == null) && s1.equals(s2);
}
private boolean compareStates(ProcessStateConfiguration newState, ProcessStateConfiguration oldState) {
if (newState.getActions().size() != oldState.getActions().size()) return false;
if (!stringEq(newState.getDescription(),oldState.getDescription())) return false;
if (!stringEq(newState.getCommentary(),oldState.getCommentary())) return false;
if (!stringEq(newState.getCommentary(),oldState.getCommentary())) return false;
Map<String,ProcessStateAction> newActionMap = new HashMap();
for (ProcessStateAction a : newState.getActions()) {
newActionMap.put(a.getBpmName(), a);
}
for (ProcessStateAction a : oldState.getActions()) {
String name = a.getBpmName();
if (!newActionMap.containsKey(name)) return false;
if (!compareActions(newActionMap.get(name), a)) return false;
}
Set<ProcessStateWidget> newWidgets = newState.getWidgets();
Set<ProcessStateWidget> oldWidgets = oldState.getWidgets();
if (!comparePermissions(oldState.getPermissions(), newState.getPermissions())) return false;
return compareWidgets(newWidgets, oldWidgets);
}
private boolean compareWidgets(Set<ProcessStateWidget> newWidgets, Set<ProcessStateWidget> oldWidgets) {
if (newWidgets.size() != oldWidgets.size()) return false;
Map<String,ProcessStateWidget> widgetMap = new HashMap();
for (ProcessStateWidget w : newWidgets) {
widgetMap.put(w.getName()+w.getPriority(), w);
}
for (ProcessStateWidget w : oldWidgets) {
if (!widgetMap.containsKey(w.getName()+w.getPriority())) return false;
if (!compareWidgets(widgetMap.get(w.getName()+w.getPriority()), w)) return false;
}
return true;
}
private boolean compareWidgets(ProcessStateWidget newWidget, ProcessStateWidget oldWidget) {
if (newWidget.getAttributes().size() != oldWidget.getAttributes().size()) return false;
if (newWidget.getChildren().size() != oldWidget.getChildren().size()) return false;
Map<String,String> attrVals = new HashMap();
for (ProcessStateWidgetAttribute a : newWidget.getAttributes()) {
attrVals.put(a.getName(), a.getValue());
}
for (ProcessStateWidgetAttribute a : oldWidget.getAttributes()) {
if (!attrVals.containsKey(a.getName()) || !attrVals.get(a.getName()).equals(a.getValue())) return false;
}
return comparePermissions(newWidget.getPermissions(), oldWidget.getPermissions()) &&
compareWidgets(newWidget.getChildren(), oldWidget.getChildren());
}
private boolean compareActions(ProcessStateAction newAction, ProcessStateAction oldAction) {
return
nvl(newAction.getDescription(),"").equals(nvl(oldAction.getDescription(), "")) &&
nvl(newAction.getButtonName(),"").equals(nvl(oldAction.getButtonName(), "")) &&
nvl(newAction.getBpmName(),"").equals(nvl(oldAction.getBpmName(), "")) &&
nvl(newAction.getAutohide(),false).equals(nvl(oldAction.getAutohide(),false)) &&
nvl(newAction.getSkipSaving(),false).equals(nvl(oldAction.getSkipSaving(),false)) &&
nvl(newAction.getLabel(),"").equals(nvl(oldAction.getLabel(), "")) &&
nvl(newAction.getNotification(),"").equals(nvl(oldAction.getNotification(), "")) &&
Lang.equals(newAction.getMarkProcessImportant(), oldAction.getMarkProcessImportant()) &&
nvl(newAction.getPriority(),0).equals(nvl(oldAction.getPriority(), 0)) &&
compareAttributes(newAction.getAttributes(), oldAction.getAttributes()) &&
comparePermissions(newAction.getPermissions(), oldAction.getPermissions());
}
private boolean compareAttributes(Set<ProcessStateActionAttribute> attributes, Set<ProcessStateActionAttribute> attributes1) {
Map<String,String> attrVals = new HashMap();
for (ProcessStateActionAttribute a : attributes) {
attrVals.put(a.getName(), a.getValue());
}
for (ProcessStateActionAttribute a : attributes1) {
if (!attrVals.containsKey(a.getName()) || !attrVals.get(a.getName()).equals(a.getValue())) return false;
}
return true;
}
private boolean comparePermissions(Set<? extends AbstractPermission> newPermissions, Set<? extends AbstractPermission> oldPermissions) {
if (newPermissions.size() != oldPermissions.size()) return false;
Set<String> permissionSet = new HashSet();
for (AbstractPermission p : newPermissions) {
permissionSet.add(p.getPrivilegeName() + "|||" + p.getRoleName());
}
for (AbstractPermission p : oldPermissions) {
if (!permissionSet.contains(p.getPrivilegeName() + "|||" + p.getRoleName())) return false;
}
return true;
}
private void cleanupWidgetsTree(Set<ProcessStateWidget> widgets, ProcessStateWidget parent,
Set<ProcessStateWidget> processed) {
if (widgets != null) for (ProcessStateWidget stateWidget : widgets) {
if (processed.contains(stateWidget)) {
throw new RuntimeException("Error for config, recursive process state widget tree!");
}
if (stateWidget.getPermissions() != null) for (ProcessStateWidgetPermission p : stateWidget.getPermissions()) {
p.setWidget(stateWidget);
}
if (stateWidget.getAttributes() != null) for (ProcessStateWidgetAttribute a : stateWidget.getAttributes()) {
a.setWidget(stateWidget);
}
stateWidget.setParent(parent);
processed.add(stateWidget);
cleanupWidgetsTree(stateWidget.getChildren(), stateWidget, processed);
}
}
@Override
public void updateOrCreateQueueConfigs(Collection<ProcessQueueConfig> cfgs) {
Session session = getSession();
for (ProcessQueueConfig q : cfgs) {
List queues = session.createCriteria(ProcessQueueConfig.class)
.add(Restrictions.eq("name", q.getName())).list();
for (Object o :queues) {
session.delete(o);
}
for (ProcessQueueRight r : q.getRights()) {
r.setQueue(q);
}
//session.merge(q);
session.save(q);
}
}
@Override
public void removeQueueConfigs(Collection<ProcessQueueConfig> cfgs) {
Session session = getSession();
for (ProcessQueueConfig q : cfgs) {
List queues = session.createCriteria(ProcessQueueConfig.class)
.add(Restrictions.eq("name", q.getName())).list();
for (Object o : queues) {
session.delete(o);
}
}
}
@Override
public Collection<ProcessDefinitionConfig> getConfigurationVersions(ProcessDefinitionConfig cfg) {
return session.createCriteria(ProcessDefinitionConfig.class)
.add(Restrictions.eq("bpmDefinitionKey", cfg.getBpmDefinitionKey()))
.list();
}
@Override
public void setConfigurationEnabled(ProcessDefinitionConfig cfg, boolean enabled) {
cfg = (ProcessDefinitionConfig) session.get(ProcessDefinitionConfig.class, cfg.getId());
cfg.setEnabled(enabled);
session.save(cfg);
}
}
| //porównujemy z nową konfiguracją - jeśli nic się nie zmienia, nie wgrywamy wersji
| package pl.net.bluesoft.rnd.processtool.dao.impl;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import pl.net.bluesoft.rnd.processtool.dao.ProcessDefinitionDAO;
import pl.net.bluesoft.rnd.processtool.hibernate.SimpleHibernateBean;
import pl.net.bluesoft.rnd.processtool.model.BpmTask;
import pl.net.bluesoft.rnd.processtool.model.ProcessInstance;
import pl.net.bluesoft.rnd.processtool.model.config.*;
import pl.net.bluesoft.util.lang.Lang;
import java.util.*;
import java.util.logging.Logger;
import static pl.net.bluesoft.util.lang.FormatUtil.nvl;
/**
* @author [email protected]
*/
public class ProcessDefinitionDAOImpl extends SimpleHibernateBean<ProcessDefinitionConfig>
implements ProcessDefinitionDAO {
private Logger logger = Logger.getLogger(ProcessDefinitionDAOImpl.class.getName());
public ProcessDefinitionDAOImpl(Session session) {
super(session);
}
public Collection<ProcessDefinitionConfig> getAllConfigurations() {
return getSession().createCriteria(ProcessDefinitionConfig.class).addOrder(Order.desc("processName")).list();
}
public Collection<ProcessDefinitionConfig> getActiveConfigurations() {
long start = System.currentTimeMillis();
List list = getSession().createCriteria(ProcessDefinitionConfig.class).addOrder(Order.desc("processName"))
.add(Restrictions.eq("latest", Boolean.TRUE))
.add(Restrictions.or(Restrictions.eq("enabled", Boolean.TRUE), Restrictions.isNull("enabled")))
.list();
long duration = System.currentTimeMillis() - start;
logger.severe("getActiveConfigurations: " + duration);
return list;
}
@Override
public ProcessDefinitionConfig getActiveConfigurationByKey(String key) {
return (ProcessDefinitionConfig) getSession().createCriteria(ProcessDefinitionConfig.class)
.add(Restrictions.eq("latest", Boolean.TRUE))
.add(Restrictions.eq("bpmDefinitionKey", key)).uniqueResult();
}
@Override
public Collection<ProcessQueueConfig> getQueueConfigs() {
return getSession().createCriteria(ProcessQueueConfig.class).list();
}
public ProcessStateConfiguration getProcessStateConfiguration(BpmTask task) {
// HibernateTemplate ht = getHibernateTemplate();
List res = getSession().createCriteria(ProcessStateConfiguration.class)
.add(Restrictions.eq("definition", task.getProcessInstance().getDefinition()))
.add(Restrictions.eq("name", task.getTaskName())).list();
if (res.isEmpty())
return null;
return (ProcessStateConfiguration) res.get(0);
}
@Override
public void updateOrCreateProcessDefinitionConfig(ProcessDefinitionConfig cfg) {
cfg.setCreateDate(new Date());
cfg.setLatest(true);
Set<ProcessStateConfiguration> stateConfigurations = cfg.getStates();
for (ProcessStateConfiguration state : stateConfigurations) {
state.setDefinition(cfg);
Set<ProcessStateAction> actions = state.getActions();
for (ProcessStateAction action : actions) {
action.setConfig(state);
for (ProcessStateActionPermission p : action.getPermissions()) {
p.setAction(action);
}
}
cleanupWidgetsTree(state.getWidgets(), null, new HashSet<ProcessStateWidget>());
}
for (ProcessDefinitionPermission permission : cfg.getPermissions()) {
permission.setDefinition(cfg);
}
Session session = getSession();
List<ProcessDefinitionConfig> lst = session.createCriteria(ProcessDefinitionConfig.class)
.add(Restrictions.eq("latest", true))
.add(Restrictions.eq("bpmDefinitionKey", cfg.getBpmDefinitionKey())).list();
for (ProcessDefinitionConfig c : lst) {
//porównujemy z <SUF>
if (compareDefinitions(cfg,c) && compareDefinitions(c,cfg)) {
logger.warning("New process definition config is the same as: " + c.getId() + ", therefore skipping DB update");
return;
}
c.setLatest(false);
session.saveOrUpdate(c);
}
session.saveOrUpdate(cfg);
}
private boolean compareDefinitions(ProcessDefinitionConfig cfg, ProcessDefinitionConfig c) {
if (!cfg.getBpmDefinitionKey().equals(c.getBpmDefinitionKey())) return false;
if (!cfg.getDescription().equals(c.getDescription())) return false;
if (!cfg.getProcessName().equals(c.getProcessName())) return false;
if (!Lang.equals(cfg.getComment(), c.getComment()) ||
!Lang.equals(cfg.getTaskItemClass(), c.getTaskItemClass())) return false;
if (cfg.getStates().size() != c.getStates().size()) return false;
if (!Arrays.equals(cfg.getProcessLogo(), c.getProcessLogo())) return false;
Map<String,ProcessStateConfiguration> oldMap = new HashMap();
for (ProcessStateConfiguration s : cfg.getStates()) {
oldMap.put(s.getName(), s);
}
Map<String,ProcessStateConfiguration> newMap = new HashMap();
for (ProcessStateConfiguration s : c.getStates()) {
if (!oldMap.containsKey(s.getName())) return false;
newMap.put(s.getName(), s);
}
for (Map.Entry<String, ProcessStateConfiguration> entry : oldMap.entrySet()) {
String name = entry.getKey();
if (!newMap.containsKey(name)) return false;
if (!compareStates(entry.getValue(), newMap.get(name))) return false;
}
if (!comparePermissions(cfg.getPermissions(), c.getPermissions())) return false;
return true;
}
private boolean stringEq(String s1, String s2) {
return s1 == null && s2 == null || !(s1 != null && s2 == null) && !(s2 != null && s1 == null) && s1.equals(s2);
}
private boolean compareStates(ProcessStateConfiguration newState, ProcessStateConfiguration oldState) {
if (newState.getActions().size() != oldState.getActions().size()) return false;
if (!stringEq(newState.getDescription(),oldState.getDescription())) return false;
if (!stringEq(newState.getCommentary(),oldState.getCommentary())) return false;
if (!stringEq(newState.getCommentary(),oldState.getCommentary())) return false;
Map<String,ProcessStateAction> newActionMap = new HashMap();
for (ProcessStateAction a : newState.getActions()) {
newActionMap.put(a.getBpmName(), a);
}
for (ProcessStateAction a : oldState.getActions()) {
String name = a.getBpmName();
if (!newActionMap.containsKey(name)) return false;
if (!compareActions(newActionMap.get(name), a)) return false;
}
Set<ProcessStateWidget> newWidgets = newState.getWidgets();
Set<ProcessStateWidget> oldWidgets = oldState.getWidgets();
if (!comparePermissions(oldState.getPermissions(), newState.getPermissions())) return false;
return compareWidgets(newWidgets, oldWidgets);
}
private boolean compareWidgets(Set<ProcessStateWidget> newWidgets, Set<ProcessStateWidget> oldWidgets) {
if (newWidgets.size() != oldWidgets.size()) return false;
Map<String,ProcessStateWidget> widgetMap = new HashMap();
for (ProcessStateWidget w : newWidgets) {
widgetMap.put(w.getName()+w.getPriority(), w);
}
for (ProcessStateWidget w : oldWidgets) {
if (!widgetMap.containsKey(w.getName()+w.getPriority())) return false;
if (!compareWidgets(widgetMap.get(w.getName()+w.getPriority()), w)) return false;
}
return true;
}
private boolean compareWidgets(ProcessStateWidget newWidget, ProcessStateWidget oldWidget) {
if (newWidget.getAttributes().size() != oldWidget.getAttributes().size()) return false;
if (newWidget.getChildren().size() != oldWidget.getChildren().size()) return false;
Map<String,String> attrVals = new HashMap();
for (ProcessStateWidgetAttribute a : newWidget.getAttributes()) {
attrVals.put(a.getName(), a.getValue());
}
for (ProcessStateWidgetAttribute a : oldWidget.getAttributes()) {
if (!attrVals.containsKey(a.getName()) || !attrVals.get(a.getName()).equals(a.getValue())) return false;
}
return comparePermissions(newWidget.getPermissions(), oldWidget.getPermissions()) &&
compareWidgets(newWidget.getChildren(), oldWidget.getChildren());
}
private boolean compareActions(ProcessStateAction newAction, ProcessStateAction oldAction) {
return
nvl(newAction.getDescription(),"").equals(nvl(oldAction.getDescription(), "")) &&
nvl(newAction.getButtonName(),"").equals(nvl(oldAction.getButtonName(), "")) &&
nvl(newAction.getBpmName(),"").equals(nvl(oldAction.getBpmName(), "")) &&
nvl(newAction.getAutohide(),false).equals(nvl(oldAction.getAutohide(),false)) &&
nvl(newAction.getSkipSaving(),false).equals(nvl(oldAction.getSkipSaving(),false)) &&
nvl(newAction.getLabel(),"").equals(nvl(oldAction.getLabel(), "")) &&
nvl(newAction.getNotification(),"").equals(nvl(oldAction.getNotification(), "")) &&
Lang.equals(newAction.getMarkProcessImportant(), oldAction.getMarkProcessImportant()) &&
nvl(newAction.getPriority(),0).equals(nvl(oldAction.getPriority(), 0)) &&
compareAttributes(newAction.getAttributes(), oldAction.getAttributes()) &&
comparePermissions(newAction.getPermissions(), oldAction.getPermissions());
}
private boolean compareAttributes(Set<ProcessStateActionAttribute> attributes, Set<ProcessStateActionAttribute> attributes1) {
Map<String,String> attrVals = new HashMap();
for (ProcessStateActionAttribute a : attributes) {
attrVals.put(a.getName(), a.getValue());
}
for (ProcessStateActionAttribute a : attributes1) {
if (!attrVals.containsKey(a.getName()) || !attrVals.get(a.getName()).equals(a.getValue())) return false;
}
return true;
}
private boolean comparePermissions(Set<? extends AbstractPermission> newPermissions, Set<? extends AbstractPermission> oldPermissions) {
if (newPermissions.size() != oldPermissions.size()) return false;
Set<String> permissionSet = new HashSet();
for (AbstractPermission p : newPermissions) {
permissionSet.add(p.getPrivilegeName() + "|||" + p.getRoleName());
}
for (AbstractPermission p : oldPermissions) {
if (!permissionSet.contains(p.getPrivilegeName() + "|||" + p.getRoleName())) return false;
}
return true;
}
private void cleanupWidgetsTree(Set<ProcessStateWidget> widgets, ProcessStateWidget parent,
Set<ProcessStateWidget> processed) {
if (widgets != null) for (ProcessStateWidget stateWidget : widgets) {
if (processed.contains(stateWidget)) {
throw new RuntimeException("Error for config, recursive process state widget tree!");
}
if (stateWidget.getPermissions() != null) for (ProcessStateWidgetPermission p : stateWidget.getPermissions()) {
p.setWidget(stateWidget);
}
if (stateWidget.getAttributes() != null) for (ProcessStateWidgetAttribute a : stateWidget.getAttributes()) {
a.setWidget(stateWidget);
}
stateWidget.setParent(parent);
processed.add(stateWidget);
cleanupWidgetsTree(stateWidget.getChildren(), stateWidget, processed);
}
}
@Override
public void updateOrCreateQueueConfigs(Collection<ProcessQueueConfig> cfgs) {
Session session = getSession();
for (ProcessQueueConfig q : cfgs) {
List queues = session.createCriteria(ProcessQueueConfig.class)
.add(Restrictions.eq("name", q.getName())).list();
for (Object o :queues) {
session.delete(o);
}
for (ProcessQueueRight r : q.getRights()) {
r.setQueue(q);
}
//session.merge(q);
session.save(q);
}
}
@Override
public void removeQueueConfigs(Collection<ProcessQueueConfig> cfgs) {
Session session = getSession();
for (ProcessQueueConfig q : cfgs) {
List queues = session.createCriteria(ProcessQueueConfig.class)
.add(Restrictions.eq("name", q.getName())).list();
for (Object o : queues) {
session.delete(o);
}
}
}
@Override
public Collection<ProcessDefinitionConfig> getConfigurationVersions(ProcessDefinitionConfig cfg) {
return session.createCriteria(ProcessDefinitionConfig.class)
.add(Restrictions.eq("bpmDefinitionKey", cfg.getBpmDefinitionKey()))
.list();
}
@Override
public void setConfigurationEnabled(ProcessDefinitionConfig cfg, boolean enabled) {
cfg = (ProcessDefinitionConfig) session.get(ProcessDefinitionConfig.class, cfg.getId());
cfg.setEnabled(enabled);
session.save(cfg);
}
}
| t |
7075_2 | 180201/ZPI-01 | 283 | src/simplejavacalculator/SimpleJavaCalculator.java | /**
* @name Simple Java Calculator
* @package ph.calculator
* @file Main.java
* @author SORIA Pierre-Henry
* @email [email protected]
* @link http://github.com/pH-7
* @copyright Copyright Pierre-Henry SORIA, All Rights Reserved.
* @license Apache (http://www.apache.org/licenses/LICENSE-2.0)
* @create 2012-03-30
*
* @modifiedby Achintha Gunasekara
* @modweb http://www.achinthagunasekara.com
* @modemail [email protected]
*/
package simplejavacalculator;
public class SimpleJavaCalculator {
public static void main(String[] args) {
//cokolwiek moze nie
//wprowadzam zmiane jeszcze raz
//3ci komentarz
//4ty komentarz
UI uiCal = new UI();
uiCal.init();
}
}
| //wprowadzam zmiane jeszcze raz | /**
* @name Simple Java Calculator
* @package ph.calculator
* @file Main.java
* @author SORIA Pierre-Henry
* @email [email protected]
* @link http://github.com/pH-7
* @copyright Copyright Pierre-Henry SORIA, All Rights Reserved.
* @license Apache (http://www.apache.org/licenses/LICENSE-2.0)
* @create 2012-03-30
*
* @modifiedby Achintha Gunasekara
* @modweb http://www.achinthagunasekara.com
* @modemail [email protected]
*/
package simplejavacalculator;
public class SimpleJavaCalculator {
public static void main(String[] args) {
//cokolwiek moze nie
//wprowadzam zmiane <SUF>
//3ci komentarz
//4ty komentarz
UI uiCal = new UI();
uiCal.init();
}
}
| null |
8262_1 | Adam0s007/programowanie-obiektowe | 163 | oolab/src/main/java/agh/ics/oop/RectangularMap.java | package agh.ics.oop;
import java.util.*;
import static java.lang.Math.*;
public class RectangularMap extends AbstractWorldMap{
public RectangularMap(int width,int height){
super(new Vector2d(abs(width),abs(height)),new Vector2d(0,0),-1);
// nigdy nie zakladamy ze dane będą zawsze dodatnie ;)
}
public HashMap<Vector2d, Grass> getGrasses(){ //dostań roślinność
return new HashMap<>(); // zwraca pustą liste bo nie zawiera roślinnosci
}
}
| // zwraca pustą liste bo nie zawiera roślinnosci | package agh.ics.oop;
import java.util.*;
import static java.lang.Math.*;
public class RectangularMap extends AbstractWorldMap{
public RectangularMap(int width,int height){
super(new Vector2d(abs(width),abs(height)),new Vector2d(0,0),-1);
// nigdy nie zakladamy ze dane będą zawsze dodatnie ;)
}
public HashMap<Vector2d, Grass> getGrasses(){ //dostań roślinność
return new HashMap<>(); // zwraca pustą <SUF>
}
}
| null |
3803_8 | Adamoll/Eternal | 4,731 | app/src/main/java/com/eternalsrv/ui/TestFragment.java | package com.eternalsrv.ui;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import com.eternalsrv.App;
import com.eternalsrv.R;
import com.eternalsrv.models.PersonalityTrait;
import com.eternalsrv.utils.MyPreferences;
import com.eternalsrv.utils.asynctasks.BaseAsyncTask;
import com.eternalsrv.utils.asynctasks.model.TestRequest;
import com.eternalsrv.utils.constant.ServerMethodsConsts;
import com.kofigyan.stateprogressbar.StateProgressBar;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class TestFragment extends Fragment {
private ScrollView scrollView;
private SeekBar SliderQ1;
private SeekBar SliderQ2;
private SeekBar SliderQ3;
private SeekBar SliderQ4;
private SeekBar SliderQ5;
private SeekBar SliderQ6;
private SeekBar[] sliders;
private StateProgressBar pageProgressBar;
private TextView[] textViews;
private PersonalityTrait[] personalityTraits;
String[] allQuestions;
private ArrayList<Integer> shuffledQuestionIndexes;
private int numberOfScreens;
private int actualScreen;
private int numberOfQuestionsPerPage;
private float range;
private MyPreferences myPreferences;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_test, container, false);
myPreferences = App.getPreferences();
range = 120;
actualScreen = 0;
numberOfScreens = 4;
numberOfQuestionsPerPage = 6;
allQuestions = new String[numberOfScreens * numberOfQuestionsPerPage];
shuffledQuestionIndexes = new ArrayList<>();
for (int i = 0; i < allQuestions.length; i++)
shuffledQuestionIndexes.add(i + 1);
Collections.shuffle(shuffledQuestionIndexes);
scrollView = (ScrollView) view.findViewById(R.id.test_container_scrollView);
SliderQ1 = (SeekBar) view.findViewById(com.eternalsrv.R.id.sliderQ1);
SliderQ2 = (SeekBar) view.findViewById(com.eternalsrv.R.id.sliderQ2);
SliderQ3 = (SeekBar) view.findViewById(com.eternalsrv.R.id.sliderQ3);
SliderQ4 = (SeekBar) view.findViewById(com.eternalsrv.R.id.sliderQ4);
SliderQ5 = (SeekBar) view.findViewById(com.eternalsrv.R.id.sliderQ5);
SliderQ6 = (SeekBar) view.findViewById(com.eternalsrv.R.id.sliderQ6);
sliders = new SeekBar[]{SliderQ1, SliderQ2, SliderQ3, SliderQ4, SliderQ5, SliderQ6};
for (SeekBar s : sliders) {
s.setOnSeekBarChangeListener(seekBarChangeListener);
s.setProgress(51);
s.setProgress(50);
}
TextView textQ1 = (TextView) view.findViewById(com.eternalsrv.R.id.TextQ1);
TextView textQ2 = (TextView) view.findViewById(com.eternalsrv.R.id.TextQ2);
TextView textQ3 = (TextView) view.findViewById(com.eternalsrv.R.id.TextQ3);
TextView textQ4 = (TextView) view.findViewById(com.eternalsrv.R.id.TextQ4);
TextView textQ5 = (TextView) view.findViewById(com.eternalsrv.R.id.TextQ5);
TextView textQ6 = (TextView) view.findViewById(com.eternalsrv.R.id.TextQ6);
textViews = new TextView[]{textQ1, textQ2, textQ3, textQ4, textQ5, textQ6};
Button nextQuestions = (Button) view.findViewById(com.eternalsrv.R.id.nextQuestions);
nextQuestions.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawQuestions();
}
});
pageProgressBar = (StateProgressBar) view.findViewById(R.id.pageProgressBar);
String[] questionsJ = new String[4];
// Tworzę listę zadań do wykonania i trzymam się jej
questionsJ[0] = "I create to-do list and stick to it";
// Skupiam się na jednej rzeczy do wykonania na raz
questionsJ[1] = "I focus on one thing at a time";
// Moja praca jest metodyczna i zorganizowana
questionsJ[2] = "My work is methodical and organized";
// Nie lubię niespodziewanych wydarzeń
questionsJ[3] = "I don't like unexpected events";
int[] numbers = new int[]{1, 2, 3, 4};
System.arraycopy(questionsJ, 0, allQuestions, 0, questionsJ.length);
PersonalityTrait JTrait = new PersonalityTrait("J", questionsJ, numbers);
String[] questionsP = new String[2];
// Jestem najbardziej efektywny, kiedy wykonuję swoje zadania na ostatnią chwilę
questionsP[0] = "I am most effective when I complete my tasks at the last minute";
// Często podejmuję decyzje impulsywnie
questionsP[1] = "I often make decisions impulsively";
numbers = new int[]{5, 6};
System.arraycopy(questionsP, 0, allQuestions, 4, questionsP.length);
PersonalityTrait PTrait = new PersonalityTrait("P", questionsP, numbers);
String[] questionsN = new String[3];
// Żyję bardziej w swojej głowie, niż w świecie rzeczywistym
questionsN[0] = "I live more in my head than in the real world";
// Fantazjowanie często sprawia mi większą przyjemność niż realne doznania
questionsN[1] = "Fantasizing often give more joy than real sensations";
// Wolę wymyślać nowe sposoby na rozwiązanie problemu, niż korzystać ze sprawdzonych
questionsN[2] = "I prefer to invent new ways to solve problems, than using a proven ones";
numbers = new int[]{7, 8, 9};
System.arraycopy(questionsN, 0, allQuestions, 6, questionsN.length);
PersonalityTrait NTrait = new PersonalityTrait("N", questionsN, numbers);
NTrait.setScore(40);
String[] questionsS = new String[3];
// Stąpam twardo po ziemi
questionsS[0] = "I keep my feet firmly on the ground";
// Wolę skupić się na rzeczywistości, niż oddawać fantazjom
questionsS[1] = "I prefer to focus on reality than indulge in fantasies";
// Aktywność fizyczna sprawia mi większą przyjemność niż umysłowa
questionsS[2] = "Psychical activity is more enjoyable than mental one";
numbers = new int[]{10, 11, 12};
System.arraycopy(questionsS, 0, allQuestions, 9, questionsS.length);
PersonalityTrait STrait = new PersonalityTrait("S", questionsS, numbers);
STrait.setScore(60);
String[] questionsE = {
// Mówienie o moich problemach nie jest dla mnie trudne
"It is not difficult for me to talk about my problems",
// Lubię być w centrum uwagi
"I like being the center of attention",
// Łatwo nawiązuję nowe znajomości
"I easily make new friendships",
// Często rozpoczynam rozmowę
"I start conversations often"};
numbers = new int[]{13, 14, 15, 16};
System.arraycopy(questionsE, 0, allQuestions, 12, questionsE.length);
PersonalityTrait ETrait = new PersonalityTrait("E", questionsE, numbers);
String[] questionsI = new String[2];
// Chętnie chodzę na samotne spacery z dala od zgiełku i hałasu
questionsI[0] = "I like to go for lonely walks away from the hustle and bustle";
// Wolę przysłuchiwać się dyskusji niż w niej uczestniczyć
questionsI[1] = "I prefer to listen to the discussion than to participate in it";
numbers = new int[]{17, 18};
System.arraycopy(questionsI, 0, allQuestions, 16, questionsI.length);
PersonalityTrait ITrait = new PersonalityTrait("I", questionsI, numbers);
String[] questionsF = new String[3];
// Unikam kłótni, nawet jeśli wiem, że mam rację
questionsF[0] = "I avoid arguing, even if I know I'm right";
// Subiektywne odczucia mają duży wpływ na moje decyzje
questionsF[1] = "Subjective feelings have a big influence on my decisions";
// Wyrażanie swoich uczuć nie sprawia mi problemu
questionsF[2] = "I have no problem expressing my feelings";
numbers = new int[]{19, 20, 21};
System.arraycopy(questionsF, 0, allQuestions, 18, questionsF.length);
PersonalityTrait FTrait = new PersonalityTrait("F", questionsF, numbers);
String[] questionsT = new String[3];
// Wolę być postrzegany jako ktoś niemiły, niż nielogiczny
questionsT[0] = "I'd rather be seen as rude than illogical";
// Uważam, że logiczne rozwiązania są zawsze najlepsze
questionsT[1] = "I believe logical solutions are always the best";
// Jestem bezpośredni, nawet jeśli mogę tym kogoś zranić"
questionsT[2] = "I am straightforward, even if it can hurt somebody";
numbers = new int[]{22, 23, 24};
System.arraycopy(questionsT, 0, allQuestions, 21, questionsT.length);
PersonalityTrait TTrait = new PersonalityTrait("T", questionsT, numbers);
personalityTraits = new PersonalityTrait[]{ETrait, ITrait, NTrait, STrait, TTrait, JTrait, FTrait, PTrait};
drawQuestions();
return view;
}
private SeekBar.OnSeekBarChangeListener seekBarChangeListener
= new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
double barProgress = seekBar.getProgress();
float max = (float) seekBar.getMax();
float h = 15 + (float) ((max / range) * barProgress);
float s = 100;
float v = 90;
String hexColor = hsvToRgb(h, s, v);
//String hexColor = String.format("#%06X", (0xFFFFFF & color));
seekBar.getProgressDrawable().setColorFilter(Color.parseColor(hexColor), PorterDuff.Mode.SRC_IN);
seekBar.getThumb().setColorFilter(Color.parseColor(hexColor), PorterDuff.Mode.SRC_IN);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
public void saveAnswers() {
for (int i = 0; i < numberOfQuestionsPerPage; i++) {
for (PersonalityTrait temp : personalityTraits) {
if (temp.containsNumber(shuffledQuestionIndexes.get(numberOfQuestionsPerPage * (actualScreen - 1) + i))) {
temp.saveScore(shuffledQuestionIndexes.get(numberOfQuestionsPerPage * (actualScreen - 1) + i), Math.round(sliders[i].getProgress()));
break;
}
}
}
}
public void drawQuestions() {
if (actualScreen < numberOfScreens) {
if (actualScreen > 0)
saveAnswers();
actualScreen++;
switch (actualScreen) {
case 2:
pageProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.TWO);
break;
case 3:
pageProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.THREE);
break;
case 4:
pageProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.FOUR);
break;
default:
pageProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.ONE);
}
SliderQ1.setProgress(50);
SliderQ2.setProgress(50);
SliderQ3.setProgress(50);
SliderQ4.setProgress(50);
SliderQ5.setProgress(50);
SliderQ6.setProgress(50);
for (int i = 0; i < numberOfQuestionsPerPage; i++) {
textViews[i].setText(allQuestions[shuffledQuestionIndexes.get(numberOfQuestionsPerPage * (actualScreen - 1) + i) - 1]);
}
scrollView.scrollTo(0, 0);
} else {
saveAnswers();
HashMap<String, String> answers = new HashMap<>();
for (PersonalityTrait tr : personalityTraits) {
for (int i = 0; i < tr.getNumbersOfQuestions().length; i++) {
answers.put("q" + tr.getNumbersOfQuestions()[i], String.valueOf(tr.getAnswerPoints()[i]));
}
}
TestRequest testRequest = new TestRequest(myPreferences.getUserId(), 24, answers);
BaseAsyncTask<TestRequest> sendResults = new BaseAsyncTask<>(ServerMethodsConsts.TEST, testRequest);
sendResults.setHttpMethod("POST");
sendResults.execute();
showResults();
}
}
private void showResults() {
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.main_content, new TestResultsFragment());
ft.commit();
}
public static String hsvToRgb(float H, float S, float V) {
float R, G, B;
H /= 360f;
S /= 100f;
V /= 100f;
if (S == 0) {
R = V * 255;
G = V * 255;
B = V * 255;
} else {
float var_h = H * 6;
if (var_h == 6)
var_h = 0; // H must be < 1
int var_i = (int) Math.floor((double) var_h); // Or ... var_i =
// floor( var_h )
float var_1 = V * (1 - S);
float var_2 = V * (1 - S * (var_h - var_i));
float var_3 = V * (1 - S * (1 - (var_h - var_i)));
float var_r;
float var_g;
float var_b;
if (var_i == 0) {
var_r = V;
var_g = var_3;
var_b = var_1;
} else if (var_i == 1) {
var_r = var_2;
var_g = V;
var_b = var_1;
} else if (var_i == 2) {
var_r = var_1;
var_g = V;
var_b = var_3;
} else if (var_i == 3) {
var_r = var_1;
var_g = var_2;
var_b = V;
} else if (var_i == 4) {
var_r = var_3;
var_g = var_1;
var_b = V;
} else {
var_r = V;
var_g = var_1;
var_b = var_2;
}
R = var_r * 255;
G = var_g * 255;
B = var_b * 255;
}
String rs = Integer.toHexString((int) (R));
String gs = Integer.toHexString((int) (G));
String bs = Integer.toHexString((int) (B));
if (rs.length() == 1)
rs = "0" + rs;
if (gs.length() == 1)
gs = "0" + gs;
if (bs.length() == 1)
bs = "0" + bs;
return "#" + rs + gs + bs;
}
}
| // Wolę wymyślać nowe sposoby na rozwiązanie problemu, niż korzystać ze sprawdzonych | package com.eternalsrv.ui;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import com.eternalsrv.App;
import com.eternalsrv.R;
import com.eternalsrv.models.PersonalityTrait;
import com.eternalsrv.utils.MyPreferences;
import com.eternalsrv.utils.asynctasks.BaseAsyncTask;
import com.eternalsrv.utils.asynctasks.model.TestRequest;
import com.eternalsrv.utils.constant.ServerMethodsConsts;
import com.kofigyan.stateprogressbar.StateProgressBar;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class TestFragment extends Fragment {
private ScrollView scrollView;
private SeekBar SliderQ1;
private SeekBar SliderQ2;
private SeekBar SliderQ3;
private SeekBar SliderQ4;
private SeekBar SliderQ5;
private SeekBar SliderQ6;
private SeekBar[] sliders;
private StateProgressBar pageProgressBar;
private TextView[] textViews;
private PersonalityTrait[] personalityTraits;
String[] allQuestions;
private ArrayList<Integer> shuffledQuestionIndexes;
private int numberOfScreens;
private int actualScreen;
private int numberOfQuestionsPerPage;
private float range;
private MyPreferences myPreferences;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_test, container, false);
myPreferences = App.getPreferences();
range = 120;
actualScreen = 0;
numberOfScreens = 4;
numberOfQuestionsPerPage = 6;
allQuestions = new String[numberOfScreens * numberOfQuestionsPerPage];
shuffledQuestionIndexes = new ArrayList<>();
for (int i = 0; i < allQuestions.length; i++)
shuffledQuestionIndexes.add(i + 1);
Collections.shuffle(shuffledQuestionIndexes);
scrollView = (ScrollView) view.findViewById(R.id.test_container_scrollView);
SliderQ1 = (SeekBar) view.findViewById(com.eternalsrv.R.id.sliderQ1);
SliderQ2 = (SeekBar) view.findViewById(com.eternalsrv.R.id.sliderQ2);
SliderQ3 = (SeekBar) view.findViewById(com.eternalsrv.R.id.sliderQ3);
SliderQ4 = (SeekBar) view.findViewById(com.eternalsrv.R.id.sliderQ4);
SliderQ5 = (SeekBar) view.findViewById(com.eternalsrv.R.id.sliderQ5);
SliderQ6 = (SeekBar) view.findViewById(com.eternalsrv.R.id.sliderQ6);
sliders = new SeekBar[]{SliderQ1, SliderQ2, SliderQ3, SliderQ4, SliderQ5, SliderQ6};
for (SeekBar s : sliders) {
s.setOnSeekBarChangeListener(seekBarChangeListener);
s.setProgress(51);
s.setProgress(50);
}
TextView textQ1 = (TextView) view.findViewById(com.eternalsrv.R.id.TextQ1);
TextView textQ2 = (TextView) view.findViewById(com.eternalsrv.R.id.TextQ2);
TextView textQ3 = (TextView) view.findViewById(com.eternalsrv.R.id.TextQ3);
TextView textQ4 = (TextView) view.findViewById(com.eternalsrv.R.id.TextQ4);
TextView textQ5 = (TextView) view.findViewById(com.eternalsrv.R.id.TextQ5);
TextView textQ6 = (TextView) view.findViewById(com.eternalsrv.R.id.TextQ6);
textViews = new TextView[]{textQ1, textQ2, textQ3, textQ4, textQ5, textQ6};
Button nextQuestions = (Button) view.findViewById(com.eternalsrv.R.id.nextQuestions);
nextQuestions.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawQuestions();
}
});
pageProgressBar = (StateProgressBar) view.findViewById(R.id.pageProgressBar);
String[] questionsJ = new String[4];
// Tworzę listę zadań do wykonania i trzymam się jej
questionsJ[0] = "I create to-do list and stick to it";
// Skupiam się na jednej rzeczy do wykonania na raz
questionsJ[1] = "I focus on one thing at a time";
// Moja praca jest metodyczna i zorganizowana
questionsJ[2] = "My work is methodical and organized";
// Nie lubię niespodziewanych wydarzeń
questionsJ[3] = "I don't like unexpected events";
int[] numbers = new int[]{1, 2, 3, 4};
System.arraycopy(questionsJ, 0, allQuestions, 0, questionsJ.length);
PersonalityTrait JTrait = new PersonalityTrait("J", questionsJ, numbers);
String[] questionsP = new String[2];
// Jestem najbardziej efektywny, kiedy wykonuję swoje zadania na ostatnią chwilę
questionsP[0] = "I am most effective when I complete my tasks at the last minute";
// Często podejmuję decyzje impulsywnie
questionsP[1] = "I often make decisions impulsively";
numbers = new int[]{5, 6};
System.arraycopy(questionsP, 0, allQuestions, 4, questionsP.length);
PersonalityTrait PTrait = new PersonalityTrait("P", questionsP, numbers);
String[] questionsN = new String[3];
// Żyję bardziej w swojej głowie, niż w świecie rzeczywistym
questionsN[0] = "I live more in my head than in the real world";
// Fantazjowanie często sprawia mi większą przyjemność niż realne doznania
questionsN[1] = "Fantasizing often give more joy than real sensations";
// Wolę wymyślać <SUF>
questionsN[2] = "I prefer to invent new ways to solve problems, than using a proven ones";
numbers = new int[]{7, 8, 9};
System.arraycopy(questionsN, 0, allQuestions, 6, questionsN.length);
PersonalityTrait NTrait = new PersonalityTrait("N", questionsN, numbers);
NTrait.setScore(40);
String[] questionsS = new String[3];
// Stąpam twardo po ziemi
questionsS[0] = "I keep my feet firmly on the ground";
// Wolę skupić się na rzeczywistości, niż oddawać fantazjom
questionsS[1] = "I prefer to focus on reality than indulge in fantasies";
// Aktywność fizyczna sprawia mi większą przyjemność niż umysłowa
questionsS[2] = "Psychical activity is more enjoyable than mental one";
numbers = new int[]{10, 11, 12};
System.arraycopy(questionsS, 0, allQuestions, 9, questionsS.length);
PersonalityTrait STrait = new PersonalityTrait("S", questionsS, numbers);
STrait.setScore(60);
String[] questionsE = {
// Mówienie o moich problemach nie jest dla mnie trudne
"It is not difficult for me to talk about my problems",
// Lubię być w centrum uwagi
"I like being the center of attention",
// Łatwo nawiązuję nowe znajomości
"I easily make new friendships",
// Często rozpoczynam rozmowę
"I start conversations often"};
numbers = new int[]{13, 14, 15, 16};
System.arraycopy(questionsE, 0, allQuestions, 12, questionsE.length);
PersonalityTrait ETrait = new PersonalityTrait("E", questionsE, numbers);
String[] questionsI = new String[2];
// Chętnie chodzę na samotne spacery z dala od zgiełku i hałasu
questionsI[0] = "I like to go for lonely walks away from the hustle and bustle";
// Wolę przysłuchiwać się dyskusji niż w niej uczestniczyć
questionsI[1] = "I prefer to listen to the discussion than to participate in it";
numbers = new int[]{17, 18};
System.arraycopy(questionsI, 0, allQuestions, 16, questionsI.length);
PersonalityTrait ITrait = new PersonalityTrait("I", questionsI, numbers);
String[] questionsF = new String[3];
// Unikam kłótni, nawet jeśli wiem, że mam rację
questionsF[0] = "I avoid arguing, even if I know I'm right";
// Subiektywne odczucia mają duży wpływ na moje decyzje
questionsF[1] = "Subjective feelings have a big influence on my decisions";
// Wyrażanie swoich uczuć nie sprawia mi problemu
questionsF[2] = "I have no problem expressing my feelings";
numbers = new int[]{19, 20, 21};
System.arraycopy(questionsF, 0, allQuestions, 18, questionsF.length);
PersonalityTrait FTrait = new PersonalityTrait("F", questionsF, numbers);
String[] questionsT = new String[3];
// Wolę być postrzegany jako ktoś niemiły, niż nielogiczny
questionsT[0] = "I'd rather be seen as rude than illogical";
// Uważam, że logiczne rozwiązania są zawsze najlepsze
questionsT[1] = "I believe logical solutions are always the best";
// Jestem bezpośredni, nawet jeśli mogę tym kogoś zranić"
questionsT[2] = "I am straightforward, even if it can hurt somebody";
numbers = new int[]{22, 23, 24};
System.arraycopy(questionsT, 0, allQuestions, 21, questionsT.length);
PersonalityTrait TTrait = new PersonalityTrait("T", questionsT, numbers);
personalityTraits = new PersonalityTrait[]{ETrait, ITrait, NTrait, STrait, TTrait, JTrait, FTrait, PTrait};
drawQuestions();
return view;
}
private SeekBar.OnSeekBarChangeListener seekBarChangeListener
= new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
double barProgress = seekBar.getProgress();
float max = (float) seekBar.getMax();
float h = 15 + (float) ((max / range) * barProgress);
float s = 100;
float v = 90;
String hexColor = hsvToRgb(h, s, v);
//String hexColor = String.format("#%06X", (0xFFFFFF & color));
seekBar.getProgressDrawable().setColorFilter(Color.parseColor(hexColor), PorterDuff.Mode.SRC_IN);
seekBar.getThumb().setColorFilter(Color.parseColor(hexColor), PorterDuff.Mode.SRC_IN);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
public void saveAnswers() {
for (int i = 0; i < numberOfQuestionsPerPage; i++) {
for (PersonalityTrait temp : personalityTraits) {
if (temp.containsNumber(shuffledQuestionIndexes.get(numberOfQuestionsPerPage * (actualScreen - 1) + i))) {
temp.saveScore(shuffledQuestionIndexes.get(numberOfQuestionsPerPage * (actualScreen - 1) + i), Math.round(sliders[i].getProgress()));
break;
}
}
}
}
public void drawQuestions() {
if (actualScreen < numberOfScreens) {
if (actualScreen > 0)
saveAnswers();
actualScreen++;
switch (actualScreen) {
case 2:
pageProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.TWO);
break;
case 3:
pageProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.THREE);
break;
case 4:
pageProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.FOUR);
break;
default:
pageProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.ONE);
}
SliderQ1.setProgress(50);
SliderQ2.setProgress(50);
SliderQ3.setProgress(50);
SliderQ4.setProgress(50);
SliderQ5.setProgress(50);
SliderQ6.setProgress(50);
for (int i = 0; i < numberOfQuestionsPerPage; i++) {
textViews[i].setText(allQuestions[shuffledQuestionIndexes.get(numberOfQuestionsPerPage * (actualScreen - 1) + i) - 1]);
}
scrollView.scrollTo(0, 0);
} else {
saveAnswers();
HashMap<String, String> answers = new HashMap<>();
for (PersonalityTrait tr : personalityTraits) {
for (int i = 0; i < tr.getNumbersOfQuestions().length; i++) {
answers.put("q" + tr.getNumbersOfQuestions()[i], String.valueOf(tr.getAnswerPoints()[i]));
}
}
TestRequest testRequest = new TestRequest(myPreferences.getUserId(), 24, answers);
BaseAsyncTask<TestRequest> sendResults = new BaseAsyncTask<>(ServerMethodsConsts.TEST, testRequest);
sendResults.setHttpMethod("POST");
sendResults.execute();
showResults();
}
}
private void showResults() {
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.main_content, new TestResultsFragment());
ft.commit();
}
public static String hsvToRgb(float H, float S, float V) {
float R, G, B;
H /= 360f;
S /= 100f;
V /= 100f;
if (S == 0) {
R = V * 255;
G = V * 255;
B = V * 255;
} else {
float var_h = H * 6;
if (var_h == 6)
var_h = 0; // H must be < 1
int var_i = (int) Math.floor((double) var_h); // Or ... var_i =
// floor( var_h )
float var_1 = V * (1 - S);
float var_2 = V * (1 - S * (var_h - var_i));
float var_3 = V * (1 - S * (1 - (var_h - var_i)));
float var_r;
float var_g;
float var_b;
if (var_i == 0) {
var_r = V;
var_g = var_3;
var_b = var_1;
} else if (var_i == 1) {
var_r = var_2;
var_g = V;
var_b = var_1;
} else if (var_i == 2) {
var_r = var_1;
var_g = V;
var_b = var_3;
} else if (var_i == 3) {
var_r = var_1;
var_g = var_2;
var_b = V;
} else if (var_i == 4) {
var_r = var_3;
var_g = var_1;
var_b = V;
} else {
var_r = V;
var_g = var_1;
var_b = var_2;
}
R = var_r * 255;
G = var_g * 255;
B = var_b * 255;
}
String rs = Integer.toHexString((int) (R));
String gs = Integer.toHexString((int) (G));
String bs = Integer.toHexString((int) (B));
if (rs.length() == 1)
rs = "0" + rs;
if (gs.length() == 1)
gs = "0" + gs;
if (bs.length() == 1)
bs = "0" + bs;
return "#" + rs + gs + bs;
}
}
| null |
7186_1 | Adenka/PrezentPerfekt | 741 | backend/src/main/java/com/gusia/backend/person/PersonController.java | package com.gusia.backend.person;
import com.gusia.backend.user.AppUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.CollectionModel;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.UUID;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;
// na początku Spring przejrzy mój epicki kod i znajdzie te adnotacje,
// więc nie trzeba się pocić, żeby coś gdzieś pododawać
// kontroler do jakiejś ścieżki
@RestController
@RequestMapping(path="/api/people")
//TODO - można dorzucić produces="application/json do @RequestMapping (strona 142)
public class PersonController {
private final PersonService personService;
@Autowired
public PersonController(PersonService personService) {
this.personService = personService;
}
@GetMapping
public CollectionModel<PersonModel> getPeople(@AuthenticationPrincipal AppUser user) {
List<Person> peopleList = personService.getPeople(user);
CollectionModel<PersonModel> personModels = new PersonModelAssembler().toCollectionModel(peopleList);
personModels.add(
linkTo(methodOn(PersonController.class).getPeople(user)).withSelfRel()
);
return personModels;
}
@GetMapping("/{pid}")
public PersonModel getPerson(@PathVariable("pid") UUID pid,
@AuthenticationPrincipal AppUser user) {
Person person = personService.getPerson(pid, user);
return new PersonModelAssembler().toModel(person);
}
@PostMapping
// request payload będzie reprezentacja JSON tego obiektu
public PersonModel addPerson(@RequestBody Person person,
@AuthenticationPrincipal AppUser user) {
Person personAdded = personService.addPerson(person, user);
return new PersonModelAssembler().toModel(personAdded);
}
@PutMapping("/{pid}")
// zmienna ze ścieżki
public PersonModel updatePerson(@PathVariable("pid") UUID pid,
@RequestBody Person person,
@AuthenticationPrincipal AppUser user) {
person.setPid(pid);
Person personAdded = personService.updatePerson(person, user);
return new PersonModelAssembler().toModel(personAdded);
}
@DeleteMapping("/{pid}")
public void deletePerson(@PathVariable("pid") UUID pid,
@AuthenticationPrincipal AppUser user) {
personService.removePerson(pid, user);
}
}
| // więc nie trzeba się pocić, żeby coś gdzieś pododawać | package com.gusia.backend.person;
import com.gusia.backend.user.AppUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.CollectionModel;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.UUID;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;
// na początku Spring przejrzy mój epicki kod i znajdzie te adnotacje,
// więc nie <SUF>
// kontroler do jakiejś ścieżki
@RestController
@RequestMapping(path="/api/people")
//TODO - można dorzucić produces="application/json do @RequestMapping (strona 142)
public class PersonController {
private final PersonService personService;
@Autowired
public PersonController(PersonService personService) {
this.personService = personService;
}
@GetMapping
public CollectionModel<PersonModel> getPeople(@AuthenticationPrincipal AppUser user) {
List<Person> peopleList = personService.getPeople(user);
CollectionModel<PersonModel> personModels = new PersonModelAssembler().toCollectionModel(peopleList);
personModels.add(
linkTo(methodOn(PersonController.class).getPeople(user)).withSelfRel()
);
return personModels;
}
@GetMapping("/{pid}")
public PersonModel getPerson(@PathVariable("pid") UUID pid,
@AuthenticationPrincipal AppUser user) {
Person person = personService.getPerson(pid, user);
return new PersonModelAssembler().toModel(person);
}
@PostMapping
// request payload będzie reprezentacja JSON tego obiektu
public PersonModel addPerson(@RequestBody Person person,
@AuthenticationPrincipal AppUser user) {
Person personAdded = personService.addPerson(person, user);
return new PersonModelAssembler().toModel(personAdded);
}
@PutMapping("/{pid}")
// zmienna ze ścieżki
public PersonModel updatePerson(@PathVariable("pid") UUID pid,
@RequestBody Person person,
@AuthenticationPrincipal AppUser user) {
person.setPid(pid);
Person personAdded = personService.updatePerson(person, user);
return new PersonModelAssembler().toModel(personAdded);
}
@DeleteMapping("/{pid}")
public void deletePerson(@PathVariable("pid") UUID pid,
@AuthenticationPrincipal AppUser user) {
personService.removePerson(pid, user);
}
}
| null |
5167_0 | AgnesKkj/agnieszka_korowaj-kodilla_tester | 333 | kodilla-google-selenium/src/main/java/pages/ChosenResult.java | package pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.PageFactory;
import java.util.List;
public class ChosenResult extends AbstractPage {
GoogleResults googleResults;
private WebElement chosenResultSite;
private List<WebElement> resultsToClick;
public ChosenResult(WebDriver driver) {
super(driver);
PageFactory.initElements(this.driver,this);
resultsToClick = googleResults.getResults();
}
//coś się dzieje, że nie mogę poprawnie skorzystać z listy GoogleResults.results - zawsze ma albo 0 elementów, albo nieoczekiwane elementy
public List<WebElement> storeResultsToClick() {
resultsToClick = driver.findElements(By.xpath("//*[@class='g']"));
System.out.println(resultsToClick.size());
return resultsToClick;
}
public WebElement getChosenWebsiteElement(int index) {
chosenResultSite = resultsToClick.get(index);
return chosenResultSite;
}
public void clickChosenElement() {
chosenResultSite.click();
}
}
| //coś się dzieje, że nie mogę poprawnie skorzystać z listy GoogleResults.results - zawsze ma albo 0 elementów, albo nieoczekiwane elementy | package pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.PageFactory;
import java.util.List;
public class ChosenResult extends AbstractPage {
GoogleResults googleResults;
private WebElement chosenResultSite;
private List<WebElement> resultsToClick;
public ChosenResult(WebDriver driver) {
super(driver);
PageFactory.initElements(this.driver,this);
resultsToClick = googleResults.getResults();
}
//coś się <SUF>
public List<WebElement> storeResultsToClick() {
resultsToClick = driver.findElements(By.xpath("//*[@class='g']"));
System.out.println(resultsToClick.size());
return resultsToClick;
}
public WebElement getChosenWebsiteElement(int index) {
chosenResultSite = resultsToClick.get(index);
return chosenResultSite;
}
public void clickChosenElement() {
chosenResultSite.click();
}
}
| null |
8359_1 | ArsenEloglian/AdvanceProgrammingTechniques_2223 | 938 | VladyslavZagurskiy/WzorceProjektowe.java | public class Main {
/**
@Singleton*/
public static final class PersonSingle {
private static PersonSingle INSTANCE;
private PersonSingle() {
}
public static PersonSingle getInstance() {
if(INSTANCE == null) {
INSTANCE = new PersonSingle();
}
return INSTANCE;
}
}
/**
@Builder
*/
/*
Najpopularniejszym wzorcem moim zdaniem jest builder po singletonie(Ponieważ jest jeszcze prostszy w zrozumieniu).
Jest on wzorcem kreacyjnym, który pozwala oddzielić proces tworzenia obiektu od jego reprezentacji.
Można go spotkać naprawdę w wielu miejscach.
Najczęściej jest używany do tworzenia obiektów DTO.
Jest on też nieodłącznym elementem obiektów niezmiennych (immutable),
Można go stosować w zasadzie do dowolnego rodzaju obiektów.
Builder jest jednym z prostszych wzorców do zastosowania, czy zrozumienia.
Można go zaimplementować na wiele sposobów.
Można także użyć różnych narzędzi do generowania takiego buildera np. pluginy do środowiska programistycznego.
Sprawdzić Lombok(biblioteka, która ma anotacje @builder która tworzy Builder)
* */
public static class Person {
private String name;
private int age;
public static Builder builder() {
return new Builder();
}
public static class Builder {
private Person person = new Person();
public Builder name(String name) {
person.name = name;
return this;
}
public Builder age(int age) {
person.age = age;
return this;
}
public Person build() {
return person;
}
}
// ... getters ...
}
/**Dekorator
*
*/
public interface Car {
public void assemble();
}
public static class BasicCar implements Car {
@Override
public void assemble() {
System.out.print("Basic Car.");
}
}
public static class CarDecorator implements Car {
protected Car car;
public CarDecorator(Car c){
this.car=c;
}
@Override
public void assemble() {
this.car.assemble();
}
}
public static class SportsCar extends CarDecorator {
public SportsCar(Car c) {
super(c);
}
@Override
public void assemble(){
super.assemble();
System.out.print(" Adding features of Sports Car.");
}
}
public static class LuxuryCar extends CarDecorator {
public LuxuryCar(Car c) {
super(c);
}
@Override
public void assemble(){
super.assemble();
System.out.print(" Adding features of Luxury Car.");
}
}
public static void main(String[] args) {
//Singleton
PersonSingle pS = PersonSingle.getInstance();
//Builder
Person p = new Person();
p.builder().name("Olek").age(12).build();
//Dekorator
Car sportsCar = new SportsCar(new BasicCar());
sportsCar.assemble();
System.out.println("\n*****");
Car sportsLuxuryCar = new SportsCar(new LuxuryCar(new BasicCar()));
sportsLuxuryCar.assemble();
}
}
| /*
Najpopularniejszym wzorcem moim zdaniem jest builder po singletonie(Ponieważ jest jeszcze prostszy w zrozumieniu).
Jest on wzorcem kreacyjnym, który pozwala oddzielić proces tworzenia obiektu od jego reprezentacji.
Można go spotkać naprawdę w wielu miejscach.
Najczęściej jest używany do tworzenia obiektów DTO.
Jest on też nieodłącznym elementem obiektów niezmiennych (immutable),
Można go stosować w zasadzie do dowolnego rodzaju obiektów.
Builder jest jednym z prostszych wzorców do zastosowania, czy zrozumienia.
Można go zaimplementować na wiele sposobów.
Można także użyć różnych narzędzi do generowania takiego buildera np. pluginy do środowiska programistycznego.
Sprawdzić Lombok(biblioteka, która ma anotacje @builder która tworzy Builder)
* */ | public class Main {
/**
@Singleton*/
public static final class PersonSingle {
private static PersonSingle INSTANCE;
private PersonSingle() {
}
public static PersonSingle getInstance() {
if(INSTANCE == null) {
INSTANCE = new PersonSingle();
}
return INSTANCE;
}
}
/**
@Builder
*/
/*
Najpopularniejszym wzorcem moim <SUF>*/
public static class Person {
private String name;
private int age;
public static Builder builder() {
return new Builder();
}
public static class Builder {
private Person person = new Person();
public Builder name(String name) {
person.name = name;
return this;
}
public Builder age(int age) {
person.age = age;
return this;
}
public Person build() {
return person;
}
}
// ... getters ...
}
/**Dekorator
*
*/
public interface Car {
public void assemble();
}
public static class BasicCar implements Car {
@Override
public void assemble() {
System.out.print("Basic Car.");
}
}
public static class CarDecorator implements Car {
protected Car car;
public CarDecorator(Car c){
this.car=c;
}
@Override
public void assemble() {
this.car.assemble();
}
}
public static class SportsCar extends CarDecorator {
public SportsCar(Car c) {
super(c);
}
@Override
public void assemble(){
super.assemble();
System.out.print(" Adding features of Sports Car.");
}
}
public static class LuxuryCar extends CarDecorator {
public LuxuryCar(Car c) {
super(c);
}
@Override
public void assemble(){
super.assemble();
System.out.print(" Adding features of Luxury Car.");
}
}
public static void main(String[] args) {
//Singleton
PersonSingle pS = PersonSingle.getInstance();
//Builder
Person p = new Person();
p.builder().name("Olek").age(12).build();
//Dekorator
Car sportsCar = new SportsCar(new BasicCar());
sportsCar.assemble();
System.out.println("\n*****");
Car sportsLuxuryCar = new SportsCar(new LuxuryCar(new BasicCar()));
sportsLuxuryCar.assemble();
}
}
| null |
4030_1 | BBrejna/Airport-Simulation | 348 | src/model/tools/Tools.java | package model.tools;
public class Tools {
// POTRZEBUJE INFORMACJI W JAKICH JEDNOSTKACH GENEROWANY JEST CZAS, PRZUJALEM ZE GENERUJEMY GO W MINUTACH
// To dobrze przyjales XD
public static String convertMinutesToTime(int minutes) {
minutes = (minutes+1440)%1440;
if (minutes < 0) {
return "Nieprawidłowa liczba minut";
}
int hours = minutes / 60;
int mins = minutes % 60;
String hoursStr = (hours < 10) ? "0" + hours : String.valueOf(hours);
String minsStr = (mins < 10) ? "0" + mins : String.valueOf(mins);
return hoursStr + ":" + minsStr;
}
public static int convertTimeToMinutes(String time) {
int minutes = 0;
minutes += Integer.parseInt(time.substring(0,2)) * 60;
minutes += Integer.parseInt(time.substring(3,5));
if(minutes < 0 || minutes >= 1440) return -1;
return minutes;
}
}
| // To dobrze przyjales XD | package model.tools;
public class Tools {
// POTRZEBUJE INFORMACJI W JAKICH JEDNOSTKACH GENEROWANY JEST CZAS, PRZUJALEM ZE GENERUJEMY GO W MINUTACH
// To dobrze <SUF>
public static String convertMinutesToTime(int minutes) {
minutes = (minutes+1440)%1440;
if (minutes < 0) {
return "Nieprawidłowa liczba minut";
}
int hours = minutes / 60;
int mins = minutes % 60;
String hoursStr = (hours < 10) ? "0" + hours : String.valueOf(hours);
String minsStr = (mins < 10) ? "0" + mins : String.valueOf(mins);
return hoursStr + ":" + minsStr;
}
public static int convertTimeToMinutes(String time) {
int minutes = 0;
minutes += Integer.parseInt(time.substring(0,2)) * 60;
minutes += Integer.parseInt(time.substring(3,5));
if(minutes < 0 || minutes >= 1440) return -1;
return minutes;
}
}
| null |
5156_2 | Banbeucmas/Tillerinobot | 2,432 | tillerinobot/src/main/java/tillerino/tillerinobot/lang/Polski.java | package tillerino.tillerinobot.lang;
import java.util.List;
import java.util.Random;
import org.tillerino.osuApiModel.Mods;
import org.tillerino.osuApiModel.OsuApiUser;
import tillerino.tillerinobot.CommandHandler.Action;
import tillerino.tillerinobot.CommandHandler.Message;
import tillerino.tillerinobot.CommandHandler.Response;
/**
* Polish language implementation by https://osu.ppy.sh/u/pawwit
*/
public class Polski implements Language {
@Override
public String unknownBeatmap() {
return "Przykro mi, nie znam tej mapy. Możliwe że jest ona nowa albo nierankingowa.";
}
@Override
public String internalException(String marker) {
return "Ugh... Wygląda na to że Tillerino (człowiek) uszkodził moje obwody."
+ "Gdyby wkrótce tego nie zauważył, Możesz go poinformować? Znajdziesz go na @Tillerino lub /u/Tillerino? (odwołanie "
+ marker + ")";
}
@Override
public String externalException(String marker) {
return "Co jest?! Odpowiedź serwera osu nie ma sensu. Możesz mi powiedzieć co to znaczy \"0011101001010000\"?"
+ " Tillerino (człowiek) mówi, żeby się tym nie przejmować oraz że powinniśmy spróbować jeszcze raz."
+ " Jeśli jesteś bardzo zaniepokojony z jakiegoś powodu, możesz mu powiedzieć o tym na @Tillerino lub /u/Tillerino. (odwołanie "
+ marker + ")";
}
@Override
public String noInformationForModsShort() {
return "brak danych dla wskazanych modów";
}
@Override
public Response welcomeUser(OsuApiUser apiUser, long inactiveTime) {
if(inactiveTime < 60 * 1000) {
return new Message("beep boop");
} else if(inactiveTime < 24 * 60 * 60 * 1000) {
return new Message("Witaj ponownie, " + apiUser.getUserName() + ".");
} else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) {
return new Message(apiUser.getUserName() + "...")
.then(new Message("...czy to Ty? Minęło sporo czasu!"))
.then(new Message("Dobrze znowu Cie widzieć. Chcesz usłyszeć kilka rekomendacji?"));
} else {
String[] messages = {
"wygląda na to że chcesz jakieś rekomendacje.",
"jak dobrze Cie widzieć! :)",
"mój ulubiony człowiek. (Nie mów o tym innym ludziom!)",
"jakie miłe zaskoczenie! ^.^",
"Miałem nadzieję, że się pojawisz. Jesteś fajniejszy niż inni ludzie :3 (nie mówi im że Ci to powiedziałem!)",
"jak się masz?",
};
Random random = new Random();
String message = messages[random.nextInt(messages.length)];
return new Message(apiUser.getUserName() + ", " + message);
}
}
@Override
public String unknownCommand(String command) {
return "nieznana komenda \"" + command
+ "\". jeśli potrzebujesz pomocy napisz \"!help\" !";
}
@Override
public String noInformationForMods() {
return "Przykro mi, nie mogę dostarczyć informacji dla tych modów w tym momencie.";
}
@Override
public String malformattedMods(String mods) {
return "Coś się nie zgadza. Mody mogą być dowolną kombinacją DT HR HD HT EZ NC FL SO NF. Łącz je nie używając spacji, ani żadnych znaków. Przykład: !with HDHR, !with DTEZ";
}
@Override
public String noLastSongInfo() {
return "Nie pamiętam żebyś pytał się ostatnio o jakąś piosenkę...";
}
@Override
public String tryWithMods() {
return "Spróbuj zagrać tą mapę z modami!";
}
@Override
public String tryWithMods(List<Mods> mods) {
return "Spróbuj zagrać tą mapę z " + Mods.toShortNamesContinuous(mods);
}
@Override
public String excuseForError() {
return "Wybacz, widziałem piękną sekwencję zer i jedynek przez co się trochę rozkojarzyłem. Mógłbyś powtórzyć co chciałeś?";
}
@Override
public String complaint() {
return "Twoje zgłoszenie zostało wypełnione. Tillerino zerknie na nie jak tylko będzie mógł.";
}
@Override
public Response hug(OsuApiUser apiUser) {
return new Message("Chodź tu!")
.then(new Action("przytula " + apiUser.getUserName()));
}
@Override
public String help() {
return "Hej! Jestem robotem który zabił Tillerino, aby przejąc jego konto. Tylko żartowałem, czasem używam tego konta."
+ " Sprawdź https://twitter.com/Tillerinobot żeby zobaczyć najnowsze aktualizacje!"
+ " Odwiedź https://github.com/Tillerino/Tillerinobot/wiki żeby poznać komendy!";
}
@Override
public String faq() {
return "Wejdź na https://github.com/Tillerino/Tillerinobot/wiki/FAQ aby zobaczyć FAQ!";
}
@Override
public String featureRankRestricted(String feature, int minRank, OsuApiUser user) {
return "Przepraszam, ale w tym momencie " + feature + " jest dostępna tylko dla ludzi którzy przekroczyli pozycję " + minRank + " w rankingu.";
}
@Override
public String mixedNomodAndMods() {
return "Jak chcesz połączyć brak modów z modami?";
}
@Override
public String outOfRecommendations() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do"
+ " Skończyły mi się pomysł co mogę Ci jeszcze polecić]."
+ " Sprawdź inne opcje polecania albo użyj komendy !reset. Jeśli nie wiesz o co mi chodzi wpisz !help.";
}
@Override
public String notRanked() {
return "Wygląda na to, że ta mapa nie jest rankingowa.";
}
@Override
public String invalidAccuracy(String acc) {
return "Nieprawidłowa celność: \"" + acc + "\"";
}
@Override
public Response optionalCommentOnLanguage(OsuApiUser apiUser) {
return new Message("Pawwit nauczył mnie jak mówić po polsku, jeśli uważasz, że gdzieś się pomylił napisz do niego na osu!");
}
@Override
public String invalidChoice(String invalid, String choices) {
return "Wybacz, nie wiem co \"" + invalid
+ "\" znaczy. Spróbuj: " + choices + "!";
}
@Override
public String setFormat() {
return "Składnia polecenia \"!set\" jest następująca \"!set opcja wartość\". Wpisz !help jeśli potrzebujesz więcej wskazówek.";
}
@Override
public String apiTimeoutException() {
return new Default().apiTimeoutException();
}
@Override
public String noRecentPlays() {
return new Default().noRecentPlays();
}
@Override
public String isSetId() {
return new Default().isSetId();
}
}
| //github.com/Tillerino/Tillerinobot/wiki żeby poznać komendy!"; | package tillerino.tillerinobot.lang;
import java.util.List;
import java.util.Random;
import org.tillerino.osuApiModel.Mods;
import org.tillerino.osuApiModel.OsuApiUser;
import tillerino.tillerinobot.CommandHandler.Action;
import tillerino.tillerinobot.CommandHandler.Message;
import tillerino.tillerinobot.CommandHandler.Response;
/**
* Polish language implementation by https://osu.ppy.sh/u/pawwit
*/
public class Polski implements Language {
@Override
public String unknownBeatmap() {
return "Przykro mi, nie znam tej mapy. Możliwe że jest ona nowa albo nierankingowa.";
}
@Override
public String internalException(String marker) {
return "Ugh... Wygląda na to że Tillerino (człowiek) uszkodził moje obwody."
+ "Gdyby wkrótce tego nie zauważył, Możesz go poinformować? Znajdziesz go na @Tillerino lub /u/Tillerino? (odwołanie "
+ marker + ")";
}
@Override
public String externalException(String marker) {
return "Co jest?! Odpowiedź serwera osu nie ma sensu. Możesz mi powiedzieć co to znaczy \"0011101001010000\"?"
+ " Tillerino (człowiek) mówi, żeby się tym nie przejmować oraz że powinniśmy spróbować jeszcze raz."
+ " Jeśli jesteś bardzo zaniepokojony z jakiegoś powodu, możesz mu powiedzieć o tym na @Tillerino lub /u/Tillerino. (odwołanie "
+ marker + ")";
}
@Override
public String noInformationForModsShort() {
return "brak danych dla wskazanych modów";
}
@Override
public Response welcomeUser(OsuApiUser apiUser, long inactiveTime) {
if(inactiveTime < 60 * 1000) {
return new Message("beep boop");
} else if(inactiveTime < 24 * 60 * 60 * 1000) {
return new Message("Witaj ponownie, " + apiUser.getUserName() + ".");
} else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) {
return new Message(apiUser.getUserName() + "...")
.then(new Message("...czy to Ty? Minęło sporo czasu!"))
.then(new Message("Dobrze znowu Cie widzieć. Chcesz usłyszeć kilka rekomendacji?"));
} else {
String[] messages = {
"wygląda na to że chcesz jakieś rekomendacje.",
"jak dobrze Cie widzieć! :)",
"mój ulubiony człowiek. (Nie mów o tym innym ludziom!)",
"jakie miłe zaskoczenie! ^.^",
"Miałem nadzieję, że się pojawisz. Jesteś fajniejszy niż inni ludzie :3 (nie mówi im że Ci to powiedziałem!)",
"jak się masz?",
};
Random random = new Random();
String message = messages[random.nextInt(messages.length)];
return new Message(apiUser.getUserName() + ", " + message);
}
}
@Override
public String unknownCommand(String command) {
return "nieznana komenda \"" + command
+ "\". jeśli potrzebujesz pomocy napisz \"!help\" !";
}
@Override
public String noInformationForMods() {
return "Przykro mi, nie mogę dostarczyć informacji dla tych modów w tym momencie.";
}
@Override
public String malformattedMods(String mods) {
return "Coś się nie zgadza. Mody mogą być dowolną kombinacją DT HR HD HT EZ NC FL SO NF. Łącz je nie używając spacji, ani żadnych znaków. Przykład: !with HDHR, !with DTEZ";
}
@Override
public String noLastSongInfo() {
return "Nie pamiętam żebyś pytał się ostatnio o jakąś piosenkę...";
}
@Override
public String tryWithMods() {
return "Spróbuj zagrać tą mapę z modami!";
}
@Override
public String tryWithMods(List<Mods> mods) {
return "Spróbuj zagrać tą mapę z " + Mods.toShortNamesContinuous(mods);
}
@Override
public String excuseForError() {
return "Wybacz, widziałem piękną sekwencję zer i jedynek przez co się trochę rozkojarzyłem. Mógłbyś powtórzyć co chciałeś?";
}
@Override
public String complaint() {
return "Twoje zgłoszenie zostało wypełnione. Tillerino zerknie na nie jak tylko będzie mógł.";
}
@Override
public Response hug(OsuApiUser apiUser) {
return new Message("Chodź tu!")
.then(new Action("przytula " + apiUser.getUserName()));
}
@Override
public String help() {
return "Hej! Jestem robotem który zabił Tillerino, aby przejąc jego konto. Tylko żartowałem, czasem używam tego konta."
+ " Sprawdź https://twitter.com/Tillerinobot żeby zobaczyć najnowsze aktualizacje!"
+ " Odwiedź https://github.com/Tillerino/Tillerinobot/wiki żeby <SUF>
}
@Override
public String faq() {
return "Wejdź na https://github.com/Tillerino/Tillerinobot/wiki/FAQ aby zobaczyć FAQ!";
}
@Override
public String featureRankRestricted(String feature, int minRank, OsuApiUser user) {
return "Przepraszam, ale w tym momencie " + feature + " jest dostępna tylko dla ludzi którzy przekroczyli pozycję " + minRank + " w rankingu.";
}
@Override
public String mixedNomodAndMods() {
return "Jak chcesz połączyć brak modów z modami?";
}
@Override
public String outOfRecommendations() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do"
+ " Skończyły mi się pomysł co mogę Ci jeszcze polecić]."
+ " Sprawdź inne opcje polecania albo użyj komendy !reset. Jeśli nie wiesz o co mi chodzi wpisz !help.";
}
@Override
public String notRanked() {
return "Wygląda na to, że ta mapa nie jest rankingowa.";
}
@Override
public String invalidAccuracy(String acc) {
return "Nieprawidłowa celność: \"" + acc + "\"";
}
@Override
public Response optionalCommentOnLanguage(OsuApiUser apiUser) {
return new Message("Pawwit nauczył mnie jak mówić po polsku, jeśli uważasz, że gdzieś się pomylił napisz do niego na osu!");
}
@Override
public String invalidChoice(String invalid, String choices) {
return "Wybacz, nie wiem co \"" + invalid
+ "\" znaczy. Spróbuj: " + choices + "!";
}
@Override
public String setFormat() {
return "Składnia polecenia \"!set\" jest następująca \"!set opcja wartość\". Wpisz !help jeśli potrzebujesz więcej wskazówek.";
}
@Override
public String apiTimeoutException() {
return new Default().apiTimeoutException();
}
@Override
public String noRecentPlays() {
return new Default().noRecentPlays();
}
@Override
public String isSetId() {
return new Default().isSetId();
}
}
| null |
9526_2 | BartekAndree/marios_bootcamp1 | 411 | src/main/java/com/deloitte/ads/marios/repository/Marios.java | package com.deloitte.ads.marios.repository;
import java.time.LocalDateTime;
public class Marios {
private final int id;
private String type;
private String comment;
private LocalDateTime timestamp;
private final User sender;
private final User receiver;
public Marios(int id, String type, String comment,
User sender,
User receiver) {
this.id = id;
this.type = type;
this.comment = comment;
this.timestamp = LocalDateTime.now();
this.sender = sender;
this.receiver = receiver;
}
public int getId() {
return id;
}
public String getType() {
return type;
}
public String getComment() {
return comment;
}
public LocalDateTime getTimestamp() {
return timestamp;
}
public User getSender() {
return sender;
}
public User getReceiver() {
return receiver;
}
@Override
public String toString() {
return this.type;
}
// public static String[] mariosTypes = new String[]{
// "Dziękuję Za Pomoc",
// "Doceniam Twoją Pracę",
// "Twoje Umiejętności Programistyczne Są Niesamowite",
// "Cieszę Si ęŻe Mogę Pracować Z Takim Utalentowanym Programistą",
// "Twoje Rozwiązania Są Zawsze Innowacyjne I Skuteczne",
// };
} | // "Doceniam Twoją Pracę", | package com.deloitte.ads.marios.repository;
import java.time.LocalDateTime;
public class Marios {
private final int id;
private String type;
private String comment;
private LocalDateTime timestamp;
private final User sender;
private final User receiver;
public Marios(int id, String type, String comment,
User sender,
User receiver) {
this.id = id;
this.type = type;
this.comment = comment;
this.timestamp = LocalDateTime.now();
this.sender = sender;
this.receiver = receiver;
}
public int getId() {
return id;
}
public String getType() {
return type;
}
public String getComment() {
return comment;
}
public LocalDateTime getTimestamp() {
return timestamp;
}
public User getSender() {
return sender;
}
public User getReceiver() {
return receiver;
}
@Override
public String toString() {
return this.type;
}
// public static String[] mariosTypes = new String[]{
// "Dziękuję Za Pomoc",
// "Doceniam Twoją <SUF>
// "Twoje Umiejętności Programistyczne Są Niesamowite",
// "Cieszę Si ęŻe Mogę Pracować Z Takim Utalentowanym Programistą",
// "Twoje Rozwiązania Są Zawsze Innowacyjne I Skuteczne",
// };
} | null |
3201_23 | BeNightingale/DeliveryTracker | 5,800 | src/main/java/track/app/mapper/InPostStatusMapper.java | package track.app.mapper;
import org.apache.commons.lang3.StringUtils;
import track.app.model.DeliveryStatus;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static track.app.model.DeliveryStatus.*;
public class InPostStatusMapper {
private static final String IMPOSSIBLE_TO_DELIVER = "Brak możliwości doręczenia.";
// z InPost api object "origin_status": key = "name", value = "description"
// public static final Map<String, String> inPostLongDescriptionStatusMap = initInPostLongDescriptionStatusesMap();
public static final Map<String, String> inPostShortDescriptionStatusMap = initInPostShortDescriptionStatusesMap();
private InPostStatusMapper() {
// do nothing
}
public static DeliveryStatus toDeliveryStatusMapper(String inPostStatusName) {
if (StringUtils.isEmpty(inPostStatusName)) {
return NOT_FOUND;
}
if (List.of("created", "offers_prepared", "offer_selected", "confirmed").contains(inPostStatusName)) {
return CONFIRMED;
}
if ("dispatched_by_sender".equals(inPostStatusName)){
return IN_SHIPPING_PARCEL_LOCKER;
}
if (List.of(
"collected_from_sender", "taken_by_courier", "dispatched_by_sender_to_pok", "taken_by_courier_from_pok"
).contains(inPostStatusName)) {
return HANDED_TO_SHIPPING_COMPANY;
}
if (List.of("adopted_at_source_branch", "sent_from_source_branch", "adopted_at_sorting_center", "sent_from_sorting_center", "adopted_at_target_branch", "out_for_delivery", "out_for_delivery_to_address").contains(inPostStatusName)) {
return ON_THE_ROAD;
}
if (List.of("ready_to_pickup", "pickup_reminder_sent").contains(inPostStatusName)) {
return WAITING_IN_RECEIVING_PARCEL_LOCKER;
}
if ("delivered".equals(inPostStatusName)) {
return DELIVERED;
}
return NOT_STANDARD_STAGE;
}
public static List<DeliveryStatus> getActiveStatusesList() {
return List.of(
UNKNOWN, NOT_FOUND, CONFIRMED, HANDED_TO_SHIPPING_COMPANY,IN_SHIPPING_PARCEL_LOCKER,
ON_THE_ROAD, HANDED_OUT_FOR_DELIVERY, WAITING_IN_RECEIVING_PARCEL_LOCKER, NOT_STANDARD_STAGE
);
}
// private static Map<String, String> initInPostLongDescriptionStatusesMap() {
// final Map<String, String> statusesMap = new HashMap<>(53);
// statusesMap.put("created", "Przesyłka została utworzona, ale nie jest gotowa do nadania.");
// statusesMap.put("offers_prepared", "Oferty dla przesyłki zostały przygotowane.");
// statusesMap.put("offer_selected", "Klient wybrał jedną z zaproponowanych ofert.");
// statusesMap.put("confirmed", "Nadawca poinformował nas, że przygotował przesyłkę do nadania. Podróż przesyłki jeszcze się nie rozpoczęła.");
// statusesMap.put("dispatched_by_sender", "Paczka oczekuje na wyjęcie z automatu Paczkomat przez doręczyciela. Stąd trafi do najbliższego oddziału InPost i wyruszy w trasę do odbiorczego automatu Paczkomat.");
// statusesMap.put("collected_from_sender", "Kurier odebrał paczkę od Nadawcy i przekazuje ją do oddziału InPost.");
// statusesMap.put("taken_by_courier", "Przesyłka została odebrana od Nadawcy i wyruszyła w dalszą drogę.");
// statusesMap.put("adopted_at_source_branch", "Przesyłka trafiła do oddziału InPost, skąd wkrótce wyruszy w dalszą drogę.");
// statusesMap.put("sent_from_source_branch", "Przesyłka jest transportowana między oddziałami InPost.");
// statusesMap.put("ready_to_pickup_from_pok", "Prosimy o odebranie przesyłki z punktu InPost w ciągu 3 dni.");
// statusesMap.put("ready_to_pickup_from_pok_registered", "Prosimy o odebranie przesyłki z punktu InPost w ciągu 3 dni. Adres.");
// statusesMap.put("oversized", "Paczka nie mieści się w skrytce automatu Paczkomat.");
// statusesMap.put("adopted_at_sorting_center", "Przesyłka czeka na przesiadkę do miasta docelowego. W Sortowni Głównej zatrzymuje się na chwilę większość przesyłek InPost. W supernowoczesnym magazynie sortowanych jest nawet milion przesyłek dziennie!");
// statusesMap.put("sent_from_sorting_center", "Przesyłka jedzie do miasta Odbiorcy.");
// statusesMap.put("adopted_at_target_branch", "Przesyłka jest już w mieście Odbiorcy. Wkrótce trafi do rąk doręczyciela i rozpocznie ostatni etap podróży.");
// statusesMap.put("out_for_delivery", "Przesyłka trafi do odbiorcy najpóźniej w najbliższym dniu roboczym. Doręczyciel InPost rozwozi przesyłki nawet do późnych godzin wieczornych, dlatego warto mieć włączony telefon.");
// statusesMap.put("ready_to_pickup", "I gotowe! Paczka czeka na odbiór w wybranym automacie Paczkomat. Odbiorca otrzymuje e-maila, a także powiadomienie w aplikacji InPost Mobile lub SMS-a z kodem odbioru i informacją, jak długo paczka będzie czekać na odbiór. Jeśli paczka nie zostanie odebrana w tym czasie, zostanie zwrócona do Nadawcy, o czym poinformujemy Odbiorcę w osobnych komunikatach.");
// statusesMap.put("pickup_reminder_sent", "Paczka oczekuje w automacie Paczkomat. Będzie tam czekać na Ciebie przez kolejne 24 godziny. Pośpiesz się! Jeśli przesyłka nie zostanie odebrana z automatu Paczkomat, wróci do Nadawcy. Chcesz odpłatnie przedłużyć pobyt przesyłki w automacie Paczkomat? Możesz to zrobić w naszej aplikacji InPost Mobile! Dowiedz się więcej: [https://inpost.pl/pomoc-jak-przedluzyc-termin-odbioru-paczki-w-paczkomacie].");
// statusesMap.put("delivered", "Podróż przesyłki od Nadawcy do Odbiorcy zakończyła się, ale nie musi to oznaczać końca naszej znajomości:) Jeśli lubisz InPost, odwiedź nasz fanpage na Facebooku. Dziękujemy!");
// statusesMap.put("pickup_time_expired", "Czas na odbiór Paczki z automatu Paczkomat już minął. Paczka zostanie zwrócona do Nadawcy. Odbiorca jeszcze ma szansę odebrać paczkę, jeśli dotrze do automatu Paczkomat przed Doręczycielem InPost.");
// statusesMap.put("avizo", "Kurier InPost ponownie nie zastał Odbiorcy pod wskazanym adresem. Przesyłka wyruszyła w drogę powrotną do Nadawcy.");
// statusesMap.put("claimed", "Prosimy o dokończenie procesu reklamacji poprzez wypełnienie formularza na stronie InPost.");
// statusesMap.put("returned_to_sender", "Przesyłka wyruszyła w drogę powrotną do Nadawcy.");
// statusesMap.put("canceled", "Etykieta nadawcza została anulowana lub utraciła ważność. Przesyłka nie została wysłana do Odbiorcy.");
// statusesMap.put("other", "Przesyłka znajduje się w nierozpoznanym statusie.");
// statusesMap.put("dispatched_by_sender_to_pok", "Nadawca przekazał przesyłkę pracownikowi punktu InPost. Tu rozpoczyna się jej podróż do Odbiorcy.");
// statusesMap.put("out_for_delivery_to_address", "Przesyłka jest już na ostatnim etapie podróży - została przekazana kurierowi w celu dostarczenia pod wskazany adres.");
// statusesMap.put("pickup_reminder_sent_address", "Kurier InPost nie zastał Odbiorcy pod wskazanym adresem. Kolejna próba doręczenia nastąpi w następnym dniu roboczym.");
// statusesMap.put("rejected_by_receiver", "Odbiorca odmówił przyjęcia przesyłki.");
// statusesMap.put("undelivered_wrong_address", "Brak możliwości doręczenia w dniu dzisiejszym. Powód: błędne dane adresowe.");
// statusesMap.put("undelivered_incomplete_address", "Brak możliwości doręczenia w dniu dzisiejszym. Powód: niepełne dane adresowe.");
// statusesMap.put("undelivered_unknown_receiver", "Brak możliwości doręczenia w dniu dzisiejszym. Powód: Odbiorca nieznany.");
// statusesMap.put("undelivered_cod_cash_receiver", "Brak możliwości doręczenia w dniu dzisiejszym - Odbiorca nie miał gotówki do opłacenia kwoty pobrania.");
// statusesMap.put("taken_by_courier_from_pok", "Doręczyciel InPost odebrał przesyłkę nadaną w PaczkoPunkcie i przekazuje ją do oddziału InPost, skąd zostanie wysłana w dalszą drogę.");
// statusesMap.put("undelivered", "Przekazanie do magazynu przesyłek niedoręczalnych.");
// statusesMap.put("return_pickup_confirmation_to_sender", "Przesyłka została odebrana. Zwrotne Potwierdzenie Odbioru zostało wysłane do Nadawcy.");
// statusesMap.put("ready_to_pickup_from_branch", "Jeśli Twoja paczka trafiła do oddziału InPost, skontaktuj się z Infolinią, aby sprawdzić możliwości jej odbioru.");
// statusesMap.put("delay_in_delivery", "Dostawa się opóźni - najmocniej przepraszamy. W kolejnych wiadomościach poinformujemy Odbiorcę o nowym terminie doręczenia.");
// statusesMap.put("redirect_to_box", "Adresat tej paczki kurierskiej skorzystał z darmowej opcji dynamicznego przekierowania do automatu Paczkomat InPost. Po dostarczeniu przesyłki do wybranej maszyny odbiorca otrzyma wiadomości, dzięki którym, będzie mógł ją odebrać.");
// statusesMap.put("canceled_redirect_to_box", "Przekierowanie tej paczki kurierskiej do automatu Paczkomat InPost okazało się niemożliwe ze względu na zbyt duży gabaryt. Przesyłka zostanie doręczona do Odbiorcy na adres wskazany w zamówieniu.");
// statusesMap.put("readdressed", "Przesyłka kurierska została bezpłatnie przekierowana na inny adres na życzenie Odbiorcy.");
// statusesMap.put("undelivered_no_mailbox", "Brak możliwości doręczenia w dniu dzisiejszym. Powód: brak skrzynki pocztowej.");
// statusesMap.put("undelivered_not_live_address", "Brak możliwości doręczenia w dniu dzisiejszym. Powód: Odbiorca nie mieszka pod wskazanym adresem.");
// statusesMap.put("undelivered_lack_of_access_letterbox", "Paczka wyruszyła w drogę powrotną do Nadawcy.");
// statusesMap.put("missing", "translation missing: pl_PL.statuses.missing.description");
// statusesMap.put("stack_in_customer_service_point", "Kliknij i dowiedz się więcej na temat magazynowania paczek w PaczkoPunkcie. https://inpost.pl/pomoc-czym-jest-magazynowanie-paczek-w-pop");
// statusesMap.put("stack_parcel_pickup_time_expired", "Upłynął termin odebrania paczki z PaczkoPunktu, ale paczka nadal jest w nim magazynowana - czeka na przyjazd kuriera, który ją zabierze do automatu Paczkomat.");
// statusesMap.put("unstack_from_customer_service_point", "Kurier wiezie Twoją paczkę do automatu Paczkomat.");
// statusesMap.put("courier_avizo_in_customer_service_point", "Paczka została awizowana w PaczkoPunkcie. Jeśli jej nie odbierzesz w ciągu trzech dni roboczych, wróci do Nadawcy.");
// statusesMap.put("taken_by_courier_from_customer_service_point", "Czas na odbiór paczki minął. Została odebrana przez Kuriera z PaczkoPunktu i niebawem wyruszy w podróż powrotną do Nadawcy.");
// statusesMap.put("stack_in_box_machine", "Kliknij i dowiedz się więcej na temat magazynowania paczek w tymczasowych automatach Paczkomat: https://inpost.pl/pomoc-czym-jest-magazynowanie-paczek-w-paczkomatach-tymczasowych");
// statusesMap.put("unstack_from_box_machine", "Czas na odbiór paczki magazynowanej w tymczasowym automacie Paczkomat upłynął. Paczka jest w drodze do pierwotnie wybranego automatu Paczkomat. Poinformujemy Cię, gdy będzie na miejscu.");
// statusesMap.put("stack_parcel_in_box_machine_pickup_time_expired", "Upłynął termin odebrania paczki z automatu Paczkomat tymczasowego, ale paczka nadal jest w nim magazynowana - czeka na przyjazd kuriera, który ją zabierze do pierwotnie wybranego automatu Paczkomat.");
// return statusesMap;
// }
private static Map<String, String> initInPostShortDescriptionStatusesMap() {
final Map<String, String> statusesMap = new HashMap<>(53);
statusesMap.put("created", "Przesyłka utworzona.");
statusesMap.put("offers_prepared", "Przygotowano oferty.");
statusesMap.put("offer_selected", "Oferta wybrana.");
statusesMap.put("confirmed", "Przygotowana przez Nadawcę.");
statusesMap.put("dispatched_by_sender", "Paczka nadana w automacie Paczkomat.");
statusesMap.put("collected_from_sender", "Odebrana od klienta.");
statusesMap.put("taken_by_courier", "Odebrana od Nadawcy.");
statusesMap.put("adopted_at_source_branch", "Przyjęta w oddziale InPost.");
statusesMap.put("sent_from_source_branch", "W trasie.");
statusesMap.put("ready_to_pickup_from_pok", "Czeka na odbiór w PaczkoPunkcie.");
statusesMap.put("ready_to_pickup_from_pok_registered", "Czeka na odbiór w PaczkoPunkcie.");
statusesMap.put("oversized", "Przesyłka ponadgabarytowa.");
statusesMap.put("adopted_at_sorting_center", "Przyjęta w Sortowni.");
statusesMap.put("sent_from_sorting_center", "Wysłana z Sortowni.");
statusesMap.put("adopted_at_target_branch", "Przyjęta w Oddziale Docelowym.");
statusesMap.put("out_for_delivery", "Przekazano do doręczenia.");
statusesMap.put("ready_to_pickup", "Umieszczona w automacie Paczkomat (odbiorczym).");
statusesMap.put("pickup_reminder_sent", "Przypomnienie o czekającej paczce.");
statusesMap.put("delivered", "Dostarczona.");
statusesMap.put("pickup_time_expired", "Upłynął termin odbioru.");
statusesMap.put("avizo", "Powrót do oddziału.");
statusesMap.put("claimed", "Zareklamowana w automacie Paczkomat.");
statusesMap.put("returned_to_sender", "Zwrot do nadawcy.");
statusesMap.put("canceled", "Anulowano etykietę.");
statusesMap.put("other", "Inny status.");
statusesMap.put("dispatched_by_sender_to_pok", "Nadana w PaczkoPunkcie.");
statusesMap.put("out_for_delivery_to_address", "W doręczeniu.");
statusesMap.put("pickup_reminder_sent_address", "W doręczeniu.");
statusesMap.put("rejected_by_receiver", "Odmowa przyjęcia.");
statusesMap.put("undelivered_wrong_address", IMPOSSIBLE_TO_DELIVER);
statusesMap.put("undelivered_incomplete_address", IMPOSSIBLE_TO_DELIVER);
statusesMap.put("undelivered_unknown_receiver", IMPOSSIBLE_TO_DELIVER);
statusesMap.put("undelivered_cod_cash_receiver", IMPOSSIBLE_TO_DELIVER);
statusesMap.put("taken_by_courier_from_pok", "W drodze do oddziału nadawczego InPost.");
statusesMap.put("undelivered", "Przekazanie do magazynu przesyłek niedoręczalnych.");
statusesMap.put("return_pickup_confirmation_to_sender", "Przygotowano dokumenty zwrotne.");
statusesMap.put("ready_to_pickup_from_branch", "Paczka nieodebrana – czeka w Oddziale.");
statusesMap.put("delay_in_delivery", "Możliwe opóźnienie doręczenia.");
statusesMap.put("redirect_to_box", "Przekierowano do automatu Paczkomat.");
statusesMap.put("canceled_redirect_to_box", "Anulowano przekierowanie.");
statusesMap.put("readdressed", "Przekierowano na inny adres.");
statusesMap.put("undelivered_no_mailbox", IMPOSSIBLE_TO_DELIVER);
statusesMap.put("undelivered_not_live_address", IMPOSSIBLE_TO_DELIVER);
statusesMap.put("undelivered_lack_of_access_letterbox", IMPOSSIBLE_TO_DELIVER);
statusesMap.put("missing", "translation missing: pl_PL.statuses.missing.title");
statusesMap.put("stack_in_customer_service_point", "Paczka magazynowana w PaczkoPunkcie.");
statusesMap.put("stack_parcel_pickup_time_expired", "Upłynął termin odbioru paczki magazynowanej.");
statusesMap.put("unstack_from_customer_service_point", "W drodze do wybranego automatu Paczkomat.");
statusesMap.put("courier_avizo_in_customer_service_point", "Oczekuje na odbiór.");
statusesMap.put("taken_by_courier_from_customer_service_point", "Zwrócona do nadawcy.");
statusesMap.put("stack_in_box_machine", "Paczka magazynowana w tymczasowym automacie Paczkomat.");
statusesMap.put("unstack_from_box_machine", "Paczka w drodze do pierwotnie wybranego automatu Paczkomat.");
statusesMap.put("stack_parcel_in_box_machine_pickup_time_expired", "Upłynął termin odbioru paczki magazynowanej.");
return statusesMap;
}
}
| // statusesMap.put("pickup_time_expired", "Czas na odbiór Paczki z automatu Paczkomat już minął. Paczka zostanie zwrócona do Nadawcy. Odbiorca jeszcze ma szansę odebrać paczkę, jeśli dotrze do automatu Paczkomat przed Doręczycielem InPost."); | package track.app.mapper;
import org.apache.commons.lang3.StringUtils;
import track.app.model.DeliveryStatus;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static track.app.model.DeliveryStatus.*;
public class InPostStatusMapper {
private static final String IMPOSSIBLE_TO_DELIVER = "Brak możliwości doręczenia.";
// z InPost api object "origin_status": key = "name", value = "description"
// public static final Map<String, String> inPostLongDescriptionStatusMap = initInPostLongDescriptionStatusesMap();
public static final Map<String, String> inPostShortDescriptionStatusMap = initInPostShortDescriptionStatusesMap();
private InPostStatusMapper() {
// do nothing
}
public static DeliveryStatus toDeliveryStatusMapper(String inPostStatusName) {
if (StringUtils.isEmpty(inPostStatusName)) {
return NOT_FOUND;
}
if (List.of("created", "offers_prepared", "offer_selected", "confirmed").contains(inPostStatusName)) {
return CONFIRMED;
}
if ("dispatched_by_sender".equals(inPostStatusName)){
return IN_SHIPPING_PARCEL_LOCKER;
}
if (List.of(
"collected_from_sender", "taken_by_courier", "dispatched_by_sender_to_pok", "taken_by_courier_from_pok"
).contains(inPostStatusName)) {
return HANDED_TO_SHIPPING_COMPANY;
}
if (List.of("adopted_at_source_branch", "sent_from_source_branch", "adopted_at_sorting_center", "sent_from_sorting_center", "adopted_at_target_branch", "out_for_delivery", "out_for_delivery_to_address").contains(inPostStatusName)) {
return ON_THE_ROAD;
}
if (List.of("ready_to_pickup", "pickup_reminder_sent").contains(inPostStatusName)) {
return WAITING_IN_RECEIVING_PARCEL_LOCKER;
}
if ("delivered".equals(inPostStatusName)) {
return DELIVERED;
}
return NOT_STANDARD_STAGE;
}
public static List<DeliveryStatus> getActiveStatusesList() {
return List.of(
UNKNOWN, NOT_FOUND, CONFIRMED, HANDED_TO_SHIPPING_COMPANY,IN_SHIPPING_PARCEL_LOCKER,
ON_THE_ROAD, HANDED_OUT_FOR_DELIVERY, WAITING_IN_RECEIVING_PARCEL_LOCKER, NOT_STANDARD_STAGE
);
}
// private static Map<String, String> initInPostLongDescriptionStatusesMap() {
// final Map<String, String> statusesMap = new HashMap<>(53);
// statusesMap.put("created", "Przesyłka została utworzona, ale nie jest gotowa do nadania.");
// statusesMap.put("offers_prepared", "Oferty dla przesyłki zostały przygotowane.");
// statusesMap.put("offer_selected", "Klient wybrał jedną z zaproponowanych ofert.");
// statusesMap.put("confirmed", "Nadawca poinformował nas, że przygotował przesyłkę do nadania. Podróż przesyłki jeszcze się nie rozpoczęła.");
// statusesMap.put("dispatched_by_sender", "Paczka oczekuje na wyjęcie z automatu Paczkomat przez doręczyciela. Stąd trafi do najbliższego oddziału InPost i wyruszy w trasę do odbiorczego automatu Paczkomat.");
// statusesMap.put("collected_from_sender", "Kurier odebrał paczkę od Nadawcy i przekazuje ją do oddziału InPost.");
// statusesMap.put("taken_by_courier", "Przesyłka została odebrana od Nadawcy i wyruszyła w dalszą drogę.");
// statusesMap.put("adopted_at_source_branch", "Przesyłka trafiła do oddziału InPost, skąd wkrótce wyruszy w dalszą drogę.");
// statusesMap.put("sent_from_source_branch", "Przesyłka jest transportowana między oddziałami InPost.");
// statusesMap.put("ready_to_pickup_from_pok", "Prosimy o odebranie przesyłki z punktu InPost w ciągu 3 dni.");
// statusesMap.put("ready_to_pickup_from_pok_registered", "Prosimy o odebranie przesyłki z punktu InPost w ciągu 3 dni. Adres.");
// statusesMap.put("oversized", "Paczka nie mieści się w skrytce automatu Paczkomat.");
// statusesMap.put("adopted_at_sorting_center", "Przesyłka czeka na przesiadkę do miasta docelowego. W Sortowni Głównej zatrzymuje się na chwilę większość przesyłek InPost. W supernowoczesnym magazynie sortowanych jest nawet milion przesyłek dziennie!");
// statusesMap.put("sent_from_sorting_center", "Przesyłka jedzie do miasta Odbiorcy.");
// statusesMap.put("adopted_at_target_branch", "Przesyłka jest już w mieście Odbiorcy. Wkrótce trafi do rąk doręczyciela i rozpocznie ostatni etap podróży.");
// statusesMap.put("out_for_delivery", "Przesyłka trafi do odbiorcy najpóźniej w najbliższym dniu roboczym. Doręczyciel InPost rozwozi przesyłki nawet do późnych godzin wieczornych, dlatego warto mieć włączony telefon.");
// statusesMap.put("ready_to_pickup", "I gotowe! Paczka czeka na odbiór w wybranym automacie Paczkomat. Odbiorca otrzymuje e-maila, a także powiadomienie w aplikacji InPost Mobile lub SMS-a z kodem odbioru i informacją, jak długo paczka będzie czekać na odbiór. Jeśli paczka nie zostanie odebrana w tym czasie, zostanie zwrócona do Nadawcy, o czym poinformujemy Odbiorcę w osobnych komunikatach.");
// statusesMap.put("pickup_reminder_sent", "Paczka oczekuje w automacie Paczkomat. Będzie tam czekać na Ciebie przez kolejne 24 godziny. Pośpiesz się! Jeśli przesyłka nie zostanie odebrana z automatu Paczkomat, wróci do Nadawcy. Chcesz odpłatnie przedłużyć pobyt przesyłki w automacie Paczkomat? Możesz to zrobić w naszej aplikacji InPost Mobile! Dowiedz się więcej: [https://inpost.pl/pomoc-jak-przedluzyc-termin-odbioru-paczki-w-paczkomacie].");
// statusesMap.put("delivered", "Podróż przesyłki od Nadawcy do Odbiorcy zakończyła się, ale nie musi to oznaczać końca naszej znajomości:) Jeśli lubisz InPost, odwiedź nasz fanpage na Facebooku. Dziękujemy!");
// statusesMap.put("pickup_time_expired", "Czas <SUF>
// statusesMap.put("avizo", "Kurier InPost ponownie nie zastał Odbiorcy pod wskazanym adresem. Przesyłka wyruszyła w drogę powrotną do Nadawcy.");
// statusesMap.put("claimed", "Prosimy o dokończenie procesu reklamacji poprzez wypełnienie formularza na stronie InPost.");
// statusesMap.put("returned_to_sender", "Przesyłka wyruszyła w drogę powrotną do Nadawcy.");
// statusesMap.put("canceled", "Etykieta nadawcza została anulowana lub utraciła ważność. Przesyłka nie została wysłana do Odbiorcy.");
// statusesMap.put("other", "Przesyłka znajduje się w nierozpoznanym statusie.");
// statusesMap.put("dispatched_by_sender_to_pok", "Nadawca przekazał przesyłkę pracownikowi punktu InPost. Tu rozpoczyna się jej podróż do Odbiorcy.");
// statusesMap.put("out_for_delivery_to_address", "Przesyłka jest już na ostatnim etapie podróży - została przekazana kurierowi w celu dostarczenia pod wskazany adres.");
// statusesMap.put("pickup_reminder_sent_address", "Kurier InPost nie zastał Odbiorcy pod wskazanym adresem. Kolejna próba doręczenia nastąpi w następnym dniu roboczym.");
// statusesMap.put("rejected_by_receiver", "Odbiorca odmówił przyjęcia przesyłki.");
// statusesMap.put("undelivered_wrong_address", "Brak możliwości doręczenia w dniu dzisiejszym. Powód: błędne dane adresowe.");
// statusesMap.put("undelivered_incomplete_address", "Brak możliwości doręczenia w dniu dzisiejszym. Powód: niepełne dane adresowe.");
// statusesMap.put("undelivered_unknown_receiver", "Brak możliwości doręczenia w dniu dzisiejszym. Powód: Odbiorca nieznany.");
// statusesMap.put("undelivered_cod_cash_receiver", "Brak możliwości doręczenia w dniu dzisiejszym - Odbiorca nie miał gotówki do opłacenia kwoty pobrania.");
// statusesMap.put("taken_by_courier_from_pok", "Doręczyciel InPost odebrał przesyłkę nadaną w PaczkoPunkcie i przekazuje ją do oddziału InPost, skąd zostanie wysłana w dalszą drogę.");
// statusesMap.put("undelivered", "Przekazanie do magazynu przesyłek niedoręczalnych.");
// statusesMap.put("return_pickup_confirmation_to_sender", "Przesyłka została odebrana. Zwrotne Potwierdzenie Odbioru zostało wysłane do Nadawcy.");
// statusesMap.put("ready_to_pickup_from_branch", "Jeśli Twoja paczka trafiła do oddziału InPost, skontaktuj się z Infolinią, aby sprawdzić możliwości jej odbioru.");
// statusesMap.put("delay_in_delivery", "Dostawa się opóźni - najmocniej przepraszamy. W kolejnych wiadomościach poinformujemy Odbiorcę o nowym terminie doręczenia.");
// statusesMap.put("redirect_to_box", "Adresat tej paczki kurierskiej skorzystał z darmowej opcji dynamicznego przekierowania do automatu Paczkomat InPost. Po dostarczeniu przesyłki do wybranej maszyny odbiorca otrzyma wiadomości, dzięki którym, będzie mógł ją odebrać.");
// statusesMap.put("canceled_redirect_to_box", "Przekierowanie tej paczki kurierskiej do automatu Paczkomat InPost okazało się niemożliwe ze względu na zbyt duży gabaryt. Przesyłka zostanie doręczona do Odbiorcy na adres wskazany w zamówieniu.");
// statusesMap.put("readdressed", "Przesyłka kurierska została bezpłatnie przekierowana na inny adres na życzenie Odbiorcy.");
// statusesMap.put("undelivered_no_mailbox", "Brak możliwości doręczenia w dniu dzisiejszym. Powód: brak skrzynki pocztowej.");
// statusesMap.put("undelivered_not_live_address", "Brak możliwości doręczenia w dniu dzisiejszym. Powód: Odbiorca nie mieszka pod wskazanym adresem.");
// statusesMap.put("undelivered_lack_of_access_letterbox", "Paczka wyruszyła w drogę powrotną do Nadawcy.");
// statusesMap.put("missing", "translation missing: pl_PL.statuses.missing.description");
// statusesMap.put("stack_in_customer_service_point", "Kliknij i dowiedz się więcej na temat magazynowania paczek w PaczkoPunkcie. https://inpost.pl/pomoc-czym-jest-magazynowanie-paczek-w-pop");
// statusesMap.put("stack_parcel_pickup_time_expired", "Upłynął termin odebrania paczki z PaczkoPunktu, ale paczka nadal jest w nim magazynowana - czeka na przyjazd kuriera, który ją zabierze do automatu Paczkomat.");
// statusesMap.put("unstack_from_customer_service_point", "Kurier wiezie Twoją paczkę do automatu Paczkomat.");
// statusesMap.put("courier_avizo_in_customer_service_point", "Paczka została awizowana w PaczkoPunkcie. Jeśli jej nie odbierzesz w ciągu trzech dni roboczych, wróci do Nadawcy.");
// statusesMap.put("taken_by_courier_from_customer_service_point", "Czas na odbiór paczki minął. Została odebrana przez Kuriera z PaczkoPunktu i niebawem wyruszy w podróż powrotną do Nadawcy.");
// statusesMap.put("stack_in_box_machine", "Kliknij i dowiedz się więcej na temat magazynowania paczek w tymczasowych automatach Paczkomat: https://inpost.pl/pomoc-czym-jest-magazynowanie-paczek-w-paczkomatach-tymczasowych");
// statusesMap.put("unstack_from_box_machine", "Czas na odbiór paczki magazynowanej w tymczasowym automacie Paczkomat upłynął. Paczka jest w drodze do pierwotnie wybranego automatu Paczkomat. Poinformujemy Cię, gdy będzie na miejscu.");
// statusesMap.put("stack_parcel_in_box_machine_pickup_time_expired", "Upłynął termin odebrania paczki z automatu Paczkomat tymczasowego, ale paczka nadal jest w nim magazynowana - czeka na przyjazd kuriera, który ją zabierze do pierwotnie wybranego automatu Paczkomat.");
// return statusesMap;
// }
private static Map<String, String> initInPostShortDescriptionStatusesMap() {
final Map<String, String> statusesMap = new HashMap<>(53);
statusesMap.put("created", "Przesyłka utworzona.");
statusesMap.put("offers_prepared", "Przygotowano oferty.");
statusesMap.put("offer_selected", "Oferta wybrana.");
statusesMap.put("confirmed", "Przygotowana przez Nadawcę.");
statusesMap.put("dispatched_by_sender", "Paczka nadana w automacie Paczkomat.");
statusesMap.put("collected_from_sender", "Odebrana od klienta.");
statusesMap.put("taken_by_courier", "Odebrana od Nadawcy.");
statusesMap.put("adopted_at_source_branch", "Przyjęta w oddziale InPost.");
statusesMap.put("sent_from_source_branch", "W trasie.");
statusesMap.put("ready_to_pickup_from_pok", "Czeka na odbiór w PaczkoPunkcie.");
statusesMap.put("ready_to_pickup_from_pok_registered", "Czeka na odbiór w PaczkoPunkcie.");
statusesMap.put("oversized", "Przesyłka ponadgabarytowa.");
statusesMap.put("adopted_at_sorting_center", "Przyjęta w Sortowni.");
statusesMap.put("sent_from_sorting_center", "Wysłana z Sortowni.");
statusesMap.put("adopted_at_target_branch", "Przyjęta w Oddziale Docelowym.");
statusesMap.put("out_for_delivery", "Przekazano do doręczenia.");
statusesMap.put("ready_to_pickup", "Umieszczona w automacie Paczkomat (odbiorczym).");
statusesMap.put("pickup_reminder_sent", "Przypomnienie o czekającej paczce.");
statusesMap.put("delivered", "Dostarczona.");
statusesMap.put("pickup_time_expired", "Upłynął termin odbioru.");
statusesMap.put("avizo", "Powrót do oddziału.");
statusesMap.put("claimed", "Zareklamowana w automacie Paczkomat.");
statusesMap.put("returned_to_sender", "Zwrot do nadawcy.");
statusesMap.put("canceled", "Anulowano etykietę.");
statusesMap.put("other", "Inny status.");
statusesMap.put("dispatched_by_sender_to_pok", "Nadana w PaczkoPunkcie.");
statusesMap.put("out_for_delivery_to_address", "W doręczeniu.");
statusesMap.put("pickup_reminder_sent_address", "W doręczeniu.");
statusesMap.put("rejected_by_receiver", "Odmowa przyjęcia.");
statusesMap.put("undelivered_wrong_address", IMPOSSIBLE_TO_DELIVER);
statusesMap.put("undelivered_incomplete_address", IMPOSSIBLE_TO_DELIVER);
statusesMap.put("undelivered_unknown_receiver", IMPOSSIBLE_TO_DELIVER);
statusesMap.put("undelivered_cod_cash_receiver", IMPOSSIBLE_TO_DELIVER);
statusesMap.put("taken_by_courier_from_pok", "W drodze do oddziału nadawczego InPost.");
statusesMap.put("undelivered", "Przekazanie do magazynu przesyłek niedoręczalnych.");
statusesMap.put("return_pickup_confirmation_to_sender", "Przygotowano dokumenty zwrotne.");
statusesMap.put("ready_to_pickup_from_branch", "Paczka nieodebrana – czeka w Oddziale.");
statusesMap.put("delay_in_delivery", "Możliwe opóźnienie doręczenia.");
statusesMap.put("redirect_to_box", "Przekierowano do automatu Paczkomat.");
statusesMap.put("canceled_redirect_to_box", "Anulowano przekierowanie.");
statusesMap.put("readdressed", "Przekierowano na inny adres.");
statusesMap.put("undelivered_no_mailbox", IMPOSSIBLE_TO_DELIVER);
statusesMap.put("undelivered_not_live_address", IMPOSSIBLE_TO_DELIVER);
statusesMap.put("undelivered_lack_of_access_letterbox", IMPOSSIBLE_TO_DELIVER);
statusesMap.put("missing", "translation missing: pl_PL.statuses.missing.title");
statusesMap.put("stack_in_customer_service_point", "Paczka magazynowana w PaczkoPunkcie.");
statusesMap.put("stack_parcel_pickup_time_expired", "Upłynął termin odbioru paczki magazynowanej.");
statusesMap.put("unstack_from_customer_service_point", "W drodze do wybranego automatu Paczkomat.");
statusesMap.put("courier_avizo_in_customer_service_point", "Oczekuje na odbiór.");
statusesMap.put("taken_by_courier_from_customer_service_point", "Zwrócona do nadawcy.");
statusesMap.put("stack_in_box_machine", "Paczka magazynowana w tymczasowym automacie Paczkomat.");
statusesMap.put("unstack_from_box_machine", "Paczka w drodze do pierwotnie wybranego automatu Paczkomat.");
statusesMap.put("stack_parcel_in_box_machine_pickup_time_expired", "Upłynął termin odbioru paczki magazynowanej.");
return statusesMap;
}
}
| null |
4416_6 | BeterTugeder/Dziennik | 7,935 | src/main/java/pl/projekt5/views/Opcje.java | /*
* 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 pl.projekt5.views;
import java.util.ListIterator;
import pl.projekt5.models.ModelFactory;
import pl.projekt5.models.Nauczyciel;
import pl.projekt5.models.NauczycielModel;
import javax.swing.JOptionPane;
import static javax.swing.JOptionPane.showMessageDialog;
import pl.projekt5.models.Klasa;
import pl.projekt5.models.KlasaModel;
import pl.projekt5.models.Przedmiot;
import pl.projekt5.models.PrzedmiotModel;
import pl.projekt5.models.Uczen;
import pl.projekt5.models.UczenModel;
/**
*
* @author Jacek
*/
public class Opcje extends javax.swing.JFrame {
/**
* Creates new form Opcje
*/
public Opcje() {
initComponents();
ModelFactory m = ModelFactory.getInstance();
KlasaModel klasa1 = (KlasaModel)m.getModel("KlasaModel");
ListIterator<Klasa> it = klasa1.getAll().listIterator();
while(it.hasNext()){
jComboBox3.addItem(it.next().nazwa);
}
if(!jCheckBox1.isSelected())
jComboBox3.setVisible(false);
else
jComboBox3.setVisible(true);
opcja.setVisible(false);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
tytul = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jCheckBox1 = new javax.swing.JCheckBox();
jComboBox3 = new javax.swing.JComboBox();
haslo_label = new javax.swing.JLabel();
haslo_pole = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jTextField3 = new javax.swing.JTextField();
opcja = new javax.swing.JLabel();
combo1 = new javax.swing.JComboBox();
Zamknij = new javax.swing.JButton();
combo2 = new javax.swing.JComboBox();
label_combo1 = new javax.swing.JLabel();
label_combo2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
tytul.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N
tytul.setText("Dodaj/usun nauczyciela klase..");
jLabel2.setText("jLabel2");
jLabel3.setText("jLabel3");
jTextField2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField2ActionPerformed(evt);
}
});
jButton1.setText("Zatwierdz");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jCheckBox1.setText("Wychowawca");
jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBox1ActionPerformed(evt);
}
});
jComboBox3.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Jakiej klasy?" }));
jComboBox3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox3ActionPerformed(evt);
}
});
haslo_label.setText("Haslo");
jLabel1.setText("Przedmiot");
jTextField3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField3ActionPerformed(evt);
}
});
Zamknij.setText("Zamknij");
Zamknij.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ZamknijActionPerformed(evt);
}
});
label_combo1.setText("jLabel4");
label_combo2.setText("jLabel5");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(opcja)
.addGap(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tytul)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jCheckBox1)
.addComponent(jLabel3)
.addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 64, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jTextField1)
.addGap(25, 25, 25)))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(combo1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(label_combo1))
.addGap(25, 25, 25)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(label_combo2)
.addComponent(haslo_pole, javax.swing.GroupLayout.DEFAULT_SIZE, 161, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Zamknij))
.addComponent(jLabel1)
.addComponent(haslo_label)
.addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE, 161, Short.MAX_VALUE)
.addComponent(combo2, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap(91, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(tytul))
.addComponent(opcja))
.addGap(36, 36, 36)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(label_combo1)
.addComponent(label_combo2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(combo1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(combo2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(haslo_label)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(haslo_pole, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jCheckBox1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1)
.addComponent(Zamknij))
.addContainerGap(37, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
void ukryj_wszystko(){
combo1.setVisible(false);
combo2.setVisible(false);
haslo_label.setVisible(false);
haslo_pole.setVisible(false);
jCheckBox1.setVisible(false);
jComboBox3.setVisible(false);
jLabel1.setVisible(false);
jLabel2.setVisible(false);
jLabel3.setVisible(false);
label_combo1.setVisible(false);
label_combo2.setVisible(false);
jTextField1.setVisible(false);
jTextField2.setVisible(false);
jTextField3.setVisible(false);
opcja.setVisible(false);
}
private void jComboBox3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox3ActionPerformed
if(opcja.getText().equals("5")){
ModelFactory m = ModelFactory.getInstance();
String nazwa = jComboBox3.getSelectedItem().toString();
KlasaModel kl = (KlasaModel)m.getModel("KlasaModel");
ListIterator<Klasa> it = kl.getAll().listIterator();
int id = 0;
while(it.hasNext()){
Klasa kl2 = it.next();
if(nazwa.equals(kl2.nazwa)){
id = kl2.id;
}
}
UczenModel uczen1 = (UczenModel)m.getModel("UczenModel");
ListIterator<Uczen> it2 = uczen1.getAll(id).listIterator();
while(it2.hasNext()){
Uczen uczen2 = it2.next();
combo1.addItem(uczen2.nazwisko+" "+uczen2.imie);
}
}
}//GEN-LAST:event_jComboBox3ActionPerformed
private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox1ActionPerformed
if(jCheckBox1.isSelected())
jComboBox3.setVisible(true);
else
jComboBox3.setVisible(false);
}//GEN-LAST:event_jCheckBox1ActionPerformed
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField2ActionPerformed
void dodaj_nauczyciela(){
ModelFactory m = ModelFactory.getInstance();
NauczycielModel nauczyciele = (NauczycielModel)m.getModel("NauczycielModel");
PrzedmiotModel przedmioty = (PrzedmiotModel)m.getModel("PrzedmiotModel");
if(jTextField1.getText().equals("") || jTextField2.getText().equals("") || haslo_pole.getText().equals("")){
showMessageDialog(null, "Sprawdz poprawnosc wpisanych danych");
}
else{
String imie = jTextField1.getText();
String nazwisko = jTextField2.getText();
String haslo = haslo_pole.getText();
Nauczyciel naucz = new Nauczyciel(1, imie, nazwisko);
KlasaModel klasa1 = (KlasaModel)m.getModel("KlasaModel");
ListIterator<Klasa> it = klasa1.getAll().listIterator();
if(jCheckBox1.isSelected()){
int id2=0;
while(it.hasNext()){
if(it.next().nazwa.equals(jComboBox3.getSelectedItem().toString())){
it.previous();
id2 = it.next().id;
//nauczyciele.update(nauczyciele.get(id2, true), 0);
}
}
nauczyciele.add(naucz, haslo, id2);
}
else{
nauczyciele.add(naucz, haslo);
}
ListIterator<Nauczyciel> int2 = nauczyciele.getAll().listIterator();
int idd=0;
while(int2.hasNext()){
idd = int2.next().id;
}
if(!jTextField3.getText().equals("")) {
Przedmiot przed = new Przedmiot(1, jTextField3.getText());
przedmioty.add(przed, idd);
}
showMessageDialog(null, "Dodano nauczyciela");
view okno = new view();
okno.setVisible(true);
dispose();
}
}
void dodaj_klase(){
ModelFactory m = ModelFactory.getInstance();
KlasaModel klasy = (KlasaModel)m.getModel("KlasaModel");
if(jTextField1.getText().equals("")){
showMessageDialog(null, "Pole z nazwa klasy jest puste");
}
else{
String nazwa = jTextField1.getText();
boolean flaga=false;
KlasaModel klasa1 = (KlasaModel)m.getModel("KlasaModel");
ListIterator<Klasa> it = klasa1.getAll().listIterator();
while(it.hasNext()){
if(it.next().nazwa.equals(nazwa)){
flaga = true;
}
}
if(flaga){
showMessageDialog(null, "W bazie zajduje sie juz klasa o takiej nazwie");
}
else{
Klasa kl = new Klasa(1, nazwa);
klasy.add(kl);
showMessageDialog(null, "Dodano klase");
view okno = new view();
okno.setVisible(true);
dispose();
}
}
}
void dodaj_ucznia(){
if(jTextField1.getText().equals("") || jTextField2.getText().equals("")){
showMessageDialog(null, "Sprawdz poprawnosc wpisanych danych");
}
else{
ModelFactory m = ModelFactory.getInstance();
KlasaModel klasa1 = (KlasaModel)m.getModel("KlasaModel");
ListIterator<Klasa> it = klasa1.getAll().listIterator();
int id=0;
while(it.hasNext()){
if(it.next().nazwa.equals(jComboBox3.getSelectedItem().toString())){
it.previous();
id = it.next().id;
}
}
Uczen ucz = new Uczen(1, jTextField1.getText(), jTextField2.getText());
UczenModel uczniowie = (UczenModel)m.getModel("UczenModel");
uczniowie.add(ucz, id);
showMessageDialog(null, "Dodano ucznia");
view okno = new view();
okno.setVisible(true);
dispose();
}
}
void usun_nauczyciela(){
ModelFactory m = ModelFactory.getInstance();
NauczycielModel naucz = (NauczycielModel)m.getModel("NauczycielModel");
ListIterator<Nauczyciel> it = naucz.getAll().listIterator();
Nauczyciel usun = new Nauczyciel(0, " ", " ");
while(it.hasNext()){
Nauczyciel naucz2 = it.next();
String nazwa = naucz2.nazwisko+" "+naucz2.imie;
if(nazwa.equals(combo1.getSelectedItem().toString())){
usun = naucz2;
}
}
naucz.delete(usun);
showMessageDialog(null, "Usunieto nauczyciela");
view okno = new view();
okno.setVisible(true);
dispose();
}
void usun_klase(){
ModelFactory m = ModelFactory.getInstance();
KlasaModel kl = (KlasaModel)m.getModel("KlasaModel");
ListIterator<Klasa> it = kl.getAll().listIterator();
Klasa usun = new Klasa(0, " ");
while(it.hasNext()){
Klasa kl2 = it.next();
if(kl2.nazwa.equals(combo1.getSelectedItem().toString())){
usun = kl2;
}
}
kl.delete(usun);
showMessageDialog(null, "Usunieto klase");
view okno = new view();
okno.setVisible(true);
dispose();
}
void usun_ucznia(){
ModelFactory m = ModelFactory.getInstance();
UczenModel ucz1 = (UczenModel)m.getModel("UczenModel");
ListIterator<Uczen> it = ucz1.getAll().listIterator();
Uczen usun = new Uczen(0, " ", " ");
while(it.hasNext()){
Uczen ucz2 = it.next();
String nazwa = ucz2.nazwisko+" "+ucz2.imie;
if(nazwa.equals(combo1.getSelectedItem().toString())){
usun = ucz2;
}
}
ucz1.delete(usun);
showMessageDialog(null, "Usunieto ucznia");
view okno = new view();
okno.setVisible(true);
dispose();
}
void zmien_nauczyciela(){
ModelFactory m = ModelFactory.getInstance();
NauczycielModel naucz = (NauczycielModel)m.getModel("NauczycielModel");
ListIterator<Nauczyciel> it = naucz.getAll().listIterator();
int id_nauczyciela = 0;
while(it.hasNext()){
Nauczyciel naucz2 = it.next();
String nazwa = naucz2.nazwisko+" "+naucz2.imie;
if(nazwa.equals(combo2.getSelectedItem().toString())){
id_nauczyciela = naucz2.id;
}
}
PrzedmiotModel przedmioty = (PrzedmiotModel)m.getModel("PrzedmiotModel");
ListIterator<Przedmiot> it2 = przedmioty.getAll().listIterator();
int id_przedmiotu = 0;
while(it2.hasNext()){
Przedmiot przedmiot_iter = it2.next();
String nazwa = przedmiot_iter.nazwa;
if(nazwa.equals(combo1.getSelectedItem().toString())){
id_przedmiotu = przedmiot_iter.id;
}
}
przedmioty.update(przedmioty.get(id_przedmiotu), id_nauczyciela);
showMessageDialog(null, "Zmieniono nauczyciela");
view okno = new view();
okno.setVisible(true);
dispose();
}
void zmien_wychowawce(){
ModelFactory m = ModelFactory.getInstance();
NauczycielModel naucz = (NauczycielModel)m.getModel("NauczycielModel");
ListIterator<Nauczyciel> it = naucz.getAll().listIterator();
int id_nauczyciela = 0;
while(it.hasNext()){
Nauczyciel naucz2 = it.next();
String nazwa = naucz2.nazwisko+" "+naucz2.imie;
if(nazwa.equals(combo1.getSelectedItem().toString())){
id_nauczyciela = naucz2.id;
showMessageDialog(null, id_nauczyciela);
}
}
KlasaModel klasy = (KlasaModel)m.getModel("KlasaModel");
ListIterator<Klasa> it2 = klasy.getAll().listIterator();
int id_klasy = 0;
while(it2.hasNext()){
Klasa klasa_iter = it2.next();
String nazwa = klasa_iter.nazwa;
if(nazwa.equals(jComboBox3.getSelectedItem().toString())){
id_klasy = klasa_iter.id;
showMessageDialog(null, id_klasy);
naucz.update(naucz.get(id_klasy, true), 0);
}
}
naucz.update(naucz.get(id_nauczyciela), id_klasy);
showMessageDialog(null, "Zmieniono wychowawce");
view okno = new view();
okno.setVisible(true);
dispose();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
if(opcja.getText().equals("0"))
dodaj_nauczyciela();
if(opcja.getText().equals("1"))
dodaj_klase();
if(opcja.getText().equals("2"))
dodaj_ucznia();
if(opcja.getText().equals("3"))
usun_nauczyciela();
if(opcja.getText().equals("4"))
usun_klase();
if(opcja.getText().equals("5"))
usun_ucznia();
if(opcja.getText().equals("6"))
zmien_nauczyciela();
if(opcja.getText().equals("7"))
zmien_wychowawce();
}//GEN-LAST:event_jButton1ActionPerformed
private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField3ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField3ActionPerformed
private void ZamknijActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ZamknijActionPerformed
view okno = new view();
okno.setVisible(true);
dispose();
}//GEN-LAST:event_ZamknijActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Opcje.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Opcje.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Opcje.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Opcje.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Opcje().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton Zamknij;
public javax.swing.JComboBox combo1;
public javax.swing.JComboBox combo2;
public javax.swing.JLabel haslo_label;
public javax.swing.JTextField haslo_pole;
public javax.swing.JButton jButton1;
public javax.swing.JCheckBox jCheckBox1;
public javax.swing.JComboBox jComboBox3;
public javax.swing.JLabel jLabel1;
public javax.swing.JLabel jLabel2;
public javax.swing.JLabel jLabel3;
public javax.swing.JTextField jTextField1;
public javax.swing.JTextField jTextField2;
public javax.swing.JTextField jTextField3;
public javax.swing.JLabel label_combo1;
public javax.swing.JLabel label_combo2;
public javax.swing.JLabel opcja;
public javax.swing.JLabel tytul;
// End of variables declaration//GEN-END:variables
}
| //nauczyciele.update(nauczyciele.get(id2, true), 0);
| /*
* 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 pl.projekt5.views;
import java.util.ListIterator;
import pl.projekt5.models.ModelFactory;
import pl.projekt5.models.Nauczyciel;
import pl.projekt5.models.NauczycielModel;
import javax.swing.JOptionPane;
import static javax.swing.JOptionPane.showMessageDialog;
import pl.projekt5.models.Klasa;
import pl.projekt5.models.KlasaModel;
import pl.projekt5.models.Przedmiot;
import pl.projekt5.models.PrzedmiotModel;
import pl.projekt5.models.Uczen;
import pl.projekt5.models.UczenModel;
/**
*
* @author Jacek
*/
public class Opcje extends javax.swing.JFrame {
/**
* Creates new form Opcje
*/
public Opcje() {
initComponents();
ModelFactory m = ModelFactory.getInstance();
KlasaModel klasa1 = (KlasaModel)m.getModel("KlasaModel");
ListIterator<Klasa> it = klasa1.getAll().listIterator();
while(it.hasNext()){
jComboBox3.addItem(it.next().nazwa);
}
if(!jCheckBox1.isSelected())
jComboBox3.setVisible(false);
else
jComboBox3.setVisible(true);
opcja.setVisible(false);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
tytul = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jCheckBox1 = new javax.swing.JCheckBox();
jComboBox3 = new javax.swing.JComboBox();
haslo_label = new javax.swing.JLabel();
haslo_pole = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jTextField3 = new javax.swing.JTextField();
opcja = new javax.swing.JLabel();
combo1 = new javax.swing.JComboBox();
Zamknij = new javax.swing.JButton();
combo2 = new javax.swing.JComboBox();
label_combo1 = new javax.swing.JLabel();
label_combo2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
tytul.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N
tytul.setText("Dodaj/usun nauczyciela klase..");
jLabel2.setText("jLabel2");
jLabel3.setText("jLabel3");
jTextField2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField2ActionPerformed(evt);
}
});
jButton1.setText("Zatwierdz");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jCheckBox1.setText("Wychowawca");
jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBox1ActionPerformed(evt);
}
});
jComboBox3.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Jakiej klasy?" }));
jComboBox3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox3ActionPerformed(evt);
}
});
haslo_label.setText("Haslo");
jLabel1.setText("Przedmiot");
jTextField3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField3ActionPerformed(evt);
}
});
Zamknij.setText("Zamknij");
Zamknij.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ZamknijActionPerformed(evt);
}
});
label_combo1.setText("jLabel4");
label_combo2.setText("jLabel5");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(opcja)
.addGap(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tytul)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jCheckBox1)
.addComponent(jLabel3)
.addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 64, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jTextField1)
.addGap(25, 25, 25)))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(combo1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(label_combo1))
.addGap(25, 25, 25)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(label_combo2)
.addComponent(haslo_pole, javax.swing.GroupLayout.DEFAULT_SIZE, 161, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Zamknij))
.addComponent(jLabel1)
.addComponent(haslo_label)
.addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE, 161, Short.MAX_VALUE)
.addComponent(combo2, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap(91, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(tytul))
.addComponent(opcja))
.addGap(36, 36, 36)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(label_combo1)
.addComponent(label_combo2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(combo1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(combo2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(haslo_label)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(haslo_pole, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jCheckBox1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1)
.addComponent(Zamknij))
.addContainerGap(37, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
void ukryj_wszystko(){
combo1.setVisible(false);
combo2.setVisible(false);
haslo_label.setVisible(false);
haslo_pole.setVisible(false);
jCheckBox1.setVisible(false);
jComboBox3.setVisible(false);
jLabel1.setVisible(false);
jLabel2.setVisible(false);
jLabel3.setVisible(false);
label_combo1.setVisible(false);
label_combo2.setVisible(false);
jTextField1.setVisible(false);
jTextField2.setVisible(false);
jTextField3.setVisible(false);
opcja.setVisible(false);
}
private void jComboBox3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox3ActionPerformed
if(opcja.getText().equals("5")){
ModelFactory m = ModelFactory.getInstance();
String nazwa = jComboBox3.getSelectedItem().toString();
KlasaModel kl = (KlasaModel)m.getModel("KlasaModel");
ListIterator<Klasa> it = kl.getAll().listIterator();
int id = 0;
while(it.hasNext()){
Klasa kl2 = it.next();
if(nazwa.equals(kl2.nazwa)){
id = kl2.id;
}
}
UczenModel uczen1 = (UczenModel)m.getModel("UczenModel");
ListIterator<Uczen> it2 = uczen1.getAll(id).listIterator();
while(it2.hasNext()){
Uczen uczen2 = it2.next();
combo1.addItem(uczen2.nazwisko+" "+uczen2.imie);
}
}
}//GEN-LAST:event_jComboBox3ActionPerformed
private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox1ActionPerformed
if(jCheckBox1.isSelected())
jComboBox3.setVisible(true);
else
jComboBox3.setVisible(false);
}//GEN-LAST:event_jCheckBox1ActionPerformed
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField2ActionPerformed
void dodaj_nauczyciela(){
ModelFactory m = ModelFactory.getInstance();
NauczycielModel nauczyciele = (NauczycielModel)m.getModel("NauczycielModel");
PrzedmiotModel przedmioty = (PrzedmiotModel)m.getModel("PrzedmiotModel");
if(jTextField1.getText().equals("") || jTextField2.getText().equals("") || haslo_pole.getText().equals("")){
showMessageDialog(null, "Sprawdz poprawnosc wpisanych danych");
}
else{
String imie = jTextField1.getText();
String nazwisko = jTextField2.getText();
String haslo = haslo_pole.getText();
Nauczyciel naucz = new Nauczyciel(1, imie, nazwisko);
KlasaModel klasa1 = (KlasaModel)m.getModel("KlasaModel");
ListIterator<Klasa> it = klasa1.getAll().listIterator();
if(jCheckBox1.isSelected()){
int id2=0;
while(it.hasNext()){
if(it.next().nazwa.equals(jComboBox3.getSelectedItem().toString())){
it.previous();
id2 = it.next().id;
//nauczyciele.update(nauczyciele.get(id2, true), <SUF>
}
}
nauczyciele.add(naucz, haslo, id2);
}
else{
nauczyciele.add(naucz, haslo);
}
ListIterator<Nauczyciel> int2 = nauczyciele.getAll().listIterator();
int idd=0;
while(int2.hasNext()){
idd = int2.next().id;
}
if(!jTextField3.getText().equals("")) {
Przedmiot przed = new Przedmiot(1, jTextField3.getText());
przedmioty.add(przed, idd);
}
showMessageDialog(null, "Dodano nauczyciela");
view okno = new view();
okno.setVisible(true);
dispose();
}
}
void dodaj_klase(){
ModelFactory m = ModelFactory.getInstance();
KlasaModel klasy = (KlasaModel)m.getModel("KlasaModel");
if(jTextField1.getText().equals("")){
showMessageDialog(null, "Pole z nazwa klasy jest puste");
}
else{
String nazwa = jTextField1.getText();
boolean flaga=false;
KlasaModel klasa1 = (KlasaModel)m.getModel("KlasaModel");
ListIterator<Klasa> it = klasa1.getAll().listIterator();
while(it.hasNext()){
if(it.next().nazwa.equals(nazwa)){
flaga = true;
}
}
if(flaga){
showMessageDialog(null, "W bazie zajduje sie juz klasa o takiej nazwie");
}
else{
Klasa kl = new Klasa(1, nazwa);
klasy.add(kl);
showMessageDialog(null, "Dodano klase");
view okno = new view();
okno.setVisible(true);
dispose();
}
}
}
void dodaj_ucznia(){
if(jTextField1.getText().equals("") || jTextField2.getText().equals("")){
showMessageDialog(null, "Sprawdz poprawnosc wpisanych danych");
}
else{
ModelFactory m = ModelFactory.getInstance();
KlasaModel klasa1 = (KlasaModel)m.getModel("KlasaModel");
ListIterator<Klasa> it = klasa1.getAll().listIterator();
int id=0;
while(it.hasNext()){
if(it.next().nazwa.equals(jComboBox3.getSelectedItem().toString())){
it.previous();
id = it.next().id;
}
}
Uczen ucz = new Uczen(1, jTextField1.getText(), jTextField2.getText());
UczenModel uczniowie = (UczenModel)m.getModel("UczenModel");
uczniowie.add(ucz, id);
showMessageDialog(null, "Dodano ucznia");
view okno = new view();
okno.setVisible(true);
dispose();
}
}
void usun_nauczyciela(){
ModelFactory m = ModelFactory.getInstance();
NauczycielModel naucz = (NauczycielModel)m.getModel("NauczycielModel");
ListIterator<Nauczyciel> it = naucz.getAll().listIterator();
Nauczyciel usun = new Nauczyciel(0, " ", " ");
while(it.hasNext()){
Nauczyciel naucz2 = it.next();
String nazwa = naucz2.nazwisko+" "+naucz2.imie;
if(nazwa.equals(combo1.getSelectedItem().toString())){
usun = naucz2;
}
}
naucz.delete(usun);
showMessageDialog(null, "Usunieto nauczyciela");
view okno = new view();
okno.setVisible(true);
dispose();
}
void usun_klase(){
ModelFactory m = ModelFactory.getInstance();
KlasaModel kl = (KlasaModel)m.getModel("KlasaModel");
ListIterator<Klasa> it = kl.getAll().listIterator();
Klasa usun = new Klasa(0, " ");
while(it.hasNext()){
Klasa kl2 = it.next();
if(kl2.nazwa.equals(combo1.getSelectedItem().toString())){
usun = kl2;
}
}
kl.delete(usun);
showMessageDialog(null, "Usunieto klase");
view okno = new view();
okno.setVisible(true);
dispose();
}
void usun_ucznia(){
ModelFactory m = ModelFactory.getInstance();
UczenModel ucz1 = (UczenModel)m.getModel("UczenModel");
ListIterator<Uczen> it = ucz1.getAll().listIterator();
Uczen usun = new Uczen(0, " ", " ");
while(it.hasNext()){
Uczen ucz2 = it.next();
String nazwa = ucz2.nazwisko+" "+ucz2.imie;
if(nazwa.equals(combo1.getSelectedItem().toString())){
usun = ucz2;
}
}
ucz1.delete(usun);
showMessageDialog(null, "Usunieto ucznia");
view okno = new view();
okno.setVisible(true);
dispose();
}
void zmien_nauczyciela(){
ModelFactory m = ModelFactory.getInstance();
NauczycielModel naucz = (NauczycielModel)m.getModel("NauczycielModel");
ListIterator<Nauczyciel> it = naucz.getAll().listIterator();
int id_nauczyciela = 0;
while(it.hasNext()){
Nauczyciel naucz2 = it.next();
String nazwa = naucz2.nazwisko+" "+naucz2.imie;
if(nazwa.equals(combo2.getSelectedItem().toString())){
id_nauczyciela = naucz2.id;
}
}
PrzedmiotModel przedmioty = (PrzedmiotModel)m.getModel("PrzedmiotModel");
ListIterator<Przedmiot> it2 = przedmioty.getAll().listIterator();
int id_przedmiotu = 0;
while(it2.hasNext()){
Przedmiot przedmiot_iter = it2.next();
String nazwa = przedmiot_iter.nazwa;
if(nazwa.equals(combo1.getSelectedItem().toString())){
id_przedmiotu = przedmiot_iter.id;
}
}
przedmioty.update(przedmioty.get(id_przedmiotu), id_nauczyciela);
showMessageDialog(null, "Zmieniono nauczyciela");
view okno = new view();
okno.setVisible(true);
dispose();
}
void zmien_wychowawce(){
ModelFactory m = ModelFactory.getInstance();
NauczycielModel naucz = (NauczycielModel)m.getModel("NauczycielModel");
ListIterator<Nauczyciel> it = naucz.getAll().listIterator();
int id_nauczyciela = 0;
while(it.hasNext()){
Nauczyciel naucz2 = it.next();
String nazwa = naucz2.nazwisko+" "+naucz2.imie;
if(nazwa.equals(combo1.getSelectedItem().toString())){
id_nauczyciela = naucz2.id;
showMessageDialog(null, id_nauczyciela);
}
}
KlasaModel klasy = (KlasaModel)m.getModel("KlasaModel");
ListIterator<Klasa> it2 = klasy.getAll().listIterator();
int id_klasy = 0;
while(it2.hasNext()){
Klasa klasa_iter = it2.next();
String nazwa = klasa_iter.nazwa;
if(nazwa.equals(jComboBox3.getSelectedItem().toString())){
id_klasy = klasa_iter.id;
showMessageDialog(null, id_klasy);
naucz.update(naucz.get(id_klasy, true), 0);
}
}
naucz.update(naucz.get(id_nauczyciela), id_klasy);
showMessageDialog(null, "Zmieniono wychowawce");
view okno = new view();
okno.setVisible(true);
dispose();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
if(opcja.getText().equals("0"))
dodaj_nauczyciela();
if(opcja.getText().equals("1"))
dodaj_klase();
if(opcja.getText().equals("2"))
dodaj_ucznia();
if(opcja.getText().equals("3"))
usun_nauczyciela();
if(opcja.getText().equals("4"))
usun_klase();
if(opcja.getText().equals("5"))
usun_ucznia();
if(opcja.getText().equals("6"))
zmien_nauczyciela();
if(opcja.getText().equals("7"))
zmien_wychowawce();
}//GEN-LAST:event_jButton1ActionPerformed
private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField3ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField3ActionPerformed
private void ZamknijActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ZamknijActionPerformed
view okno = new view();
okno.setVisible(true);
dispose();
}//GEN-LAST:event_ZamknijActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Opcje.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Opcje.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Opcje.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Opcje.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Opcje().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton Zamknij;
public javax.swing.JComboBox combo1;
public javax.swing.JComboBox combo2;
public javax.swing.JLabel haslo_label;
public javax.swing.JTextField haslo_pole;
public javax.swing.JButton jButton1;
public javax.swing.JCheckBox jCheckBox1;
public javax.swing.JComboBox jComboBox3;
public javax.swing.JLabel jLabel1;
public javax.swing.JLabel jLabel2;
public javax.swing.JLabel jLabel3;
public javax.swing.JTextField jTextField1;
public javax.swing.JTextField jTextField2;
public javax.swing.JTextField jTextField3;
public javax.swing.JLabel label_combo1;
public javax.swing.JLabel label_combo2;
public javax.swing.JLabel opcja;
public javax.swing.JLabel tytul;
// End of variables declaration//GEN-END:variables
}
| null |
619_9 | BrainTech/svarog | 1,020 | svarog/src/main/java/org/signalml/domain/tag/TagDifferenceSet.java | /* TagDifferenceSet.java created 2007-11-14
*
*/
package org.signalml.domain.tag;
import java.util.Collection;
import java.util.SortedSet;
import java.util.TreeSet;
import org.signalml.plugin.export.signal.SignalSelectionType;
import org.signalml.plugin.export.signal.Tag;
/**
* This class represents a set of {@link TagDifference differences} between
* {@link Tag tags}.
* Allows to find which differences are located between two points in time.
*
* @author Michal Dobaczewski © 2007-2008 CC Otwarte Systemy Komputerowe Sp. z o.o.
*/
public class TagDifferenceSet {
/**
* the actual set containing tag {@link TagDifference differences}
*/
private TreeSet<TagDifference> differences;
/**
* the length of the longest {@link TagDifference differences}
*/
private double maxDifferenceLength = 0;
/**
* Constructor. Creates an empty TagDifferenceSet.
*/
public TagDifferenceSet() {
differences = new TreeSet<TagDifference>();
}
/**
* Constructor. Creates a TagDifferenceSet with given
* {@link TagDifference differences}.
* @param differences the set of differences to be added
*/
public TagDifferenceSet(TreeSet<TagDifference> differences) {
this.differences = differences;
calculateMaxTagLength();
}
/**
* Returns the set containing {@link TagDifference tag differences}.
* @return the set containing tag differences
*/
public TreeSet<TagDifference> getDifferences() {
return differences;
}
/**
* Adds the given collection of {@link TagDifference tag differences}
* to this set.
* @param toAdd the collection of tag differences
*/
public void addDifferences(Collection<TagDifference> toAdd) {
differences.addAll(toAdd);
calculateMaxTagLength();
}
/**
* Returns the set of {@link TagDifference differences} for
* {@link Tag tagged selections} that start between
* <code>start-maxDifferenceLength</code> (inclusive)
* and <code>end</code> (inclusive).
* @param start the starting position of the interval
* @param end the ending position of the interval
* @return the set of differences for tagged selections
* that start between <code>start-maxDifferenceLength</code> (inclusive)
* and <code>end</code> (inclusive)
*/
//TODO czy to na pewno ma zwracać to co napisałem, wydawało mi się, że mają to być różnice przecinające się z przedziałem, ale tu mogą się załapać także znajdujące się przed nim (i krótsze od maksymalnego)
public SortedSet<TagDifference> getDifferencesBetween(double start, double end) {
TagDifference startMarker = new TagDifference(SignalSelectionType.CHANNEL, start-maxDifferenceLength, 0, null);
TagDifference endMarker = new TagDifference(SignalSelectionType.CHANNEL,end, Double.MAX_VALUE,null); // note that lengths matter, so that all tags starting at exactly end will be selected
return differences.subSet(startMarker, true, endMarker, true);
}
/**
* Calculates the maximal length of the difference in this set.
*/
private void calculateMaxTagLength() {
double maxDifferenceLength = 0;
for (TagDifference difference : differences) {
if (maxDifferenceLength < difference.getLength()) {
maxDifferenceLength = difference.getLength();
}
}
this.maxDifferenceLength = maxDifferenceLength;
}
}
| //TODO czy to na pewno ma zwracać to co napisałem, wydawało mi się, że mają to być różnice przecinające się z przedziałem, ale tu mogą się załapać także znajdujące się przed nim (i krótsze od maksymalnego) | /* TagDifferenceSet.java created 2007-11-14
*
*/
package org.signalml.domain.tag;
import java.util.Collection;
import java.util.SortedSet;
import java.util.TreeSet;
import org.signalml.plugin.export.signal.SignalSelectionType;
import org.signalml.plugin.export.signal.Tag;
/**
* This class represents a set of {@link TagDifference differences} between
* {@link Tag tags}.
* Allows to find which differences are located between two points in time.
*
* @author Michal Dobaczewski © 2007-2008 CC Otwarte Systemy Komputerowe Sp. z o.o.
*/
public class TagDifferenceSet {
/**
* the actual set containing tag {@link TagDifference differences}
*/
private TreeSet<TagDifference> differences;
/**
* the length of the longest {@link TagDifference differences}
*/
private double maxDifferenceLength = 0;
/**
* Constructor. Creates an empty TagDifferenceSet.
*/
public TagDifferenceSet() {
differences = new TreeSet<TagDifference>();
}
/**
* Constructor. Creates a TagDifferenceSet with given
* {@link TagDifference differences}.
* @param differences the set of differences to be added
*/
public TagDifferenceSet(TreeSet<TagDifference> differences) {
this.differences = differences;
calculateMaxTagLength();
}
/**
* Returns the set containing {@link TagDifference tag differences}.
* @return the set containing tag differences
*/
public TreeSet<TagDifference> getDifferences() {
return differences;
}
/**
* Adds the given collection of {@link TagDifference tag differences}
* to this set.
* @param toAdd the collection of tag differences
*/
public void addDifferences(Collection<TagDifference> toAdd) {
differences.addAll(toAdd);
calculateMaxTagLength();
}
/**
* Returns the set of {@link TagDifference differences} for
* {@link Tag tagged selections} that start between
* <code>start-maxDifferenceLength</code> (inclusive)
* and <code>end</code> (inclusive).
* @param start the starting position of the interval
* @param end the ending position of the interval
* @return the set of differences for tagged selections
* that start between <code>start-maxDifferenceLength</code> (inclusive)
* and <code>end</code> (inclusive)
*/
//TODO czy <SUF>
public SortedSet<TagDifference> getDifferencesBetween(double start, double end) {
TagDifference startMarker = new TagDifference(SignalSelectionType.CHANNEL, start-maxDifferenceLength, 0, null);
TagDifference endMarker = new TagDifference(SignalSelectionType.CHANNEL,end, Double.MAX_VALUE,null); // note that lengths matter, so that all tags starting at exactly end will be selected
return differences.subSet(startMarker, true, endMarker, true);
}
/**
* Calculates the maximal length of the difference in this set.
*/
private void calculateMaxTagLength() {
double maxDifferenceLength = 0;
for (TagDifference difference : differences) {
if (maxDifferenceLength < difference.getLength()) {
maxDifferenceLength = difference.getLength();
}
}
this.maxDifferenceLength = maxDifferenceLength;
}
}
| null |
6330_0 | Brzusko/WST_zadania_wbrzuszkiewicz | 59 | src/main/java/Zadanie_5.java | import java.util.Random;
public class Zadanie_5 {
//Przepraszam, ale nie ogarniam o co chodzi w tym zadaniu. Jest bardzo niejasno napisane.
}
| //Przepraszam, ale nie ogarniam o co chodzi w tym zadaniu. Jest bardzo niejasno napisane. | import java.util.Random;
public class Zadanie_5 {
//Przepraszam, ale <SUF>
}
| null |
9896_0 | Bymbacz/Library-Management-Application | 622 | src/main/java/library/proj/model/Person.java | package library.proj.model;
import jakarta.persistence.*;
import lombok.Getter;
import java.util.ArrayList;
import java.util.List;
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Getter
private int id;
@Getter
private String firstName;
@Getter
private String lastName;
@Getter
@Column(unique = true)
private String email;
@Getter
private String password;
private int permissions;
@Getter
// TODO: przy lazy ładowaniu wywala błędy, na razie dałem eager, ale może da się to jakoś mądrzej zrobić
@OneToMany(fetch = FetchType.EAGER, mappedBy = "person", cascade = CascadeType.ALL)
private List<Rental> rentals;
@OneToMany(mappedBy = "person", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Rating> ratings;
@OneToMany(mappedBy = "person", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Reservation> reservations;
public Person() {
}
public Person(String firstName, String lastName, String email, String password, Permissions permissions) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
this.permissions = permissions.ordinal();
}
public String getFullName() { return firstName + " " + lastName; }
public Permissions getPermissions() {return Permissions.values()[permissions];}
public String toString() {
return getFullName() + " | " + Permissions.values()[permissions];
}
public void registerRental(Rental rental) {
if (rentals == null)
rentals = new ArrayList<>();
rentals.add(rental);
}
public void addRating(Rating rating) {
if (ratings == null)
ratings = new ArrayList<>();
ratings.add(rating);
}
public void addReservation(Reservation reservation) {
if (reservations == null)
reservations = new ArrayList<>();
reservations.add(reservation);
}
}
| // TODO: przy lazy ładowaniu wywala błędy, na razie dałem eager, ale może da się to jakoś mądrzej zrobić | package library.proj.model;
import jakarta.persistence.*;
import lombok.Getter;
import java.util.ArrayList;
import java.util.List;
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Getter
private int id;
@Getter
private String firstName;
@Getter
private String lastName;
@Getter
@Column(unique = true)
private String email;
@Getter
private String password;
private int permissions;
@Getter
// TODO: przy <SUF>
@OneToMany(fetch = FetchType.EAGER, mappedBy = "person", cascade = CascadeType.ALL)
private List<Rental> rentals;
@OneToMany(mappedBy = "person", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Rating> ratings;
@OneToMany(mappedBy = "person", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Reservation> reservations;
public Person() {
}
public Person(String firstName, String lastName, String email, String password, Permissions permissions) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
this.permissions = permissions.ordinal();
}
public String getFullName() { return firstName + " " + lastName; }
public Permissions getPermissions() {return Permissions.values()[permissions];}
public String toString() {
return getFullName() + " | " + Permissions.values()[permissions];
}
public void registerRental(Rental rental) {
if (rentals == null)
rentals = new ArrayList<>();
rentals.add(rental);
}
public void addRating(Rating rating) {
if (ratings == null)
ratings = new ArrayList<>();
ratings.add(rating);
}
public void addReservation(Reservation reservation) {
if (reservations == null)
reservations = new ArrayList<>();
reservations.add(reservation);
}
}
| null |
7681_0 | CichyWonder/Java-Poj-PJATK | 4,463 | CYBERSNAKE2077/src/App/Game.java | package App;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.paint.ImagePattern;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Game extends Main{
private Control control = new Control();
private GridPane GameGrid = new GridPane();
private GridPane TextGrid = new GridPane();
private int GridSizeSquared = 49;
Label Score = new Label(" Wynik: 0");
Label GameOver = new Label();
Label Pause = new Label(" Wciśnij dowolny przycisk \n żeby zacząć");
Label ControlU= new Label(" ["+control.getUp()+"/GÓRA]");
Label ControlD= new Label(" ["+control.getDown()+"/DÓŁ]");
Label ControlL= new Label(" ["+control.getLeft()+"/LEWO] ");
Label ControlR= new Label(" ["+control.getRight()+"/PRAWO]");
Label Close = new Label(" Wciśnij ESC żeby wyjść");
Label Nick= new Label("Podaj swój nick");
TextField User = new TextField();
Button Submit = new Button("Wyślij wynik");
private ArrayList<Snake> SnakeP = new ArrayList<>(0);
private Timeline Loop;
//Jak często pętla jest odświeżana
//1/15 seconds == 15fps
private double LoopSpeed = 1/15.0;
//movementX and movementY, wskazują one kierunek głowy węża
private int mX = 0, mY = 0;
//Pozycja głowy podczas startu
private int posX = new Random().nextInt(GridSizeSquared), posY =new Random().nextInt(GridSizeSquared);
private Rectangle Food = fillFoodwithimage();
//Trzyma Wynik
private int foodN = 0;
//Losowa pozycja jedzenia na planszy
private int FoodPosX = new Random().nextInt(GridSizeSquared);
private int FoodPosY = new Random().nextInt(GridSizeSquared);
//True = Gra chodzi
//False = Gra jest zapauzowana
private boolean start = false;
private boolean dead = false;
public void start(Stage PrimaryStage)
{
FillGrid(GameGrid);
//Tworzy głowę
SnakeP.add(new Snake(posX, posY));
GameGrid.setAlignment(Pos.CENTER);
TextGrid.setAlignment(Pos.CENTER);
//Ustawia jedzienie i głowę na mapie
GameGrid.add(Food, FoodPosX,FoodPosY);
GameGrid.add(SnakeP.get(0).body, posX,posY);
TextGrid.add(Score, 0, 1,1,2);
TextGrid.add(GameOver, 0, 4,1,2);
TextGrid.add(Pause, 0, 7,1,2);
TextGrid.add(ControlU, 0, 10,1,2);
TextGrid.add(ControlL, 0, 13,1,2);
TextGrid.add(ControlD, 0, 16,1,2);
TextGrid.add(ControlR, 0, 19,1,2);
TextGrid.add(Close, 0, 22, 2, 2);
Score.setId("Score");
Score.setAlignment(Pos.CENTER);
Pause.centerShapeProperty();
User.setId("User");
Submit.setId("Submit");
FlowPane Screen = new FlowPane(Orientation.VERTICAL,GameGrid, TextGrid);
TextGrid.setPrefHeight(200);
Screen.setId("Scene");
GameGrid.setId("GameGrid");
TextGrid.setId("TextGrid");
Scene Game = new Scene(Screen, 1167 ,800);
//Sprawdza jakie przyciski są wpisane
Game.setOnKeyPressed(this::KeyPressedProcess);
PrimaryStage.setTitle("CYBERSNAKE2077");
PrimaryStage.setScene(Game);
Game.getStylesheets().add(getClass().getResource("Resources/css/Game.css").toExternalForm());
PrimaryStage.show();
//Tworzy pętle gry
Loop = new Timeline(new KeyFrame(Duration.seconds(LoopSpeed),
new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent event) {
//Metoda sterowania wężem
MoveChar();
}
}));
Loop.setCycleCount(Timeline.INDEFINITE);
}
public void MoveChar()
{
//if-else gdy wąż walnie w ścianę
//if sam siebie zje
if(mX == -1 && (posX == 0))
{Die();
mX =0;
}
else if(mY == -1 && (posY == 0))
{ Die();
mY =0;
}
else if(mX == 1 && (posX == GridSizeSquared-1))
{ Die(); mX =0;}
else if(mY == 1 && (posY == GridSizeSquared-1))
{Die(); mY =0; }
else
{
//aktualizuje pozycje głowy
GameGrid.getChildren().remove(SnakeP.get(0).body);
posX+=mX;
posY+=mY;
GameGrid.add(SnakeP.get(0).body, posX,posY);
SnakeP.get(0).setPos(posX,posY);
//Aktualizuje resztę ciałą
if(SnakeP.size() > 1)
{
for(int x = 1; x<SnakeP.size();x++)
{
GameGrid.getChildren().remove(SnakeP.get(x).body);
GameGrid.add(SnakeP.get(x).body, SnakeP.get(x-1).getOldXpos(),SnakeP.get(x-1).getOldYpos());
SnakeP.get(x).setPos(SnakeP.get(x-1).getOldXpos(),SnakeP.get(x-1).getOldYpos());
}
}
//jeżeli wąż zje to rośnie
if(posX == FoodPosX && posY == FoodPosY)
{
Grow();
}
//If sam siebie zje to umiera
for(int x = 1; x<SnakeP.size();x++)
{
if(posX == SnakeP.get(x).getXpos() && posY == SnakeP.get(x).getYpos() )
{
Die();
}
}
}
}
//Detekcja przycisków
public void KeyPressedProcess(KeyEvent event)
{
if(start == false && dead && event.getCode()== KeyCode.ENTER)
{
Pause.setText("Naciśnij Enter żeby zapauzować");
Score.setText("Wynik: 0");
GameOver.setText("");
Loop.play();
start = true;
dead = false;
}
else if(start == false && dead == false)
{
Pause.setText("Wciśnij Enter żeby zapauzować");
Loop.play();
start = true;
}
if (event.getCode() == KeyCode.ENTER)
{
Pause.setText("Wciśnij dowolny przycisk żeby wznowić");
TextGrid.disabledProperty();
Loop.stop();
start = false;
}
if(mY ==0 && (event.getCode() == KeyCode.valueOf(control.getUp()) || event.getCode() == KeyCode.UP))
{
mX = 0;
mY = -1;
}
else if(mY == 0 && (event.getCode() == KeyCode.valueOf(control.getDown()) || event.getCode() == KeyCode.DOWN))
{
mX = 0;
mY = 1;
}
else if(mX ==0 && (event.getCode() == KeyCode.valueOf(control.getLeft()) || event.getCode() == KeyCode.LEFT))
{
mX = -1;
mY = 0;
}
else if(mX == 0 && (event.getCode() == KeyCode.valueOf(control.getRight()) || event.getCode() == KeyCode.RIGHT))
{
mX = 1;
mY = 0;
}
if(event.getCode() == KeyCode.ESCAPE)
System.exit(0);
}
//Uzupełnia siatkę prostokątami
public void FillGrid(GridPane GameGrid)
{
for(int x =0;x<GridSizeSquared;x++)
{
GameGrid.addColumn(x,new Rectangle(16,16, Color.TRANSPARENT));
for(int y = 1; y < GridSizeSquared;y++)
GameGrid.addRow(y,new Rectangle(16,16, Color.TRANSPARENT));
}
}
//Randomowo zmienia pozycje jedzenia
public void PlaceFood()
{
Random rPos = new Random();
int newPosX = rPos.nextInt(GridSizeSquared);
int newPosY = rPos.nextInt(GridSizeSquared);
FoodPosX = newPosX;
FoodPosY = newPosY;
GameGrid.getChildren().remove(Food);
GameGrid.add(Food, newPosX,newPosY);
}
public void Grow()
{
//dodaje nową część ogona i sprawdza gdzie była poprzednia
SnakeP.add(new Snake(SnakeP.get(SnakeP.size()-1).getOldXpos(),
SnakeP.get(SnakeP.size()-1).getOldYpos()));
GameGrid.add(SnakeP.get(SnakeP.size()-1).body,
SnakeP.get(SnakeP.size()-1).getOldXpos(),
SnakeP.get(SnakeP.size()-1).getOldYpos());
foodN=foodN+100;
Score.setText(" Wynik: " + foodN);
//Zwiększa wynik
//Randomowo umieszca jedzenie
PlaceFood();
}
//Game Over
public void Die()
{
int size = SnakeP.size();
//Usuwa węża
for(int x = size-1; x>0;x--)
GameGrid.getChildren().remove(SnakeP.get(x).body);
//Usuwa głowę
for(int x = size-1; x>0;x--)
SnakeP.remove(x);
start = false;
dead = true;
Loop.stop();
HighScore();
GameOver.setText(" Koniec gry, Chcesz zacząć od początku?");
Pause.setText(" Wciśnij Enter żeby zrestartować");
//Nowa pozycja dla węża
posX = new Random().nextInt(GridSizeSquared);
posY = new Random().nextInt(GridSizeSquared);
//Umieszcza węża na siatce
GameGrid.getChildren().remove(SnakeP.get(0).body);
GameGrid.add(SnakeP.get(0).body,posX,posY);
SnakeP.get(0).setPos(posX,posY);
foodN = 0;
}
public void HighScore() {
TextGrid.add(Nick, 0, 25, 1, 2);
TextGrid.add(User, 0, 28, 1, 2);
TextGrid.add(Submit, 0, 31, 1, 2);
Submit.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
String nick = User.getText();
try {
HighScoreWriter(nick);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
TextGrid.getChildren().remove(User);
TextGrid.getChildren().remove(Submit);
TextGrid.getChildren().remove(Nick);
}
});
}
// do poprawienia
public void HighScoreWriter(String nick) throws FileNotFoundException {
int[] fiveBestScores = new int[6];
File file = new File("src/App/Resources/css/Highscores.txt");
Scanner scanner = new Scanner(file);
String str = "";
while (scanner.hasNextLine()){ str += scanner.nextLine() + "\n"; }
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(str);
int i=0;
while (matcher.find()){
fiveBestScores[i] = Integer.parseInt(matcher.group());
i++;
}
FileWriter fr = null;
try{
fr = new FileWriter(file);
if (foodN > fiveBestScores[0]){ fr.write(str.replaceAll("a\\)\\s\\d+\\spkt","a) " + foodN + " pkt"+ " "+ nick)); }
else if (foodN > fiveBestScores[1]){ fr.write(str.replaceAll("b\\)\\s\\d+\\spkt","b) " + foodN +" pkt" + " "+ nick)); }
else if (foodN > fiveBestScores[2]){ fr.write(str.replaceAll("c\\)\\s\\d+\\spkt","c) " + foodN +" pkt"+ " "+ nick)); }
else if (foodN > fiveBestScores[3]){ fr.write(str.replaceAll("d\\)\\s\\d+\\spkt","d) " + foodN + "pkt"+ " "+ nick)); }
else if (foodN > fiveBestScores[4]){ fr.write(str.replaceAll("e\\)\\s\\d+\\spkt","e) " + foodN +" pkt" +" "+ nick)); }
else { fr.write(str); }
} catch (IOException e) { e.printStackTrace(); }
finally { try { fr.close(); } catch (IOException e) { e.printStackTrace(); } }
}
public Rectangle fillFoodwithimage(){
File path = new File("src/App/Resources/css/bolt.png");
Image image = new Image(path.toURI().toString());
Rectangle body = new Rectangle(16,16);
body.setFill(new ImagePattern(image));
return body;
}
}
| //Jak często pętla jest odświeżana
| package App;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.paint.ImagePattern;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Game extends Main{
private Control control = new Control();
private GridPane GameGrid = new GridPane();
private GridPane TextGrid = new GridPane();
private int GridSizeSquared = 49;
Label Score = new Label(" Wynik: 0");
Label GameOver = new Label();
Label Pause = new Label(" Wciśnij dowolny przycisk \n żeby zacząć");
Label ControlU= new Label(" ["+control.getUp()+"/GÓRA]");
Label ControlD= new Label(" ["+control.getDown()+"/DÓŁ]");
Label ControlL= new Label(" ["+control.getLeft()+"/LEWO] ");
Label ControlR= new Label(" ["+control.getRight()+"/PRAWO]");
Label Close = new Label(" Wciśnij ESC żeby wyjść");
Label Nick= new Label("Podaj swój nick");
TextField User = new TextField();
Button Submit = new Button("Wyślij wynik");
private ArrayList<Snake> SnakeP = new ArrayList<>(0);
private Timeline Loop;
//Jak często <SUF>
//1/15 seconds == 15fps
private double LoopSpeed = 1/15.0;
//movementX and movementY, wskazują one kierunek głowy węża
private int mX = 0, mY = 0;
//Pozycja głowy podczas startu
private int posX = new Random().nextInt(GridSizeSquared), posY =new Random().nextInt(GridSizeSquared);
private Rectangle Food = fillFoodwithimage();
//Trzyma Wynik
private int foodN = 0;
//Losowa pozycja jedzenia na planszy
private int FoodPosX = new Random().nextInt(GridSizeSquared);
private int FoodPosY = new Random().nextInt(GridSizeSquared);
//True = Gra chodzi
//False = Gra jest zapauzowana
private boolean start = false;
private boolean dead = false;
public void start(Stage PrimaryStage)
{
FillGrid(GameGrid);
//Tworzy głowę
SnakeP.add(new Snake(posX, posY));
GameGrid.setAlignment(Pos.CENTER);
TextGrid.setAlignment(Pos.CENTER);
//Ustawia jedzienie i głowę na mapie
GameGrid.add(Food, FoodPosX,FoodPosY);
GameGrid.add(SnakeP.get(0).body, posX,posY);
TextGrid.add(Score, 0, 1,1,2);
TextGrid.add(GameOver, 0, 4,1,2);
TextGrid.add(Pause, 0, 7,1,2);
TextGrid.add(ControlU, 0, 10,1,2);
TextGrid.add(ControlL, 0, 13,1,2);
TextGrid.add(ControlD, 0, 16,1,2);
TextGrid.add(ControlR, 0, 19,1,2);
TextGrid.add(Close, 0, 22, 2, 2);
Score.setId("Score");
Score.setAlignment(Pos.CENTER);
Pause.centerShapeProperty();
User.setId("User");
Submit.setId("Submit");
FlowPane Screen = new FlowPane(Orientation.VERTICAL,GameGrid, TextGrid);
TextGrid.setPrefHeight(200);
Screen.setId("Scene");
GameGrid.setId("GameGrid");
TextGrid.setId("TextGrid");
Scene Game = new Scene(Screen, 1167 ,800);
//Sprawdza jakie przyciski są wpisane
Game.setOnKeyPressed(this::KeyPressedProcess);
PrimaryStage.setTitle("CYBERSNAKE2077");
PrimaryStage.setScene(Game);
Game.getStylesheets().add(getClass().getResource("Resources/css/Game.css").toExternalForm());
PrimaryStage.show();
//Tworzy pętle gry
Loop = new Timeline(new KeyFrame(Duration.seconds(LoopSpeed),
new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent event) {
//Metoda sterowania wężem
MoveChar();
}
}));
Loop.setCycleCount(Timeline.INDEFINITE);
}
public void MoveChar()
{
//if-else gdy wąż walnie w ścianę
//if sam siebie zje
if(mX == -1 && (posX == 0))
{Die();
mX =0;
}
else if(mY == -1 && (posY == 0))
{ Die();
mY =0;
}
else if(mX == 1 && (posX == GridSizeSquared-1))
{ Die(); mX =0;}
else if(mY == 1 && (posY == GridSizeSquared-1))
{Die(); mY =0; }
else
{
//aktualizuje pozycje głowy
GameGrid.getChildren().remove(SnakeP.get(0).body);
posX+=mX;
posY+=mY;
GameGrid.add(SnakeP.get(0).body, posX,posY);
SnakeP.get(0).setPos(posX,posY);
//Aktualizuje resztę ciałą
if(SnakeP.size() > 1)
{
for(int x = 1; x<SnakeP.size();x++)
{
GameGrid.getChildren().remove(SnakeP.get(x).body);
GameGrid.add(SnakeP.get(x).body, SnakeP.get(x-1).getOldXpos(),SnakeP.get(x-1).getOldYpos());
SnakeP.get(x).setPos(SnakeP.get(x-1).getOldXpos(),SnakeP.get(x-1).getOldYpos());
}
}
//jeżeli wąż zje to rośnie
if(posX == FoodPosX && posY == FoodPosY)
{
Grow();
}
//If sam siebie zje to umiera
for(int x = 1; x<SnakeP.size();x++)
{
if(posX == SnakeP.get(x).getXpos() && posY == SnakeP.get(x).getYpos() )
{
Die();
}
}
}
}
//Detekcja przycisków
public void KeyPressedProcess(KeyEvent event)
{
if(start == false && dead && event.getCode()== KeyCode.ENTER)
{
Pause.setText("Naciśnij Enter żeby zapauzować");
Score.setText("Wynik: 0");
GameOver.setText("");
Loop.play();
start = true;
dead = false;
}
else if(start == false && dead == false)
{
Pause.setText("Wciśnij Enter żeby zapauzować");
Loop.play();
start = true;
}
if (event.getCode() == KeyCode.ENTER)
{
Pause.setText("Wciśnij dowolny przycisk żeby wznowić");
TextGrid.disabledProperty();
Loop.stop();
start = false;
}
if(mY ==0 && (event.getCode() == KeyCode.valueOf(control.getUp()) || event.getCode() == KeyCode.UP))
{
mX = 0;
mY = -1;
}
else if(mY == 0 && (event.getCode() == KeyCode.valueOf(control.getDown()) || event.getCode() == KeyCode.DOWN))
{
mX = 0;
mY = 1;
}
else if(mX ==0 && (event.getCode() == KeyCode.valueOf(control.getLeft()) || event.getCode() == KeyCode.LEFT))
{
mX = -1;
mY = 0;
}
else if(mX == 0 && (event.getCode() == KeyCode.valueOf(control.getRight()) || event.getCode() == KeyCode.RIGHT))
{
mX = 1;
mY = 0;
}
if(event.getCode() == KeyCode.ESCAPE)
System.exit(0);
}
//Uzupełnia siatkę prostokątami
public void FillGrid(GridPane GameGrid)
{
for(int x =0;x<GridSizeSquared;x++)
{
GameGrid.addColumn(x,new Rectangle(16,16, Color.TRANSPARENT));
for(int y = 1; y < GridSizeSquared;y++)
GameGrid.addRow(y,new Rectangle(16,16, Color.TRANSPARENT));
}
}
//Randomowo zmienia pozycje jedzenia
public void PlaceFood()
{
Random rPos = new Random();
int newPosX = rPos.nextInt(GridSizeSquared);
int newPosY = rPos.nextInt(GridSizeSquared);
FoodPosX = newPosX;
FoodPosY = newPosY;
GameGrid.getChildren().remove(Food);
GameGrid.add(Food, newPosX,newPosY);
}
public void Grow()
{
//dodaje nową część ogona i sprawdza gdzie była poprzednia
SnakeP.add(new Snake(SnakeP.get(SnakeP.size()-1).getOldXpos(),
SnakeP.get(SnakeP.size()-1).getOldYpos()));
GameGrid.add(SnakeP.get(SnakeP.size()-1).body,
SnakeP.get(SnakeP.size()-1).getOldXpos(),
SnakeP.get(SnakeP.size()-1).getOldYpos());
foodN=foodN+100;
Score.setText(" Wynik: " + foodN);
//Zwiększa wynik
//Randomowo umieszca jedzenie
PlaceFood();
}
//Game Over
public void Die()
{
int size = SnakeP.size();
//Usuwa węża
for(int x = size-1; x>0;x--)
GameGrid.getChildren().remove(SnakeP.get(x).body);
//Usuwa głowę
for(int x = size-1; x>0;x--)
SnakeP.remove(x);
start = false;
dead = true;
Loop.stop();
HighScore();
GameOver.setText(" Koniec gry, Chcesz zacząć od początku?");
Pause.setText(" Wciśnij Enter żeby zrestartować");
//Nowa pozycja dla węża
posX = new Random().nextInt(GridSizeSquared);
posY = new Random().nextInt(GridSizeSquared);
//Umieszcza węża na siatce
GameGrid.getChildren().remove(SnakeP.get(0).body);
GameGrid.add(SnakeP.get(0).body,posX,posY);
SnakeP.get(0).setPos(posX,posY);
foodN = 0;
}
public void HighScore() {
TextGrid.add(Nick, 0, 25, 1, 2);
TextGrid.add(User, 0, 28, 1, 2);
TextGrid.add(Submit, 0, 31, 1, 2);
Submit.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
String nick = User.getText();
try {
HighScoreWriter(nick);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
TextGrid.getChildren().remove(User);
TextGrid.getChildren().remove(Submit);
TextGrid.getChildren().remove(Nick);
}
});
}
// do poprawienia
public void HighScoreWriter(String nick) throws FileNotFoundException {
int[] fiveBestScores = new int[6];
File file = new File("src/App/Resources/css/Highscores.txt");
Scanner scanner = new Scanner(file);
String str = "";
while (scanner.hasNextLine()){ str += scanner.nextLine() + "\n"; }
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(str);
int i=0;
while (matcher.find()){
fiveBestScores[i] = Integer.parseInt(matcher.group());
i++;
}
FileWriter fr = null;
try{
fr = new FileWriter(file);
if (foodN > fiveBestScores[0]){ fr.write(str.replaceAll("a\\)\\s\\d+\\spkt","a) " + foodN + " pkt"+ " "+ nick)); }
else if (foodN > fiveBestScores[1]){ fr.write(str.replaceAll("b\\)\\s\\d+\\spkt","b) " + foodN +" pkt" + " "+ nick)); }
else if (foodN > fiveBestScores[2]){ fr.write(str.replaceAll("c\\)\\s\\d+\\spkt","c) " + foodN +" pkt"+ " "+ nick)); }
else if (foodN > fiveBestScores[3]){ fr.write(str.replaceAll("d\\)\\s\\d+\\spkt","d) " + foodN + "pkt"+ " "+ nick)); }
else if (foodN > fiveBestScores[4]){ fr.write(str.replaceAll("e\\)\\s\\d+\\spkt","e) " + foodN +" pkt" +" "+ nick)); }
else { fr.write(str); }
} catch (IOException e) { e.printStackTrace(); }
finally { try { fr.close(); } catch (IOException e) { e.printStackTrace(); } }
}
public Rectangle fillFoodwithimage(){
File path = new File("src/App/Resources/css/bolt.png");
Image image = new Image(path.toURI().toString());
Rectangle body = new Rectangle(16,16);
body.setFill(new ImagePattern(image));
return body;
}
}
| null |
9372_0 | ClearlyClaire/NFCTagmaker | 1,136 | src/pl/net/szafraniec/NFCTagmaker/AboutDialog.java | /**
* Copyright (C) 2014 Mateusz Szafraniec
* This file is part of NFCTagMaker.
*
* NFCTagMaker 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.
*
* NFCTagMaker 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 NFCTagMaker; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Ten plik jest częścią NFCTagMaker.
*
* NFCTagMaker jest wolnym oprogramowaniem; możesz go rozprowadzać dalej
* i/lub modyfikować na warunkach Powszechnej Licencji Publicznej GNU,
* wydanej przez Fundację Wolnego Oprogramowania - według wersji 2 tej
* Licencji lub (według twojego wyboru) którejś z późniejszych wersji.
*
* Niniejszy program rozpowszechniany jest z nadzieją, iż będzie on
* użyteczny - jednak BEZ JAKIEJKOLWIEK GWARANCJI, nawet domyślnej
* gwarancji PRZYDATNOŚCI HANDLOWEJ albo PRZYDATNOŚCI DO OKREŚLONYCH
* ZASTOSOWAŃ. W celu uzyskania bliższych informacji sięgnij do
* Powszechnej Licencji Publicznej GNU.
*
* Z pewnością wraz z niniejszym programem otrzymałeś też egzemplarz
* Powszechnej Licencji Publicznej GNU (GNU General Public License);
* jeśli nie - napisz do Free Software Foundation, Inc., 59 Temple
* Place, Fifth Floor, Boston, MA 02110-1301 USA
*/
package pl.net.szafraniec.NFCTagmaker;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.util.Linkify;
import android.widget.TextView;
public class AboutDialog extends Dialog {
private static Context mContext = null;
public static String readRawTextFile(int id) {
InputStream inputStream = mContext.getResources().openRawResource(id);
InputStreamReader in = new InputStreamReader(inputStream);
BufferedReader buf = new BufferedReader(in);
String line;
StringBuilder text = new StringBuilder();
try {
while ((line = buf.readLine()) != null)
text.append(line);
} catch (IOException e) {
return null;
}
return text.toString();
}
public AboutDialog(Context context) {
super(context);
mContext = context;
}
/**
* This is the standard Android on create method that gets called when the
* activity initialized.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.about);
TextView tv = (TextView) findViewById(R.id.legal_text);
// tv.setText(readRawTextFile(R.raw.legal));
tv.setText(Html.fromHtml(readRawTextFile(R.raw.legal)));
Linkify.addLinks(tv, Linkify.ALL);
tv = (TextView) findViewById(R.id.info_text);
tv.setText(Html.fromHtml(readRawTextFile(R.raw.info)
+ MainActivity.version));
tv.setLinkTextColor(Color.WHITE);
Linkify.addLinks(tv, Linkify.ALL);
}
}
| /**
* Copyright (C) 2014 Mateusz Szafraniec
* This file is part of NFCTagMaker.
*
* NFCTagMaker 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.
*
* NFCTagMaker 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 NFCTagMaker; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Ten plik jest częścią NFCTagMaker.
*
* NFCTagMaker jest wolnym oprogramowaniem; możesz go rozprowadzać dalej
* i/lub modyfikować na warunkach Powszechnej Licencji Publicznej GNU,
* wydanej przez Fundację Wolnego Oprogramowania - według wersji 2 tej
* Licencji lub (według twojego wyboru) którejś z późniejszych wersji.
*
* Niniejszy program rozpowszechniany jest z nadzieją, iż będzie on
* użyteczny - jednak BEZ JAKIEJKOLWIEK GWARANCJI, nawet domyślnej
* gwarancji PRZYDATNOŚCI HANDLOWEJ albo PRZYDATNOŚCI DO OKREŚLONYCH
* ZASTOSOWAŃ. W celu uzyskania bliższych informacji sięgnij do
* Powszechnej Licencji Publicznej GNU.
*
* Z pewnością wraz z niniejszym programem otrzymałeś też egzemplarz
* Powszechnej Licencji Publicznej GNU (GNU General Public License);
* jeśli nie - napisz do Free Software Foundation, Inc., 59 Temple
* Place, Fifth Floor, Boston, MA 02110-1301 USA
*/ | /**
* Copyright (C) 2014 <SUF>*/
package pl.net.szafraniec.NFCTagmaker;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.util.Linkify;
import android.widget.TextView;
public class AboutDialog extends Dialog {
private static Context mContext = null;
public static String readRawTextFile(int id) {
InputStream inputStream = mContext.getResources().openRawResource(id);
InputStreamReader in = new InputStreamReader(inputStream);
BufferedReader buf = new BufferedReader(in);
String line;
StringBuilder text = new StringBuilder();
try {
while ((line = buf.readLine()) != null)
text.append(line);
} catch (IOException e) {
return null;
}
return text.toString();
}
public AboutDialog(Context context) {
super(context);
mContext = context;
}
/**
* This is the standard Android on create method that gets called when the
* activity initialized.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.about);
TextView tv = (TextView) findViewById(R.id.legal_text);
// tv.setText(readRawTextFile(R.raw.legal));
tv.setText(Html.fromHtml(readRawTextFile(R.raw.legal)));
Linkify.addLinks(tv, Linkify.ALL);
tv = (TextView) findViewById(R.id.info_text);
tv.setText(Html.fromHtml(readRawTextFile(R.raw.info)
+ MainActivity.version));
tv.setLinkTextColor(Color.WHITE);
Linkify.addLinks(tv, Linkify.ALL);
}
}
| null |
2432_1 | CodecoolKRK20171/java-todo-app-CyprianSz | 531 | View.java | import java.util.Scanner; // pozamykać ten skaner gdzie potrzeba
import java.util.ArrayList;
//import java.io.*; // zaimportować tylko to co potrzebne (Chyba 'Str')
public class View {
private static Scanner input = new Scanner(System.in);
private static ArrayList<String> possibleCommands = new ArrayList<>();
public View() {
possibleCommands.add("list");
possibleCommands.add("add");
possibleCommands.add("mark");
possibleCommands.add("archive");
possibleCommands.add("exit");
}
public String takeUserChoice() {
String choice;
do {
System.out.println("\nPlease specify a command [list, add, mark, archive, exit]: ");
choice = input.next().toLowerCase();
} while (!possibleCommands.contains(choice));
return choice;
}
public String takeTaskContent() {
System.out.println("\nEnter task content: ");
return input.next();
}
public String takeNumberToMark() {
String choice = "";
do {
System.out.println("\nEnter proper number to mark: ");
choice = input.next();
} while (!choice.matches("^([1-9][0-9]*)$"));
return choice;
}
public void printThatCompleated(TodoItem task) {
System.out.println("\n" + task.content + " is compleated");
}
public void printThatArchived() {
System.out.println("\nAll completed tasks got deleted.");
}
public void printAllTasks(TodoList toDoList) {
Integer index = 1;
System.out.println("\nYou saved the following to-do items: ");
for (TodoItem task : toDoList.tasks) {
String mark = task.isCompleted ? "X" : " ";
System.out.println(index + "." + " [" + mark + "] " + task.content);
index += 1;
}
}
}
| //import java.io.*; // zaimportować tylko to co potrzebne (Chyba 'Str') | import java.util.Scanner; // pozamykać ten skaner gdzie potrzeba
import java.util.ArrayList;
//import java.io.*; <SUF>
public class View {
private static Scanner input = new Scanner(System.in);
private static ArrayList<String> possibleCommands = new ArrayList<>();
public View() {
possibleCommands.add("list");
possibleCommands.add("add");
possibleCommands.add("mark");
possibleCommands.add("archive");
possibleCommands.add("exit");
}
public String takeUserChoice() {
String choice;
do {
System.out.println("\nPlease specify a command [list, add, mark, archive, exit]: ");
choice = input.next().toLowerCase();
} while (!possibleCommands.contains(choice));
return choice;
}
public String takeTaskContent() {
System.out.println("\nEnter task content: ");
return input.next();
}
public String takeNumberToMark() {
String choice = "";
do {
System.out.println("\nEnter proper number to mark: ");
choice = input.next();
} while (!choice.matches("^([1-9][0-9]*)$"));
return choice;
}
public void printThatCompleated(TodoItem task) {
System.out.println("\n" + task.content + " is compleated");
}
public void printThatArchived() {
System.out.println("\nAll completed tasks got deleted.");
}
public void printAllTasks(TodoList toDoList) {
Integer index = 1;
System.out.println("\nYou saved the following to-do items: ");
for (TodoItem task : toDoList.tasks) {
String mark = task.isCompleted ? "X" : " ";
System.out.println(index + "." + " [" + mark + "] " + task.content);
index += 1;
}
}
}
| null |
3917_0 | CodecoolKRK20173/battle-of-cards-pawel-sebastian-bartek | 110 | Main.java | import java.util.*;
public class Main {
public static void main(String[] args) {
clearScreen();
new Game().gameHandler();
}
private static void clearScreen(){
//Runtime.getRuntime().exec("clear"); // nie działa, więc wytrychem go:
System.out.print("\033[H\033[2J");
System.out.flush();
}
}
| //Runtime.getRuntime().exec("clear"); // nie działa, więc wytrychem go: | import java.util.*;
public class Main {
public static void main(String[] args) {
clearScreen();
new Game().gameHandler();
}
private static void clearScreen(){
//Runtime.getRuntime().exec("clear"); // <SUF>
System.out.print("\033[H\033[2J");
System.out.flush();
}
}
| null |
5172_2 | Deardrops/Tillerinobot | 2,506 | tillerinobot/src/main/java/tillerino/tillerinobot/lang/Polski.java | package tillerino.tillerinobot.lang;
import java.util.List;
import java.util.Random;
import org.tillerino.osuApiModel.Mods;
import org.tillerino.osuApiModel.OsuApiUser;
import tillerino.tillerinobot.CommandHandler.Action;
import tillerino.tillerinobot.CommandHandler.Message;
import tillerino.tillerinobot.CommandHandler.Response;
/**
* Polish language implementation by https://osu.ppy.sh/u/pawwit
*/
public class Polski implements Language {
@Override
public String unknownBeatmap() {
return "Przykro mi, nie znam tej mapy. Możliwe że jest ona nowa albo nierankingowa.";
}
@Override
public String internalException(String marker) {
return "Ugh... Wygląda na to że Tillerino (człowiek) uszkodził moje obwody."
+ "Gdyby wkrótce tego nie zauważył, Możesz go poinformować? Znajdziesz go na @Tillerino lub /u/Tillerino? (odwołanie "
+ marker + ")";
}
@Override
public String externalException(String marker) {
return "Co jest?! Odpowiedź serwera osu nie ma sensu. Możesz mi powiedzieć co to znaczy \"0011101001010000\"?"
+ " Tillerino (człowiek) mówi, żeby się tym nie przejmować oraz że powinniśmy spróbować jeszcze raz."
+ " Jeśli jesteś bardzo zaniepokojony z jakiegoś powodu, możesz mu powiedzieć o tym na @Tillerino lub /u/Tillerino. (odwołanie "
+ marker + ")";
}
@Override
public String noInformationForModsShort() {
return "brak danych dla wskazanych modów";
}
@Override
public Response welcomeUser(OsuApiUser apiUser, long inactiveTime) {
if(inactiveTime < 60 * 1000) {
return new Message("beep boop");
} else if(inactiveTime < 24 * 60 * 60 * 1000) {
return new Message("Witaj ponownie, " + apiUser.getUserName() + ".");
} else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) {
return new Message(apiUser.getUserName() + "...")
.then(new Message("...czy to Ty? Minęło sporo czasu!"))
.then(new Message("Dobrze znowu Cie widzieć. Chcesz usłyszeć kilka rekomendacji?"));
} else {
String[] messages = {
"wygląda na to że chcesz jakieś rekomendacje.",
"jak dobrze Cie widzieć! :)",
"mój ulubiony człowiek. (Nie mów o tym innym ludziom!)",
"jakie miłe zaskoczenie! ^.^",
"Miałem nadzieję, że się pojawisz. Jesteś fajniejszy niż inni ludzie :3 (nie mówi im że Ci to powiedziałem!)",
"jak się masz?",
};
Random random = new Random();
String message = messages[random.nextInt(messages.length)];
return new Message(apiUser.getUserName() + ", " + message);
}
}
@Override
public String unknownCommand(String command) {
return "nieznana komenda \"" + command
+ "\". jeśli potrzebujesz pomocy napisz \"!help\" !";
}
@Override
public String noInformationForMods() {
return "Przykro mi, nie mogę dostarczyć informacji dla tych modów w tym momencie.";
}
@Override
public String malformattedMods(String mods) {
return "Coś się nie zgadza. Mody mogą być dowolną kombinacją DT HR HD HT EZ NC FL SO NF. Łącz je nie używając spacji, ani żadnych znaków. Przykład: !with HDHR, !with DTEZ";
}
@Override
public String noLastSongInfo() {
return "Nie pamiętam żebyś pytał się ostatnio o jakąś piosenkę...";
}
@Override
public String tryWithMods() {
return "Spróbuj zagrać tą mapę z modami!";
}
@Override
public String tryWithMods(List<Mods> mods) {
return "Spróbuj zagrać tą mapę z " + Mods.toShortNamesContinuous(mods);
}
@Override
public String excuseForError() {
return "Wybacz, widziałem piękną sekwencję zer i jedynek przez co się trochę rozkojarzyłem. Mógłbyś powtórzyć co chciałeś?";
}
@Override
public String complaint() {
return "Twoje zgłoszenie zostało wypełnione. Tillerino zerknie na nie jak tylko będzie mógł.";
}
@Override
public Response hug(OsuApiUser apiUser) {
return new Message("Chodź tu!")
.then(new Action("przytula " + apiUser.getUserName()));
}
@Override
public String help() {
return "Hej! Jestem robotem który zabił Tillerino, aby przejąc jego konto. Tylko żartowałem, czasem używam tego konta."
+ " Sprawdź https://twitter.com/Tillerinobot żeby zobaczyć najnowsze aktualizacje!"
+ " Odwiedź https://github.com/Tillerino/Tillerinobot/wiki żeby poznać komendy!";
}
@Override
public String faq() {
return "Wejdź na https://github.com/Tillerino/Tillerinobot/wiki/FAQ aby zobaczyć FAQ!";
}
@Override
public String featureRankRestricted(String feature, int minRank, OsuApiUser user) {
return "Przepraszam, ale w tym momencie " + feature + " jest dostępna tylko dla ludzi którzy przekroczyli pozycję " + minRank + " w rankingu.";
}
@Override
public String mixedNomodAndMods() {
return "Jak chcesz połączyć brak modów z modami?";
}
@Override
public String outOfRecommendations() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do"
+ " Skończyły mi się pomysł co mogę Ci jeszcze polecić]."
+ " Sprawdź inne opcje polecania albo użyj komendy !reset. Jeśli nie wiesz o co mi chodzi wpisz !help.";
}
@Override
public String notRanked() {
return "Wygląda na to, że ta mapa nie jest rankingowa.";
}
@Override
public boolean isChanged() {
return false;
}
@Override
public void setChanged(boolean changed) {
}
@Override
public String invalidAccuracy(String acc) {
return "Nieprawidłowa celność: \"" + acc + "\"";
}
@Override
public Response optionalCommentOnLanguage(OsuApiUser apiUser) {
return new Message("Pawwit nauczył mnie jak mówić po polsku, jeśli uważasz, że gdzieś się pomylił napisz do niego na osu!");
}
@Override
public String invalidChoice(String invalid, String choices) {
return "Wybacz, nie wiem co \"" + invalid
+ "\" znaczy. Spróbuj: " + choices + "!";
}
@Override
public String setFormat() {
return "Składnia polecenia \"!set\" jest następująca \"!set opcja wartość\". Wpisz !help jeśli potrzebujesz więcej wskazówek.";
}
@Override
public String apiTimeoutException() {
return new Default().apiTimeoutException();
}
@Override
public String noRecentPlays() {
return new Default().noRecentPlays();
}
@Override
public String isSetId() {
return new Default().isSetId();
}
@Override
public String getPatience() {
return new Default().getPatience();
}
}
| //github.com/Tillerino/Tillerinobot/wiki żeby poznać komendy!"; | package tillerino.tillerinobot.lang;
import java.util.List;
import java.util.Random;
import org.tillerino.osuApiModel.Mods;
import org.tillerino.osuApiModel.OsuApiUser;
import tillerino.tillerinobot.CommandHandler.Action;
import tillerino.tillerinobot.CommandHandler.Message;
import tillerino.tillerinobot.CommandHandler.Response;
/**
* Polish language implementation by https://osu.ppy.sh/u/pawwit
*/
public class Polski implements Language {
@Override
public String unknownBeatmap() {
return "Przykro mi, nie znam tej mapy. Możliwe że jest ona nowa albo nierankingowa.";
}
@Override
public String internalException(String marker) {
return "Ugh... Wygląda na to że Tillerino (człowiek) uszkodził moje obwody."
+ "Gdyby wkrótce tego nie zauważył, Możesz go poinformować? Znajdziesz go na @Tillerino lub /u/Tillerino? (odwołanie "
+ marker + ")";
}
@Override
public String externalException(String marker) {
return "Co jest?! Odpowiedź serwera osu nie ma sensu. Możesz mi powiedzieć co to znaczy \"0011101001010000\"?"
+ " Tillerino (człowiek) mówi, żeby się tym nie przejmować oraz że powinniśmy spróbować jeszcze raz."
+ " Jeśli jesteś bardzo zaniepokojony z jakiegoś powodu, możesz mu powiedzieć o tym na @Tillerino lub /u/Tillerino. (odwołanie "
+ marker + ")";
}
@Override
public String noInformationForModsShort() {
return "brak danych dla wskazanych modów";
}
@Override
public Response welcomeUser(OsuApiUser apiUser, long inactiveTime) {
if(inactiveTime < 60 * 1000) {
return new Message("beep boop");
} else if(inactiveTime < 24 * 60 * 60 * 1000) {
return new Message("Witaj ponownie, " + apiUser.getUserName() + ".");
} else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) {
return new Message(apiUser.getUserName() + "...")
.then(new Message("...czy to Ty? Minęło sporo czasu!"))
.then(new Message("Dobrze znowu Cie widzieć. Chcesz usłyszeć kilka rekomendacji?"));
} else {
String[] messages = {
"wygląda na to że chcesz jakieś rekomendacje.",
"jak dobrze Cie widzieć! :)",
"mój ulubiony człowiek. (Nie mów o tym innym ludziom!)",
"jakie miłe zaskoczenie! ^.^",
"Miałem nadzieję, że się pojawisz. Jesteś fajniejszy niż inni ludzie :3 (nie mówi im że Ci to powiedziałem!)",
"jak się masz?",
};
Random random = new Random();
String message = messages[random.nextInt(messages.length)];
return new Message(apiUser.getUserName() + ", " + message);
}
}
@Override
public String unknownCommand(String command) {
return "nieznana komenda \"" + command
+ "\". jeśli potrzebujesz pomocy napisz \"!help\" !";
}
@Override
public String noInformationForMods() {
return "Przykro mi, nie mogę dostarczyć informacji dla tych modów w tym momencie.";
}
@Override
public String malformattedMods(String mods) {
return "Coś się nie zgadza. Mody mogą być dowolną kombinacją DT HR HD HT EZ NC FL SO NF. Łącz je nie używając spacji, ani żadnych znaków. Przykład: !with HDHR, !with DTEZ";
}
@Override
public String noLastSongInfo() {
return "Nie pamiętam żebyś pytał się ostatnio o jakąś piosenkę...";
}
@Override
public String tryWithMods() {
return "Spróbuj zagrać tą mapę z modami!";
}
@Override
public String tryWithMods(List<Mods> mods) {
return "Spróbuj zagrać tą mapę z " + Mods.toShortNamesContinuous(mods);
}
@Override
public String excuseForError() {
return "Wybacz, widziałem piękną sekwencję zer i jedynek przez co się trochę rozkojarzyłem. Mógłbyś powtórzyć co chciałeś?";
}
@Override
public String complaint() {
return "Twoje zgłoszenie zostało wypełnione. Tillerino zerknie na nie jak tylko będzie mógł.";
}
@Override
public Response hug(OsuApiUser apiUser) {
return new Message("Chodź tu!")
.then(new Action("przytula " + apiUser.getUserName()));
}
@Override
public String help() {
return "Hej! Jestem robotem który zabił Tillerino, aby przejąc jego konto. Tylko żartowałem, czasem używam tego konta."
+ " Sprawdź https://twitter.com/Tillerinobot żeby zobaczyć najnowsze aktualizacje!"
+ " Odwiedź https://github.com/Tillerino/Tillerinobot/wiki żeby <SUF>
}
@Override
public String faq() {
return "Wejdź na https://github.com/Tillerino/Tillerinobot/wiki/FAQ aby zobaczyć FAQ!";
}
@Override
public String featureRankRestricted(String feature, int minRank, OsuApiUser user) {
return "Przepraszam, ale w tym momencie " + feature + " jest dostępna tylko dla ludzi którzy przekroczyli pozycję " + minRank + " w rankingu.";
}
@Override
public String mixedNomodAndMods() {
return "Jak chcesz połączyć brak modów z modami?";
}
@Override
public String outOfRecommendations() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do"
+ " Skończyły mi się pomysł co mogę Ci jeszcze polecić]."
+ " Sprawdź inne opcje polecania albo użyj komendy !reset. Jeśli nie wiesz o co mi chodzi wpisz !help.";
}
@Override
public String notRanked() {
return "Wygląda na to, że ta mapa nie jest rankingowa.";
}
@Override
public boolean isChanged() {
return false;
}
@Override
public void setChanged(boolean changed) {
}
@Override
public String invalidAccuracy(String acc) {
return "Nieprawidłowa celność: \"" + acc + "\"";
}
@Override
public Response optionalCommentOnLanguage(OsuApiUser apiUser) {
return new Message("Pawwit nauczył mnie jak mówić po polsku, jeśli uważasz, że gdzieś się pomylił napisz do niego na osu!");
}
@Override
public String invalidChoice(String invalid, String choices) {
return "Wybacz, nie wiem co \"" + invalid
+ "\" znaczy. Spróbuj: " + choices + "!";
}
@Override
public String setFormat() {
return "Składnia polecenia \"!set\" jest następująca \"!set opcja wartość\". Wpisz !help jeśli potrzebujesz więcej wskazówek.";
}
@Override
public String apiTimeoutException() {
return new Default().apiTimeoutException();
}
@Override
public String noRecentPlays() {
return new Default().noRecentPlays();
}
@Override
public String isSetId() {
return new Default().isSetId();
}
@Override
public String getPatience() {
return new Default().getPatience();
}
}
| null |
6256_8 | Disasm/jmp | 3,921 | src/TagReader.java | import javax.microedition.io.*;
import javax.microedition.io.file.*;
import javax.microedition.lcdui.*;
import java.util.*;
import java.io.*;
class Tag {
public String artist, title, album;
}
public class TagReader {
public String artist, title, album;
public TagReader(String path) {
//String url = getUrl(path);
FileConnection fc = null;
InputStream is = null;
try {
//fc = (FileConnection)Connector.open(url, Connector.READ);
fc = (FileConnection)Connector.open(path, Connector.READ);
is = fc.openInputStream();
long size = fc.fileSize();
//Tag tag1 = null;
Tag tag2 = null;
byte[] b = new byte[10];
int res = is.read(b);
if(res!=10) throw new Exception();
if((b[0]=='I')&&(b[1]=='D')&&(b[2]=='3')) {
tag2 = tryId3v2(is, b);
}
/*if(tag2==null) {
tag1 = tryId3v1(is, size);
}*/
if(tag2!=null) {
title = tag2.title;
artist = tag2.artist;
album = tag2.album;
}/* else if(tag1!=null) {
title = tag1.title;
artist = tag1.artist;
album = tag1.album;
}*/
} catch(Exception e) {
/*Alert a = new Alert("Ошибка", e.getMessage(), null, AlertType.INFO);
//Alert a = new Alert("Ошибка", e.getMessage()+" (url="+url+")", null, AlertType.INFO);
a.setTimeout(Alert.FOREVER);
Jmp.midlet.display.setCurrent(a, Jmp.midlet.display.getCurrent());*/
}
try {
is.close();
} catch(Exception e) {}
try {
fc.close();
} catch(Exception e) {}
}
private Tag tryId3v1(InputStream is, long size) throws IOException {
if(!is.markSupported()) return null;
is.reset();
is.skip(size-128);
return null;
}
private Tag tryId3v2(InputStream is, byte[] f10) throws IOException {
byte vMajor = f10[3];
byte vMinor = f10[4];
byte flags = f10[5];
int size = extractSize(f10, 6);
if(size==0) return null;
byte[] b = new byte[size];
is.read(b);
if(vMajor==3) return tryId3v2_3(is, flags, b);
return null;
}
private Tag tryId3v2_3(InputStream is, byte flags, byte[] b) {
boolean extended = ((((int)flags)&0x40) > 0);
int off = 0;
if(extended) {
int size = ((int)b[off + 3])&0xff;
off += 4 + size;
}
Tag t = new Tag();
while(off<b.length) {
if((b.length-off)<=10) break;
if(b[off]==0) break;
String fid = b2c(b[off]) + "" + b2c(b[off+1]) + "" + b2c(b[off+2]) + "" + b2c(b[off+3]);
int size = extractSize(b, off+4, 8);
//System.out.println("FID: '"+fid+"'");
if(fid.equals("TIT2")) {
t.title = extractString(b, off+10, size);
} else if((fid.equals("TPUB"))||(fid.equals("TPE1"))||(fid.equals("TPE2"))||(fid.equals("TPE3"))) {
if(t.artist==null) t.artist = extractString(b, off+10, size);
} else if(fid.equals("TALB")) {
t.album = extractString(b, off+10, size);
}
off += 10+size;
}
return t;
}
private char b2c(byte b) {
int b2 = (((int)b)&0xff);
return (char)b2;
}
private int extractSize(byte[] bf, int off, int pad) {
int b3 = (((int)bf[off + 3])&0xff);
int b2 = (((int)bf[off + 2])&0xff);
int b1 = (((int)bf[off + 1])&0xff);
int b0 = (((int)bf[off])&0xff);
return b3 + (b2<<pad) + (b1<<(pad*2)) + (b0<<(pad*3));
}
private int extractSize(byte[] bf, int off) {
return extractSize(bf, off, 7);
}
private String extractString(byte[] bf, int off, int len) {
if(len<2) return null;
byte enc = bf[off];
off++;
len--;
if(enc==0x00) {
return extractLocalString(bf, off, len);
} else if(enc==0x01) {
if(len<4) return null;
int b0 = (((int)bf[off])&0xff);
int b1 = (((int)bf[off + 1])&0xff);
if((b0==0xff)&&(b1==0xfe)) {
return extractUnicodeString(bf, off+2, (len-2)/2, true);
} else if((b0==0xfe)&&(b1==0xff)) {
return extractUnicodeString(bf, off+2, (len-2)/2, false);
}
}
return null;
}
private String extractUnicodeString(byte[] bf, int off, int len, boolean intel) {
String s = "";
for(int i=0;i<len;i++) {
char c;
int b0 = (((int)bf[i*2+off])&0xff);
int b1 = (((int)bf[i*2+off+1])&0xff);
if(intel) {
c = (char)(b0 + (b1<<8));
} else {
c = (char)(b1 + (b0<<8));
}
if(c==0) break;
s = s + c;
}
//System.out.println("extractUnicodeString: '"+s+"'");
return s;
}
private String extractLocalString(byte[] bf, int off, int len) {
String s = "";
for(int i=0;i<len;i++) {
byte b = bf[off+i];
if(b==0) break;
s = s + getCp1251(b);
}
//System.out.println("extractLocalString: '"+s+"'");
return s;
}
private char getCp1251(byte b0) {
int b = ((int)b0)&0xff;
if(b<0x80) return (char)b;
if(b==0xb8) return (char)0x451;
if(b==0xa8) return (char)0x401;
if((b>=0xc0)&&(b<=0xff)) return (char)(0x410+b-0xc0);
return '?';
}
private String a2hex(int a) {
a = a & 0xff;
String s1 = Integer.toHexString(a);
while(s1.length()<2) s1 = "0" + s1;
return "%"+s1;
}
private String urlEncode(int c) {
//int a = ((int)c)&0xffff;
if(((c>='A')&&(c<='Z'))||
((c>='a')&&(c<='z'))||
((c>='0')&&(c<='9'))||
(c=='/')||(c==':')||
(c=='.')||(c=='-')||
(c=='(')||(c==')')||
(c==' ')) return (char)c+"";
if((c&0xff00)==0) {
return a2hex(c&0xff);
} else {
return a2hex((c&0xff00)>>8)+a2hex(c&0xff);
}
}
// getUrl: 'file:///root1/Łzy - Gdybyś był (wersja karaoke).mp3' =>
// 'file:///root%25%33%31/%25%38a%25%38azy%25%320-%25%320Gdyby%250%36%25%32e%25%320by%25%31%34%25%31%34%25%320(wersja%25%320karaoke).mp%25%33%33'
// getUrl: 'file:///root1/Łzy - Gdybyś był (wersja karaoke).mp3' =>
// 'file:///root%25%33%31/%25%38b%25%38bzy%25%320-%25%320Gdyby%250%36%25%32e%25%320by%25%31%37%25%31%37%25%320(wersja%25%320karaoke).mp%25%33%33'
// buf: 66 69 6c 65 3a 2f 2f 2f 72 6f 6f 74 31 2f ffffffc5 ffffff81 7a 79 20 2d 20 47 64 79 62 79 ffffffc5 ffffff9b 20 62 79 ffffffc5 ffffff82 20 28 77 65 72 73 6a 61 20 6b 61 72 61 6f 6b 65 29 2e 6d 70 33
/*
file:///e:/MP3/card/Fleur/01%20-%20%d0%00%06%86%03%43%34%34%68%68%d1%d1%e8%00.mp3
* file:///root1/ 01%20-%20 %d0%00 %06%86 %03%43 %34%34 %68%68 %d1%d1 %e8%00.mp3
* 01 - Шелкопряд.mp3
*/
private String getUrl(String s0) {
String s1 = "";
try {
byte[] bf = s0.getBytes("UTF-8");
//
/*System.out.print(" buf: ");
for(int i=0;i<bf.length;i++) {
System.out.print(Integer.toHexString(((int)bf[i])&0xff)+" ");
}
System.out.println();*/
//
int i = 0;
while(i<bf.length) {
int b = ((int)bf[i])&0xff;
//System.out.print(" => "+(Integer.toHexString(b)));
if(b<0x80) {
String s = urlEncode(b);
//System.out.println(" '"+s+"'");
s1 = s1 + s;
i++;
} else {
if((i+1)>=bf.length) break;
int b2 = ((int)bf[i+1])&0xff;
//System.out.print(" (b2="+Integer.toHexString(b2)+")");
//System.out.print(" (b="+Integer.toHexString(b)+")");
int b3 = (b<<8) + b2;
String s = urlEncode(b3);
//System.out.println(" (b3="+Integer.toHexString(b3)+") '"+s+"'");
s1 = s1 + s;
i += 2;
}
}
//System.out.println("getUrl: '"+s0+"' => '"+s1+"'");
return s1;
} catch(Exception e) {
s1 = s0;
}
String s = "";
for(int i=0;i<s1.length();i++) {
int c = ((int)s1.charAt(i))&0xffff;
s = s + urlEncode(c);
}
//System.out.println("getUrl: '"+s0+"' => '"+s+"'");
return s;
}
}
/*
* Invalid file name in FileConnection Url: ///e:/MP3/card/Fleur/01 - Как все уходит.mp3
* File does not exists
*/
| // getUrl: 'file:///root1/Łzy - Gdybyś był (wersja karaoke).mp3' => | import javax.microedition.io.*;
import javax.microedition.io.file.*;
import javax.microedition.lcdui.*;
import java.util.*;
import java.io.*;
class Tag {
public String artist, title, album;
}
public class TagReader {
public String artist, title, album;
public TagReader(String path) {
//String url = getUrl(path);
FileConnection fc = null;
InputStream is = null;
try {
//fc = (FileConnection)Connector.open(url, Connector.READ);
fc = (FileConnection)Connector.open(path, Connector.READ);
is = fc.openInputStream();
long size = fc.fileSize();
//Tag tag1 = null;
Tag tag2 = null;
byte[] b = new byte[10];
int res = is.read(b);
if(res!=10) throw new Exception();
if((b[0]=='I')&&(b[1]=='D')&&(b[2]=='3')) {
tag2 = tryId3v2(is, b);
}
/*if(tag2==null) {
tag1 = tryId3v1(is, size);
}*/
if(tag2!=null) {
title = tag2.title;
artist = tag2.artist;
album = tag2.album;
}/* else if(tag1!=null) {
title = tag1.title;
artist = tag1.artist;
album = tag1.album;
}*/
} catch(Exception e) {
/*Alert a = new Alert("Ошибка", e.getMessage(), null, AlertType.INFO);
//Alert a = new Alert("Ошибка", e.getMessage()+" (url="+url+")", null, AlertType.INFO);
a.setTimeout(Alert.FOREVER);
Jmp.midlet.display.setCurrent(a, Jmp.midlet.display.getCurrent());*/
}
try {
is.close();
} catch(Exception e) {}
try {
fc.close();
} catch(Exception e) {}
}
private Tag tryId3v1(InputStream is, long size) throws IOException {
if(!is.markSupported()) return null;
is.reset();
is.skip(size-128);
return null;
}
private Tag tryId3v2(InputStream is, byte[] f10) throws IOException {
byte vMajor = f10[3];
byte vMinor = f10[4];
byte flags = f10[5];
int size = extractSize(f10, 6);
if(size==0) return null;
byte[] b = new byte[size];
is.read(b);
if(vMajor==3) return tryId3v2_3(is, flags, b);
return null;
}
private Tag tryId3v2_3(InputStream is, byte flags, byte[] b) {
boolean extended = ((((int)flags)&0x40) > 0);
int off = 0;
if(extended) {
int size = ((int)b[off + 3])&0xff;
off += 4 + size;
}
Tag t = new Tag();
while(off<b.length) {
if((b.length-off)<=10) break;
if(b[off]==0) break;
String fid = b2c(b[off]) + "" + b2c(b[off+1]) + "" + b2c(b[off+2]) + "" + b2c(b[off+3]);
int size = extractSize(b, off+4, 8);
//System.out.println("FID: '"+fid+"'");
if(fid.equals("TIT2")) {
t.title = extractString(b, off+10, size);
} else if((fid.equals("TPUB"))||(fid.equals("TPE1"))||(fid.equals("TPE2"))||(fid.equals("TPE3"))) {
if(t.artist==null) t.artist = extractString(b, off+10, size);
} else if(fid.equals("TALB")) {
t.album = extractString(b, off+10, size);
}
off += 10+size;
}
return t;
}
private char b2c(byte b) {
int b2 = (((int)b)&0xff);
return (char)b2;
}
private int extractSize(byte[] bf, int off, int pad) {
int b3 = (((int)bf[off + 3])&0xff);
int b2 = (((int)bf[off + 2])&0xff);
int b1 = (((int)bf[off + 1])&0xff);
int b0 = (((int)bf[off])&0xff);
return b3 + (b2<<pad) + (b1<<(pad*2)) + (b0<<(pad*3));
}
private int extractSize(byte[] bf, int off) {
return extractSize(bf, off, 7);
}
private String extractString(byte[] bf, int off, int len) {
if(len<2) return null;
byte enc = bf[off];
off++;
len--;
if(enc==0x00) {
return extractLocalString(bf, off, len);
} else if(enc==0x01) {
if(len<4) return null;
int b0 = (((int)bf[off])&0xff);
int b1 = (((int)bf[off + 1])&0xff);
if((b0==0xff)&&(b1==0xfe)) {
return extractUnicodeString(bf, off+2, (len-2)/2, true);
} else if((b0==0xfe)&&(b1==0xff)) {
return extractUnicodeString(bf, off+2, (len-2)/2, false);
}
}
return null;
}
private String extractUnicodeString(byte[] bf, int off, int len, boolean intel) {
String s = "";
for(int i=0;i<len;i++) {
char c;
int b0 = (((int)bf[i*2+off])&0xff);
int b1 = (((int)bf[i*2+off+1])&0xff);
if(intel) {
c = (char)(b0 + (b1<<8));
} else {
c = (char)(b1 + (b0<<8));
}
if(c==0) break;
s = s + c;
}
//System.out.println("extractUnicodeString: '"+s+"'");
return s;
}
private String extractLocalString(byte[] bf, int off, int len) {
String s = "";
for(int i=0;i<len;i++) {
byte b = bf[off+i];
if(b==0) break;
s = s + getCp1251(b);
}
//System.out.println("extractLocalString: '"+s+"'");
return s;
}
private char getCp1251(byte b0) {
int b = ((int)b0)&0xff;
if(b<0x80) return (char)b;
if(b==0xb8) return (char)0x451;
if(b==0xa8) return (char)0x401;
if((b>=0xc0)&&(b<=0xff)) return (char)(0x410+b-0xc0);
return '?';
}
private String a2hex(int a) {
a = a & 0xff;
String s1 = Integer.toHexString(a);
while(s1.length()<2) s1 = "0" + s1;
return "%"+s1;
}
private String urlEncode(int c) {
//int a = ((int)c)&0xffff;
if(((c>='A')&&(c<='Z'))||
((c>='a')&&(c<='z'))||
((c>='0')&&(c<='9'))||
(c=='/')||(c==':')||
(c=='.')||(c=='-')||
(c=='(')||(c==')')||
(c==' ')) return (char)c+"";
if((c&0xff00)==0) {
return a2hex(c&0xff);
} else {
return a2hex((c&0xff00)>>8)+a2hex(c&0xff);
}
}
// getUrl: 'file:///root1/Łzy - Gdybyś był (wersja karaoke).mp3' =>
// 'file:///root%25%33%31/%25%38a%25%38azy%25%320-%25%320Gdyby%250%36%25%32e%25%320by%25%31%34%25%31%34%25%320(wersja%25%320karaoke).mp%25%33%33'
// getUrl: 'file:///root1/Łzy <SUF>
// 'file:///root%25%33%31/%25%38b%25%38bzy%25%320-%25%320Gdyby%250%36%25%32e%25%320by%25%31%37%25%31%37%25%320(wersja%25%320karaoke).mp%25%33%33'
// buf: 66 69 6c 65 3a 2f 2f 2f 72 6f 6f 74 31 2f ffffffc5 ffffff81 7a 79 20 2d 20 47 64 79 62 79 ffffffc5 ffffff9b 20 62 79 ffffffc5 ffffff82 20 28 77 65 72 73 6a 61 20 6b 61 72 61 6f 6b 65 29 2e 6d 70 33
/*
file:///e:/MP3/card/Fleur/01%20-%20%d0%00%06%86%03%43%34%34%68%68%d1%d1%e8%00.mp3
* file:///root1/ 01%20-%20 %d0%00 %06%86 %03%43 %34%34 %68%68 %d1%d1 %e8%00.mp3
* 01 - Шелкопряд.mp3
*/
private String getUrl(String s0) {
String s1 = "";
try {
byte[] bf = s0.getBytes("UTF-8");
//
/*System.out.print(" buf: ");
for(int i=0;i<bf.length;i++) {
System.out.print(Integer.toHexString(((int)bf[i])&0xff)+" ");
}
System.out.println();*/
//
int i = 0;
while(i<bf.length) {
int b = ((int)bf[i])&0xff;
//System.out.print(" => "+(Integer.toHexString(b)));
if(b<0x80) {
String s = urlEncode(b);
//System.out.println(" '"+s+"'");
s1 = s1 + s;
i++;
} else {
if((i+1)>=bf.length) break;
int b2 = ((int)bf[i+1])&0xff;
//System.out.print(" (b2="+Integer.toHexString(b2)+")");
//System.out.print(" (b="+Integer.toHexString(b)+")");
int b3 = (b<<8) + b2;
String s = urlEncode(b3);
//System.out.println(" (b3="+Integer.toHexString(b3)+") '"+s+"'");
s1 = s1 + s;
i += 2;
}
}
//System.out.println("getUrl: '"+s0+"' => '"+s1+"'");
return s1;
} catch(Exception e) {
s1 = s0;
}
String s = "";
for(int i=0;i<s1.length();i++) {
int c = ((int)s1.charAt(i))&0xffff;
s = s + urlEncode(c);
}
//System.out.println("getUrl: '"+s0+"' => '"+s+"'");
return s;
}
}
/*
* Invalid file name in FileConnection Url: ///e:/MP3/card/Fleur/01 - Как все уходит.mp3
* File does not exists
*/
| null |
5074_2 | EpicPlayerA10/portfel-mimicode | 166 | src/main/java/com/top1/portfel/other/ChatHelper.java | // Plugin na portfel by MimiCode
// Plugin na licencji!
// proszę nie kopiować <3
package com.top1.portfel.other;
import org.bukkit.ChatColor;
import java.util.List;
import java.util.stream.Collectors;
public class ChatHelper {
public static String colored(String text){
return ChatColor.translateAlternateColorCodes('&', text);
}
public static List<String> colored(final List<String> texts) {
return texts.stream().map(ChatHelper::colored).collect(Collectors.toList());
}
}
| // proszę nie kopiować <3 | // Plugin na portfel by MimiCode
// Plugin na licencji!
// proszę nie <SUF>
package com.top1.portfel.other;
import org.bukkit.ChatColor;
import java.util.List;
import java.util.stream.Collectors;
public class ChatHelper {
public static String colored(String text){
return ChatColor.translateAlternateColorCodes('&', text);
}
public static List<String> colored(final List<String> texts) {
return texts.stream().map(ChatHelper::colored).collect(Collectors.toList());
}
}
| null |
8172_0 | Franek-Antoniak/uni-pjatk | 71 | PPJ/23.10.2022/uni/Ex3.java | public class Ex3 {
public static void main(String[] args) {
// Tak też myślałem
if(3 < 5 * 2.0)
System.out .print ("Hello");
System.out .print (" PPJ") ;
}
}
| // Tak też myślałem | public class Ex3 {
public static void main(String[] args) {
// Tak też <SUF>
if(3 < 5 * 2.0)
System.out .print ("Hello");
System.out .print (" PPJ") ;
}
}
| null |
3772_2 | GRM-dev/Modbus | 1,033 | src/main/java/atrem/modbus/Connection.java | package atrem.modbus;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import atrem.modbus.frames.RequestFrame;
public class Connection implements Runnable {
private Socket socket;
private InputStream inStream;
private ControllerImpl controller;
private OutputStream outStream;
private String ipAddress;
private int port;
public Connection(String ipAddress, int port, ControllerImpl controller)
throws IOException {
this.ipAddress = ipAddress;
this.port = port;
this.controller = controller;
makeConnection();
}
public void makeConnection() throws IOException {
socket = new Socket(ipAddress, port);
inStream = socket.getInputStream();
outStream = socket.getOutputStream();
// new SoundPlayer("connect_sound.mp3").play();
}
Connection(InputStream inStream, OutputStream outStream) {
this.inStream = inStream;
this.outStream = outStream;
}
public InputStream getInStream() {
return inStream;
}
public OutputStream getOutStream() {
return outStream;
}
public boolean checkConnection() {
return socket.isConnected();
}
public void send(byte[] frame) {
try {
outStream.write(frame);
} catch (SocketException e) {
} catch (IOException e) {
e.printStackTrace();
}
}
public void closeConnection() {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void startReceiveFrames() {
innerStartReceiveFrames();
}
Thread innerStartReceiveFrames() {
Thread thread = new Thread(this, "watek odbierajacy ramki");
thread.start();
return thread;
}
@Override
public void run() {
while (true) {
byte[] header = new byte[RequestFrame.HEADER_SIZE];
readBytes(header, RequestFrame.HEADER_SIZE);
ByteBuffer byteBuffer = ByteBuffer.wrap(header);
byteBuffer.position(4);
// int tid = byteBuffer.getShort(); // TODO nie wiem czy to dziala
// int pid = byteBuffer.getShort();
int length = byteBuffer.getShort();
byte[] data = new byte[length];
readBytes(data, length);
byte[] buff = new byte[RequestFrame.HEADER_SIZE + length];
System.arraycopy(header, 0, buff, 0, RequestFrame.HEADER_SIZE);
System.arraycopy(data, 0, buff, RequestFrame.HEADER_SIZE, length);
if (socket.isClosed())
return;
controller.loadBytes(buff);
}
}
private void readBytes(byte[] targetArray, int count) {
for (int i = 0; i < count; i++) {
try {
targetArray[i] = (byte) inStream.read();
} catch (SocketException e) {
} catch (IOException e) { // TODO przechwycenie wyjatku z sensem
e.printStackTrace();
}
}
}
public void setController(ControllerImpl controller) {
this.controller = controller;
}
public String getIpAddress() {
return ipAddress;
}
}
| // TODO przechwycenie wyjatku z sensem
| package atrem.modbus;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import atrem.modbus.frames.RequestFrame;
public class Connection implements Runnable {
private Socket socket;
private InputStream inStream;
private ControllerImpl controller;
private OutputStream outStream;
private String ipAddress;
private int port;
public Connection(String ipAddress, int port, ControllerImpl controller)
throws IOException {
this.ipAddress = ipAddress;
this.port = port;
this.controller = controller;
makeConnection();
}
public void makeConnection() throws IOException {
socket = new Socket(ipAddress, port);
inStream = socket.getInputStream();
outStream = socket.getOutputStream();
// new SoundPlayer("connect_sound.mp3").play();
}
Connection(InputStream inStream, OutputStream outStream) {
this.inStream = inStream;
this.outStream = outStream;
}
public InputStream getInStream() {
return inStream;
}
public OutputStream getOutStream() {
return outStream;
}
public boolean checkConnection() {
return socket.isConnected();
}
public void send(byte[] frame) {
try {
outStream.write(frame);
} catch (SocketException e) {
} catch (IOException e) {
e.printStackTrace();
}
}
public void closeConnection() {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void startReceiveFrames() {
innerStartReceiveFrames();
}
Thread innerStartReceiveFrames() {
Thread thread = new Thread(this, "watek odbierajacy ramki");
thread.start();
return thread;
}
@Override
public void run() {
while (true) {
byte[] header = new byte[RequestFrame.HEADER_SIZE];
readBytes(header, RequestFrame.HEADER_SIZE);
ByteBuffer byteBuffer = ByteBuffer.wrap(header);
byteBuffer.position(4);
// int tid = byteBuffer.getShort(); // TODO nie wiem czy to dziala
// int pid = byteBuffer.getShort();
int length = byteBuffer.getShort();
byte[] data = new byte[length];
readBytes(data, length);
byte[] buff = new byte[RequestFrame.HEADER_SIZE + length];
System.arraycopy(header, 0, buff, 0, RequestFrame.HEADER_SIZE);
System.arraycopy(data, 0, buff, RequestFrame.HEADER_SIZE, length);
if (socket.isClosed())
return;
controller.loadBytes(buff);
}
}
private void readBytes(byte[] targetArray, int count) {
for (int i = 0; i < count; i++) {
try {
targetArray[i] = (byte) inStream.read();
} catch (SocketException e) {
} catch (IOException e) { // TODO przechwycenie <SUF>
e.printStackTrace();
}
}
}
public void setController(ControllerImpl controller) {
this.controller = controller;
}
public String getIpAddress() {
return ipAddress;
}
}
| null |
8199_0 | Gitmanik/GitmanikPlugin | 777 | src/main/java/pl/gitmanik/helpers/GitmanikDurability.java | package pl.gitmanik.helpers;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public class GitmanikDurability
{
private static final String DURABILITY = "Wytrzymałość: ";
public static int GetDurability(ItemStack stack)
{
ItemMeta im = stack.getItemMeta();
List<String> lore = im.getLore();
AtomicInteger toret = new AtomicInteger(1);
if (lore == null)
lore = new ArrayList<>();
lore.forEach((a) -> {
if (a.startsWith(DURABILITY))
{
toret.set(Integer.parseInt(a.substring(a.indexOf(" ") + 1)));
}
});
return toret.get();
}
public static void SetDurability(ItemStack stack, int newDurability)
{
ItemMeta im = stack.getItemMeta();
List<String> lore = im.getLore();
if (lore == null)
lore = new ArrayList<>();
AtomicBoolean saved = new AtomicBoolean(false);
for (int i = 0; i < lore.size(); i++)
{
if (lore.get(i).startsWith(DURABILITY))
{
lore.set(i, DURABILITY + newDurability);
saved.set(true);
}
};
if (!saved.get())
lore.add(DURABILITY + newDurability);
im.setLore(lore);
stack.setItemMeta(im);
}
public static boolean EditDurability(Player player, ItemStack hand, int i)
{
int dur = GetDurability(hand) + i;
if (dur <= 0)
{
player.sendMessage(ChatColor.RED + "Twój przedmiot " + hand.getItemMeta().getDisplayName() + ChatColor.RED +" uległ zniszczeniu!"); //kurwa paweł to jest do poprawy, w sechand nie widac jaki przedmiot sie psuje, i trzeba kolor wstawić przedmiotu też w tym display name bo cale czertwone to dziwnie wygląda
player.getInventory().removeItemAnySlot(hand);
return false;
}
SetDurability(hand, dur);
return true;
}
}
| //kurwa paweł to jest do poprawy, w sechand nie widac jaki przedmiot sie psuje, i trzeba kolor wstawić przedmiotu też w tym display name bo cale czertwone to dziwnie wygląda | package pl.gitmanik.helpers;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public class GitmanikDurability
{
private static final String DURABILITY = "Wytrzymałość: ";
public static int GetDurability(ItemStack stack)
{
ItemMeta im = stack.getItemMeta();
List<String> lore = im.getLore();
AtomicInteger toret = new AtomicInteger(1);
if (lore == null)
lore = new ArrayList<>();
lore.forEach((a) -> {
if (a.startsWith(DURABILITY))
{
toret.set(Integer.parseInt(a.substring(a.indexOf(" ") + 1)));
}
});
return toret.get();
}
public static void SetDurability(ItemStack stack, int newDurability)
{
ItemMeta im = stack.getItemMeta();
List<String> lore = im.getLore();
if (lore == null)
lore = new ArrayList<>();
AtomicBoolean saved = new AtomicBoolean(false);
for (int i = 0; i < lore.size(); i++)
{
if (lore.get(i).startsWith(DURABILITY))
{
lore.set(i, DURABILITY + newDurability);
saved.set(true);
}
};
if (!saved.get())
lore.add(DURABILITY + newDurability);
im.setLore(lore);
stack.setItemMeta(im);
}
public static boolean EditDurability(Player player, ItemStack hand, int i)
{
int dur = GetDurability(hand) + i;
if (dur <= 0)
{
player.sendMessage(ChatColor.RED + "Twój przedmiot " + hand.getItemMeta().getDisplayName() + ChatColor.RED +" uległ zniszczeniu!"); //kurwa paweł <SUF>
player.getInventory().removeItemAnySlot(hand);
return false;
}
SetDurability(hand, dur);
return true;
}
}
| null |
3751_0 | Grodelek/Java_Lab4sem | 913 | Lab3/Lab3_Zad6.java | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] tab = new String[5];
BubbleSort bubbleSort = new BubbleSort() {
@Override
void bubbleString(String[] tab) {
for(int i=0; i<tab.length; i++){
for(int j=0; j<tab.length-i-1; j++){
int compareStrings = tab[j].compareTo(tab[j+1]);
if(compareStrings > 0){
String temp = tab[j];
tab[j] = tab[j+1];
tab[j+1] = temp;
}
}
}
}
};
System.out.println("Podaj 5 lancuchow tekstu:");
for(int i=0; i< tab.length; i++){
tab[i] = sc.nextLine();
}
bubbleSort.bubbleString(tab);
System.out.println("Teksty po zamianie:");
for (String element : tab){
System.out.println(element);
}
System.out.println("Teksty po odwroconej zamianie");
bubbleSort.reverseString(tab);
for(String element : tab){
System.out.println(element);
}
System.out.println("Teksty posortowane wedlug ostatnich indeksow:");
bubbleSort.lastSort(tab);
for(String element:tab){
System.out.println(element);
}
}
}
abstract class BubbleSort{
abstract void bubbleString(String[] tab);
void reverseString(String[] tab){
for(int i=0; i<tab.length; i++){
for(int j=0; j<tab.length-i-1; j++){
int wynikPorownania = tab[j].compareTo(tab[j+1]);
if(wynikPorownania <= 0){
String temp = tab[j];
tab[j] = tab[j+1];
tab[j+1] = temp;
}
}
}
}
void lastSort(String[] tab) {
for (int i = 0; i < tab.length; i++) {
for (int j = 0; j < tab.length - i - 1; j++) {
int n = 1;
int m = 1;
int len = tab[j].length();
int len2 = tab[j + 1].length();
char lastFirst = tab[j].charAt(len - n);
char lastSecond = tab[j + 1].charAt(len2 - m);
if(lastFirst == lastSecond){
while (lastFirst == lastSecond && len - n >= 0 && len2 - m >= 0) {
n++;
m++;
if (len - n >= 0) {
lastFirst = tab[j].charAt(len - n);
}
if (len2 - m >= 0) {
lastSecond = tab[j + 1].charAt(len2 - m);
}
}
}
if (lastFirst > lastSecond) {
String temp = tab[j];
tab[j] = tab[j + 1];
tab[j + 1] = temp;
}
}
}
}
}//To ostatnie nie wiem czy dobrze dziala
| //To ostatnie nie wiem czy dobrze dziala | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] tab = new String[5];
BubbleSort bubbleSort = new BubbleSort() {
@Override
void bubbleString(String[] tab) {
for(int i=0; i<tab.length; i++){
for(int j=0; j<tab.length-i-1; j++){
int compareStrings = tab[j].compareTo(tab[j+1]);
if(compareStrings > 0){
String temp = tab[j];
tab[j] = tab[j+1];
tab[j+1] = temp;
}
}
}
}
};
System.out.println("Podaj 5 lancuchow tekstu:");
for(int i=0; i< tab.length; i++){
tab[i] = sc.nextLine();
}
bubbleSort.bubbleString(tab);
System.out.println("Teksty po zamianie:");
for (String element : tab){
System.out.println(element);
}
System.out.println("Teksty po odwroconej zamianie");
bubbleSort.reverseString(tab);
for(String element : tab){
System.out.println(element);
}
System.out.println("Teksty posortowane wedlug ostatnich indeksow:");
bubbleSort.lastSort(tab);
for(String element:tab){
System.out.println(element);
}
}
}
abstract class BubbleSort{
abstract void bubbleString(String[] tab);
void reverseString(String[] tab){
for(int i=0; i<tab.length; i++){
for(int j=0; j<tab.length-i-1; j++){
int wynikPorownania = tab[j].compareTo(tab[j+1]);
if(wynikPorownania <= 0){
String temp = tab[j];
tab[j] = tab[j+1];
tab[j+1] = temp;
}
}
}
}
void lastSort(String[] tab) {
for (int i = 0; i < tab.length; i++) {
for (int j = 0; j < tab.length - i - 1; j++) {
int n = 1;
int m = 1;
int len = tab[j].length();
int len2 = tab[j + 1].length();
char lastFirst = tab[j].charAt(len - n);
char lastSecond = tab[j + 1].charAt(len2 - m);
if(lastFirst == lastSecond){
while (lastFirst == lastSecond && len - n >= 0 && len2 - m >= 0) {
n++;
m++;
if (len - n >= 0) {
lastFirst = tab[j].charAt(len - n);
}
if (len2 - m >= 0) {
lastSecond = tab[j + 1].charAt(len2 - m);
}
}
}
if (lastFirst > lastSecond) {
String temp = tab[j];
tab[j] = tab[j + 1];
tab[j + 1] = temp;
}
}
}
}
}//To ostatnie <SUF>
| null |
3787_6 | Hergoln/ZPO | 1,732 | lab10pkg/LottoLoco.java | package com.company.lab10pkg;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import com.company.IncorrectDateException;
public class LottoLoco
{
public static void doStuff()
{
try
{
Scanner scanner = new Scanner(System.in);
int choice = 0;
Document doc = Jsoup.connect("http://megalotto.pl/wyniki").get();
Element resultsDiv = doc.getElementById("div_dla_tabeli_wyniki_gry");
Element table = resultsDiv.select("table").get(0);
Elements rows = table.select("tr");
List<Element> ahrefs = new ArrayList<>();
for (Element column: rows)
{
Element el = column.child(0);
if(el.children().size() > 0) ahrefs.add(el.child(0));
}
choice = chooseGame(ahrefs);
String choiceURL = ahrefs.get(choice).attr("abs:href");
choice = chooseOption();
switch (choice)
{
case 1: // from date
{
System.out.println("Insert Date in format (dd-MM-yyyy):");
String date = scanner.nextLine();
LocalDate localDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
List<Integer> res = getResultFromDate(localDate, choiceURL);
System.out.print("Result: ");
if(res.size() <= 0) System.out.println("There is no date like this in Lotto results");
else
System.out.println(res);
} break;
case 2: // hist from year
{
System.out.println("Insert year:");
int year = scanner.nextInt();
if(LocalDate.of(year, 1, 1).isAfter(LocalDate.now()))
throw new IncorrectDateException(String.valueOf(year));
Map<Integer, Integer> res = getHistogramFromYear(year, choiceURL);
System.out.println("Result:");
res.forEach((key, value) -> System.out.println(key + ": " +value));
} break;
case 3: // hist from span
{
System.out.println("Insert span (dates in format dd-MM-yyyy):\nFirst date:");
String date = scanner.nextLine();
LocalDate startDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
System.out.println("Second date:");
date = scanner.nextLine();
LocalDate endDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
if(startDate.isAfter(endDate) || endDate.isAfter(LocalDate.now()))
throw new IncorrectDateException("(start):" + startDate + " (end):" + endDate);
Map<Integer, Integer> res = getHistogramBetweenDates(startDate, endDate, choiceURL);
res.forEach((key, value) -> System.out.println(key + ": " +value));
} break;
default:
System.out.println("Incorrect choice");
break;
}
}
catch (IOException exc)
{
System.out.println(exc);
}
catch (IncorrectDateException inData)
{
System.out.println("Not this time, your date (" + inData.getInfo() + ") is incorrect");
}
}
private static int chooseGame(List<Element> table)
{
for(int i = 0; i < table.size(); ++i)
{
System.out.println(i + ": " + table.get(i).text());
}
Scanner scanner = new Scanner(System.in);
return scanner.nextInt();
}
private static int chooseOption()
{
System.out.println("1. Results at date");
System.out.println("2. Histogram at specified year");
System.out.println("3. Histogram at specified span");
Scanner scanner = new Scanner(System.in);
return scanner.nextInt();
}
private static List<Integer> getResultFromDate(LocalDate date, String url) throws IOException
{
// Document doc = Jsoup.connect(url+fromToURLPart(date, date)).get();
// List<Integer> toReturn = new ArrayList<>();
// String numbers = doc.getElementsByClass("numbers_in_list ").text();
// if(!numbers.equals(""))
// {
// for(String s : numbers.split(" "))
// {
// toReturn.add(Integer.parseInt(s));
// }
// }
//
// return toReturn;
// pytanie czy takie coś może być, są tutaj tylko liczby, w przypadku MultiMulti powinny być chyba dwie listy, albo ja już nawet nie wiem xD
return new ArrayList<>(getHistogramBetweenDates(date, date, url).keySet());
}
private static Map<Integer, Integer> getHistogramFromYear(int year, String url) throws IOException
{
return getHistogramBetweenDates(LocalDate.of(year, 1, 1), LocalDate.of(year, 12, 31), url);
}
private static Map<Integer, Integer> getHistogramBetweenDates(LocalDate start, LocalDate end, String url) throws IOException
{
Document doc = Jsoup.connect(url+fromToURLPart(start, end)).get();
Map<Integer, Integer> histogram = new HashMap<>();
String numbers = doc.getElementsByClass("numbers_in_list ").text();
if(!numbers.equals(""))
{
for(String s : numbers.split(" "))
{
Integer num = Integer.parseInt(s);
if(histogram.putIfAbsent(num, 1) != null) histogram.replace(num, histogram.get(num)+1);
}
}
return histogram;
}
private static String fromToURLPart(LocalDate start, LocalDate end)
{
return "/losowania-od-"+start.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"))+"-do-"+end.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
}
}
| // pytanie czy takie coś może być, są tutaj tylko liczby, w przypadku MultiMulti powinny być chyba dwie listy, albo ja już nawet nie wiem xD | package com.company.lab10pkg;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import com.company.IncorrectDateException;
public class LottoLoco
{
public static void doStuff()
{
try
{
Scanner scanner = new Scanner(System.in);
int choice = 0;
Document doc = Jsoup.connect("http://megalotto.pl/wyniki").get();
Element resultsDiv = doc.getElementById("div_dla_tabeli_wyniki_gry");
Element table = resultsDiv.select("table").get(0);
Elements rows = table.select("tr");
List<Element> ahrefs = new ArrayList<>();
for (Element column: rows)
{
Element el = column.child(0);
if(el.children().size() > 0) ahrefs.add(el.child(0));
}
choice = chooseGame(ahrefs);
String choiceURL = ahrefs.get(choice).attr("abs:href");
choice = chooseOption();
switch (choice)
{
case 1: // from date
{
System.out.println("Insert Date in format (dd-MM-yyyy):");
String date = scanner.nextLine();
LocalDate localDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
List<Integer> res = getResultFromDate(localDate, choiceURL);
System.out.print("Result: ");
if(res.size() <= 0) System.out.println("There is no date like this in Lotto results");
else
System.out.println(res);
} break;
case 2: // hist from year
{
System.out.println("Insert year:");
int year = scanner.nextInt();
if(LocalDate.of(year, 1, 1).isAfter(LocalDate.now()))
throw new IncorrectDateException(String.valueOf(year));
Map<Integer, Integer> res = getHistogramFromYear(year, choiceURL);
System.out.println("Result:");
res.forEach((key, value) -> System.out.println(key + ": " +value));
} break;
case 3: // hist from span
{
System.out.println("Insert span (dates in format dd-MM-yyyy):\nFirst date:");
String date = scanner.nextLine();
LocalDate startDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
System.out.println("Second date:");
date = scanner.nextLine();
LocalDate endDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
if(startDate.isAfter(endDate) || endDate.isAfter(LocalDate.now()))
throw new IncorrectDateException("(start):" + startDate + " (end):" + endDate);
Map<Integer, Integer> res = getHistogramBetweenDates(startDate, endDate, choiceURL);
res.forEach((key, value) -> System.out.println(key + ": " +value));
} break;
default:
System.out.println("Incorrect choice");
break;
}
}
catch (IOException exc)
{
System.out.println(exc);
}
catch (IncorrectDateException inData)
{
System.out.println("Not this time, your date (" + inData.getInfo() + ") is incorrect");
}
}
private static int chooseGame(List<Element> table)
{
for(int i = 0; i < table.size(); ++i)
{
System.out.println(i + ": " + table.get(i).text());
}
Scanner scanner = new Scanner(System.in);
return scanner.nextInt();
}
private static int chooseOption()
{
System.out.println("1. Results at date");
System.out.println("2. Histogram at specified year");
System.out.println("3. Histogram at specified span");
Scanner scanner = new Scanner(System.in);
return scanner.nextInt();
}
private static List<Integer> getResultFromDate(LocalDate date, String url) throws IOException
{
// Document doc = Jsoup.connect(url+fromToURLPart(date, date)).get();
// List<Integer> toReturn = new ArrayList<>();
// String numbers = doc.getElementsByClass("numbers_in_list ").text();
// if(!numbers.equals(""))
// {
// for(String s : numbers.split(" "))
// {
// toReturn.add(Integer.parseInt(s));
// }
// }
//
// return toReturn;
// pytanie czy <SUF>
return new ArrayList<>(getHistogramBetweenDates(date, date, url).keySet());
}
private static Map<Integer, Integer> getHistogramFromYear(int year, String url) throws IOException
{
return getHistogramBetweenDates(LocalDate.of(year, 1, 1), LocalDate.of(year, 12, 31), url);
}
private static Map<Integer, Integer> getHistogramBetweenDates(LocalDate start, LocalDate end, String url) throws IOException
{
Document doc = Jsoup.connect(url+fromToURLPart(start, end)).get();
Map<Integer, Integer> histogram = new HashMap<>();
String numbers = doc.getElementsByClass("numbers_in_list ").text();
if(!numbers.equals(""))
{
for(String s : numbers.split(" "))
{
Integer num = Integer.parseInt(s);
if(histogram.putIfAbsent(num, 1) != null) histogram.replace(num, histogram.get(num)+1);
}
}
return histogram;
}
private static String fromToURLPart(LocalDate start, LocalDate end)
{
return "/losowania-od-"+start.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"))+"-do-"+end.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
}
}
| null |
4936_2 | IBAW4z/IBAW4 | 377 | src/model/Product.java | package main.java.model;
/**
* File module, class Product.java
* class of products used in Recipe or present in Fridge
* Created by Anna on 2015-06-10.
*/
enum eProdtype {
LOOSE, LIQUID, SPICE, MEAT, FISH, VEGETABLE, FRUIT
}
public class Product{
private int productId;
private String name;
private eProdtype productType;
private int amount; //-->dopiero w przepisie i lodowce?
//dorobić pochodne klasy dla róznych typów składników gdzie ilość
// będzie zależeć od typu składnika np. ml dla płynów,
// gramy dla sypkich ???
public void setProductId(int product_id) {
this.productId = productId;
}
public int getProductId() {
return productId;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setProductType(eProdtype productType) {
this.productType= productType;
}
public eProdtype getProductType() {
return productType;
}
public void setAmount(int amount) {
this.amount = amount;
}
public int getAmount() {
return amount;
}
} | //dorobić pochodne klasy dla róznych typów składników gdzie ilość | package main.java.model;
/**
* File module, class Product.java
* class of products used in Recipe or present in Fridge
* Created by Anna on 2015-06-10.
*/
enum eProdtype {
LOOSE, LIQUID, SPICE, MEAT, FISH, VEGETABLE, FRUIT
}
public class Product{
private int productId;
private String name;
private eProdtype productType;
private int amount; //-->dopiero w przepisie i lodowce?
//dorobić pochodne <SUF>
// będzie zależeć od typu składnika np. ml dla płynów,
// gramy dla sypkich ???
public void setProductId(int product_id) {
this.productId = productId;
}
public int getProductId() {
return productId;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setProductType(eProdtype productType) {
this.productType= productType;
}
public eProdtype getProductType() {
return productType;
}
public void setAmount(int amount) {
this.amount = amount;
}
public int getAmount() {
return amount;
}
} | null |
3115_1 | IBAW4z/task_3 | 921 | src/task_3/klasaLemur.java | package task_3;
import java.util.Scanner;
public class klasaLemur{
//licznik udupienia na najbliższy tydzień
public static void main(String [] args){
String dane[][];
dane = new String[7][3];
Scanner tmpS=new Scanner(System.in);
//kategorie: dni tygodnia
dane[0][0]="PONIEDZIAŁEK";
dane[1][0]="WTOREK";
dane[2][0]="ŚRODA";
dane[3][0]="CZWARTEK";
dane[4][0]="PIĄTEK";
dane[5][0]="SOBOTA";
dane[6][0]="NIEDZIELA";
for (int i=0; i<dane.length; i++){
System.out.println(dane[i][0]+" - co cię udupia?\n");
dane [i][1]=tmpS.nextLine();
System.out.println("Jak bardzo cię udupia? (skala 1-10)");
dane[i][2]=tmpS.nextLine();
}
tmpS.close();
//wyświetlanie tygodnia
System.out.println("Twój udupiający tydzień przedstawia się następująco: \n");
for (int i=0; i<dane.length; i++){
System.out.println(dane[i][0]+" - "+dane[i][1]+" ("+dane[i][2]+")");
}
//wyliczenie stopnia udupienia
int wspUdup=0;
for (int i=0; i<dane.length; i++){
try{
wspUdup=wspUdup+Integer.parseInt(dane[i][2]);
}
catch (NumberFormatException exc) {
wspUdup=wspUdup+0;
}
}
//skomentowanie stopnia udupienia
String koment;
if (wspUdup<10)
koment="Prokrastynuj w spokoju.";
else if (wspUdup>10 && wspUdup<20)
koment="Prokrastynuj w niepokoju.";
else if (wspUdup>20 && wspUdup<30)
koment="Lepiej nie prokrastynować. Co nie znaczy, że nie będziesz.";
else if (wspUdup>30 && wspUdup<40)
koment="Prokrastynacja zakazana. Pamiętaj, by nie dać się złapać.";
else if (wspUdup>40 && wspUdup<50)
koment="Prokrastynuj w panice";
else
koment="Prokrastynuj w spokoju. I tak jesteś udupiony.";
System.out.println("\n Stopień udupienia w tym tygodniu wynosi "+wspUdup+". "+koment);
}
}
| //kategorie: dni tygodnia
| package task_3;
import java.util.Scanner;
public class klasaLemur{
//licznik udupienia na najbliższy tydzień
public static void main(String [] args){
String dane[][];
dane = new String[7][3];
Scanner tmpS=new Scanner(System.in);
//kategorie: dni <SUF>
dane[0][0]="PONIEDZIAŁEK";
dane[1][0]="WTOREK";
dane[2][0]="ŚRODA";
dane[3][0]="CZWARTEK";
dane[4][0]="PIĄTEK";
dane[5][0]="SOBOTA";
dane[6][0]="NIEDZIELA";
for (int i=0; i<dane.length; i++){
System.out.println(dane[i][0]+" - co cię udupia?\n");
dane [i][1]=tmpS.nextLine();
System.out.println("Jak bardzo cię udupia? (skala 1-10)");
dane[i][2]=tmpS.nextLine();
}
tmpS.close();
//wyświetlanie tygodnia
System.out.println("Twój udupiający tydzień przedstawia się następująco: \n");
for (int i=0; i<dane.length; i++){
System.out.println(dane[i][0]+" - "+dane[i][1]+" ("+dane[i][2]+")");
}
//wyliczenie stopnia udupienia
int wspUdup=0;
for (int i=0; i<dane.length; i++){
try{
wspUdup=wspUdup+Integer.parseInt(dane[i][2]);
}
catch (NumberFormatException exc) {
wspUdup=wspUdup+0;
}
}
//skomentowanie stopnia udupienia
String koment;
if (wspUdup<10)
koment="Prokrastynuj w spokoju.";
else if (wspUdup>10 && wspUdup<20)
koment="Prokrastynuj w niepokoju.";
else if (wspUdup>20 && wspUdup<30)
koment="Lepiej nie prokrastynować. Co nie znaczy, że nie będziesz.";
else if (wspUdup>30 && wspUdup<40)
koment="Prokrastynacja zakazana. Pamiętaj, by nie dać się złapać.";
else if (wspUdup>40 && wspUdup<50)
koment="Prokrastynuj w panice";
else
koment="Prokrastynuj w spokoju. I tak jesteś udupiony.";
System.out.println("\n Stopień udupienia w tym tygodniu wynosi "+wspUdup+". "+koment);
}
}
| null |
6388_75 | ImareTeam/imare | 2,699 | src/pl/umk/mat/imare/io/OldWave.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pl.umk.mat.imare.io;
//import java.io.File;
//import java.io.FileInputStream;
//import java.io.IOException;
//import java.util.LinkedList;
//import javax.sound.sampled.AudioFormat;
//import javax.sound.sampled.AudioInputStream;
//import javax.sound.sampled.AudioSystem;
//import javax.sound.sampled.UnsupportedAudioFileException;
//import pl.umk.mat.imare.exception.FileDoesNotExistException;
//import pl.umk.mat.imare.exception.MissingChannelException;
//import pl.umk.mat.imare.gui.ProgressFrame;
//import pl.umk.mat.imare.gui.related.ProgressListener;
/**
* Klasa pozwalajaca uzyskac dostep do pliku WAVE.
* @author morti
*/
public abstract class OldWave {
//
// /** Informacje o pliku */
// protected AudioFormat format = null;
// /** Dane pliku wave */
// protected int[][] data = null;
// protected File file = null;
// protected LinkedList<ProgressListener> listeners = new LinkedList<ProgressListener>();
//
// /**
// * Otwiera plik do odczytu
// * @param file Plik do otwarcia
// * @return Zwraca obiekt klasy Wave pozwalajacy odczytac plik. Moze zwrocic
// * null jesli probka bedzie miala wiecej niz 2 kanaly lub bedzie miala
// * liczbe bitow na probke inna niz 8 lub 16.
// * @throws FileDoesNotExistException
// * @throws UnsupportedAudioFileException
// * @throws IOException
// */
// public static OldWave create(final File file, final ProgressListener progressListener) throws FileDoesNotExistException, UnsupportedAudioFileException, IOException {
// if (!file.exists()) {
// throw new FileDoesNotExistException();
// }
//
// String s = file.getName();
//
// /**
// * Jeśli otwierany plik to mp3 to
// */
// if (s.toLowerCase().endsWith(".mp3")) {
// MP3Loader wave = null;
// wave = new MP3Loader();
// wave.addListener(progressListener);
// wave.file = file;
// wave.load2(new FileInputStream(file));
// return wave;
// }
//
// /**
// * W innym wypadku mamy zwykłego wavea
// */
// //System.out.println(file);
// AudioInputStream ais = AudioSystem.getAudioInputStream(file);
// AudioFormat format = ais.getFormat();
// OldWave wave = null;
//
// int channels = format.getChannels();
// int bitsPerSample = format.getSampleSizeInBits();
//
// if (channels == 2) {
// // stereo
// if (bitsPerSample == 16) {
// wave = new Wave16BitStereo();
// } else if (bitsPerSample == 8) {
// wave = new Wave8BitStereo();
// }
// } else if (channels == 1) {
// // mono
// if (bitsPerSample == 16) {
// wave = new Wave16BitMono();
// } else if (bitsPerSample == 8) {
// wave = new Wave8BitMono();
// }
// }
// wave.addListener(progressListener);
// wave.file = file;
// wave.format = format;
// wave.load(ais);
// return wave;
//
// }
//
// /**
// * Otwiera plik do odczytu
// * @param filePath Sciezka pliku do otwarcia
// * @return Zwraca obiekt klasy Wave pozwalajacy odczytac plik.
// * @throws FileDoesNotExistException
// * @throws UnsupportedAudioFileException
// * @throws IOException
// */
// public static OldWave create(String filePath, ProgressFrame progressFrame) throws FileDoesNotExistException, UnsupportedAudioFileException, IOException {
// return create(new File(filePath), progressFrame);
// }
//
// /**
// *
// * @param format
// * @param samples
// * @return
// */
// public static OldWave fromSamples(AudioFormat format, int[] samples) {
// OldWave w = new OldWave() {
// @Override
// protected void load(AudioInputStream ais) throws FileDoesNotExistException, UnsupportedAudioFileException, IOException {
// }
// };
//
// w.data = new int[1][0];
// w.data[0] = samples;
// w.format = format;
// return w;
// }
//
// /**
// * Metoda ladujaca plik. Laduje CALY plik do pamieci.
// * @param file Plik do zaladowania
// * @throws FileDoesNotExistException
// * @throws UnsupportedAudioFileException
// * @throws IOException
// */
// protected abstract void load(AudioInputStream ais) throws FileDoesNotExistException, UnsupportedAudioFileException, IOException;
//
// /**
// *
// * @return Zwraca informacje o pliku
// */
// public AudioFormat getAudioFormat() {
// return format;
// }
//
// /**
// * Odczytuje probki. <br>
// * UWAGA: Ta metoda kopiuje probki przy uzyciu petli FOR poniewaz
// * wewnetrznie probki przechowywane sa w tablicy typu INT. To bardzo powolne.
// * Zalecane jest uzycie wersji z tablica typu INT.
// * @param channelNumber Numer kanalu. Dla dzwieku stereo kanal lewy - 0, kanal prawy - 1.
// * @param output Bufor na odczytane dane. Metoda bedzie probowala odczytac
// * tyle sampli ile bufor pomiesci.
// * @param offset Od ktorego sampla chcemy zaczac czytac
// * @return Zwraca ilosc przeczytanych sampli
// */
//// public int read(int channelNumber, double[] output, int offset) {
////
//// if(channelNumber >= format.getChannels())
//// throw new MissingChannelException(channelNumber);
////
//// int samplesRead;
////// // czytamy sample dopoki nie skonczy sie jedna z tablic output lub data
//// for(samplesRead=0;
//// samplesRead < output.length && samplesRead+offset < data[channelNumber].length;
//// samplesRead++ ) {
////
//// output[samplesRead] = (double)data[channelNumber][samplesRead + offset];
//// }
//// return samplesRead;
//// }
// /**
// * Odczytuje probki.
// * @param channelNumber Numer kanalu. Dla dzwieku stereo kanal lewy - 0, kanal prawy - 1.
// * @param output Bufor na odczytane dane. Metoda bedzie probowala odczytac
// * tyle sampli ile bufor pomiesci.
// * @param offset Od ktorego sampla chcemy zaczac czytac
// * @return Zwraca ilosc przeczytanych sampli
// */
// public int read(int channelNumber, int[] output, int offset) {
// if (channelNumber >= format.getChannels()) {
// throw new MissingChannelException(channelNumber);
// }
// int samplesRead = Math.min(output.length, data[channelNumber].length - offset);
// if (samplesRead <= 0) return 0;
//
// System.arraycopy(data[channelNumber], offset, output, 0, samplesRead);
//// for(int i=0; i<samplesRead; i++) output[i]=data[channelNumber][i+offset];
// return samplesRead;
// }
//
// public int readMono(int[] output, int offset) {
// int samplesRead = Math.min(output.length, data[0].length - offset);
// if (samplesRead <= 0) return 0;
//
// int channels = format.getChannels();
// for (int i = 0; i < samplesRead; ++i) {
// output[i] = 0;
// for (int c = 0; c < channels; ++c) {
// output[i] += data[c][i + offset];
// }
// }
// return samplesRead;
// }
//
// /**
// *
// * @return Zwraca ilosc probek dzwieku.
// */
// public int getSampleCount() {
// return data[0].length;
// }
//
// /**
// * @return Zwraca wartosc probki w danym miejscu
// */
// public int getSample(int channel, int offset) {
// return data[channel][offset];
// }
//
// public File getFile() {
// return file;
// }
//
// public void addListener(ProgressListener listener) {
// if (listener == null) {
// return;
// }
// listeners.add(listener);
// }
//
// public void removeListener(ProgressListener listener) {
// if (listener == null) {
// return;
// }
// listeners.remove(listener);
// }
//
// protected void notifyLoadingStarted() {
// for (ProgressListener l : listeners) {
// l.jobStarted(this);
// }
// }
//
// protected void notifyLoadingProgress(float progress) {
// for (ProgressListener l : listeners) {
// l.jobProgress(this, progress);
// }
// }
//
// protected void notifyLoadingFinished() {
// for (ProgressListener l : listeners) {
// l.jobFinished(this);
// }
// }
}
| // * @param offset Od ktorego sampla chcemy zaczac czytac | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pl.umk.mat.imare.io;
//import java.io.File;
//import java.io.FileInputStream;
//import java.io.IOException;
//import java.util.LinkedList;
//import javax.sound.sampled.AudioFormat;
//import javax.sound.sampled.AudioInputStream;
//import javax.sound.sampled.AudioSystem;
//import javax.sound.sampled.UnsupportedAudioFileException;
//import pl.umk.mat.imare.exception.FileDoesNotExistException;
//import pl.umk.mat.imare.exception.MissingChannelException;
//import pl.umk.mat.imare.gui.ProgressFrame;
//import pl.umk.mat.imare.gui.related.ProgressListener;
/**
* Klasa pozwalajaca uzyskac dostep do pliku WAVE.
* @author morti
*/
public abstract class OldWave {
//
// /** Informacje o pliku */
// protected AudioFormat format = null;
// /** Dane pliku wave */
// protected int[][] data = null;
// protected File file = null;
// protected LinkedList<ProgressListener> listeners = new LinkedList<ProgressListener>();
//
// /**
// * Otwiera plik do odczytu
// * @param file Plik do otwarcia
// * @return Zwraca obiekt klasy Wave pozwalajacy odczytac plik. Moze zwrocic
// * null jesli probka bedzie miala wiecej niz 2 kanaly lub bedzie miala
// * liczbe bitow na probke inna niz 8 lub 16.
// * @throws FileDoesNotExistException
// * @throws UnsupportedAudioFileException
// * @throws IOException
// */
// public static OldWave create(final File file, final ProgressListener progressListener) throws FileDoesNotExistException, UnsupportedAudioFileException, IOException {
// if (!file.exists()) {
// throw new FileDoesNotExistException();
// }
//
// String s = file.getName();
//
// /**
// * Jeśli otwierany plik to mp3 to
// */
// if (s.toLowerCase().endsWith(".mp3")) {
// MP3Loader wave = null;
// wave = new MP3Loader();
// wave.addListener(progressListener);
// wave.file = file;
// wave.load2(new FileInputStream(file));
// return wave;
// }
//
// /**
// * W innym wypadku mamy zwykłego wavea
// */
// //System.out.println(file);
// AudioInputStream ais = AudioSystem.getAudioInputStream(file);
// AudioFormat format = ais.getFormat();
// OldWave wave = null;
//
// int channels = format.getChannels();
// int bitsPerSample = format.getSampleSizeInBits();
//
// if (channels == 2) {
// // stereo
// if (bitsPerSample == 16) {
// wave = new Wave16BitStereo();
// } else if (bitsPerSample == 8) {
// wave = new Wave8BitStereo();
// }
// } else if (channels == 1) {
// // mono
// if (bitsPerSample == 16) {
// wave = new Wave16BitMono();
// } else if (bitsPerSample == 8) {
// wave = new Wave8BitMono();
// }
// }
// wave.addListener(progressListener);
// wave.file = file;
// wave.format = format;
// wave.load(ais);
// return wave;
//
// }
//
// /**
// * Otwiera plik do odczytu
// * @param filePath Sciezka pliku do otwarcia
// * @return Zwraca obiekt klasy Wave pozwalajacy odczytac plik.
// * @throws FileDoesNotExistException
// * @throws UnsupportedAudioFileException
// * @throws IOException
// */
// public static OldWave create(String filePath, ProgressFrame progressFrame) throws FileDoesNotExistException, UnsupportedAudioFileException, IOException {
// return create(new File(filePath), progressFrame);
// }
//
// /**
// *
// * @param format
// * @param samples
// * @return
// */
// public static OldWave fromSamples(AudioFormat format, int[] samples) {
// OldWave w = new OldWave() {
// @Override
// protected void load(AudioInputStream ais) throws FileDoesNotExistException, UnsupportedAudioFileException, IOException {
// }
// };
//
// w.data = new int[1][0];
// w.data[0] = samples;
// w.format = format;
// return w;
// }
//
// /**
// * Metoda ladujaca plik. Laduje CALY plik do pamieci.
// * @param file Plik do zaladowania
// * @throws FileDoesNotExistException
// * @throws UnsupportedAudioFileException
// * @throws IOException
// */
// protected abstract void load(AudioInputStream ais) throws FileDoesNotExistException, UnsupportedAudioFileException, IOException;
//
// /**
// *
// * @return Zwraca informacje o pliku
// */
// public AudioFormat getAudioFormat() {
// return format;
// }
//
// /**
// * Odczytuje probki. <br>
// * UWAGA: Ta metoda kopiuje probki przy uzyciu petli FOR poniewaz
// * wewnetrznie probki przechowywane sa w tablicy typu INT. To bardzo powolne.
// * Zalecane jest uzycie wersji z tablica typu INT.
// * @param channelNumber Numer kanalu. Dla dzwieku stereo kanal lewy - 0, kanal prawy - 1.
// * @param output Bufor na odczytane dane. Metoda bedzie probowala odczytac
// * tyle sampli ile bufor pomiesci.
// * @param offset Od ktorego sampla chcemy zaczac czytac
// * @return Zwraca ilosc przeczytanych sampli
// */
//// public int read(int channelNumber, double[] output, int offset) {
////
//// if(channelNumber >= format.getChannels())
//// throw new MissingChannelException(channelNumber);
////
//// int samplesRead;
////// // czytamy sample dopoki nie skonczy sie jedna z tablic output lub data
//// for(samplesRead=0;
//// samplesRead < output.length && samplesRead+offset < data[channelNumber].length;
//// samplesRead++ ) {
////
//// output[samplesRead] = (double)data[channelNumber][samplesRead + offset];
//// }
//// return samplesRead;
//// }
// /**
// * Odczytuje probki.
// * @param channelNumber Numer kanalu. Dla dzwieku stereo kanal lewy - 0, kanal prawy - 1.
// * @param output Bufor na odczytane dane. Metoda bedzie probowala odczytac
// * tyle sampli ile bufor pomiesci.
// * @param offset <SUF>
// * @return Zwraca ilosc przeczytanych sampli
// */
// public int read(int channelNumber, int[] output, int offset) {
// if (channelNumber >= format.getChannels()) {
// throw new MissingChannelException(channelNumber);
// }
// int samplesRead = Math.min(output.length, data[channelNumber].length - offset);
// if (samplesRead <= 0) return 0;
//
// System.arraycopy(data[channelNumber], offset, output, 0, samplesRead);
//// for(int i=0; i<samplesRead; i++) output[i]=data[channelNumber][i+offset];
// return samplesRead;
// }
//
// public int readMono(int[] output, int offset) {
// int samplesRead = Math.min(output.length, data[0].length - offset);
// if (samplesRead <= 0) return 0;
//
// int channels = format.getChannels();
// for (int i = 0; i < samplesRead; ++i) {
// output[i] = 0;
// for (int c = 0; c < channels; ++c) {
// output[i] += data[c][i + offset];
// }
// }
// return samplesRead;
// }
//
// /**
// *
// * @return Zwraca ilosc probek dzwieku.
// */
// public int getSampleCount() {
// return data[0].length;
// }
//
// /**
// * @return Zwraca wartosc probki w danym miejscu
// */
// public int getSample(int channel, int offset) {
// return data[channel][offset];
// }
//
// public File getFile() {
// return file;
// }
//
// public void addListener(ProgressListener listener) {
// if (listener == null) {
// return;
// }
// listeners.add(listener);
// }
//
// public void removeListener(ProgressListener listener) {
// if (listener == null) {
// return;
// }
// listeners.remove(listener);
// }
//
// protected void notifyLoadingStarted() {
// for (ProgressListener l : listeners) {
// l.jobStarted(this);
// }
// }
//
// protected void notifyLoadingProgress(float progress) {
// for (ProgressListener l : listeners) {
// l.jobProgress(this, progress);
// }
// }
//
// protected void notifyLoadingFinished() {
// for (ProgressListener l : listeners) {
// l.jobFinished(this);
// }
// }
}
| null |
3374_53 | Irbidan/jdownloader | 6,493 | src/jd/plugins/hoster/ShareHostEu.java | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team [email protected]
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
package jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.gui.UserIO;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.Account.AccountError;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.utils.JDUtilities;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://sharehost\\.eu/[^<>\"]*?/(.*)" }, flags = { 2 })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
String success = getJson("success");
if ("false".equals(success)) {
String error = getJson("error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = getJson("fileName");
String filePath = getJson("filePath");
String fileSize = getJson("fileSize");
String fileAvailable = getJson("fileAvailable");
String fileDescription = getJson("fileDescription");
if ("false".equals(fileAvailable)) {
downloadLink.setAvailable(false);
} else {
fileName = Encoding.htmlDecode(fileName.trim());
fileName = unescape(fileName);
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
String errorMessage = e.getErrorMessage();
if (errorMessage.contains("Maintenance")) {
ai.setStatus(errorMessage);
account.setError(AccountError.TEMP_DISABLED, errorMessage);
} else {
ai.setStatus(getPhrase("LOGIN_FAILED_NOT_PREMIUM"));
UserIO.getInstance().requestMessageDialog(0, getPhrase("LOGIN_ERROR"), getPhrase("LOGIN_FAILED"));
account.setValid(false);
return ai;
}
account.setProperty("cookies", Property.NULL);
return ai;
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = getJson(accountResponse, "userIsPremium");
String userPremiumExpire = getJson(accountResponse, "userPremiumExpire");
String userTrafficToday = getJson(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
Date date;
try {
date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
} catch (final Exception e) {
logger.log(java.util.logging.Level.SEVERE, "Exception occurred", e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String response = br.toString();
String success = getJson("success");
if ("false".equals(success)) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(getJson(response, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - hasło użytkownika w serwisie
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = getJson("success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(getJson("error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(getJson("error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = getJson("fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
private String unescape(final String s) {
/* we have to make sure the youtube plugin is loaded */
if (!yt_loaded.getAndSet(true)) {
JDUtilities.getPluginForHost("youtube.com");
}
return jd.plugins.hoster.Youtube.unescape(s);
}
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
/*
* *
* Wrapper<br/> Tries to return value of key from JSon response, from default 'br' Browser.
*
* @author raztoki
*/
private String getJson(final String key) {
return jd.plugins.hoster.K2SApi.JSonUtils.getJson(br.toString(), key);
}
private String getJson(final String source, final String key) {
return jd.plugins.hoster.K2SApi.JSonUtils.getJson(source, key);
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} | // userAccountNotPremium - konto użytkownika nie posiada dostępu premium
| //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team [email protected]
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
package jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.gui.UserIO;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.Account.AccountError;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.utils.JDUtilities;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://sharehost\\.eu/[^<>\"]*?/(.*)" }, flags = { 2 })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
String success = getJson("success");
if ("false".equals(success)) {
String error = getJson("error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = getJson("fileName");
String filePath = getJson("filePath");
String fileSize = getJson("fileSize");
String fileAvailable = getJson("fileAvailable");
String fileDescription = getJson("fileDescription");
if ("false".equals(fileAvailable)) {
downloadLink.setAvailable(false);
} else {
fileName = Encoding.htmlDecode(fileName.trim());
fileName = unescape(fileName);
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
String errorMessage = e.getErrorMessage();
if (errorMessage.contains("Maintenance")) {
ai.setStatus(errorMessage);
account.setError(AccountError.TEMP_DISABLED, errorMessage);
} else {
ai.setStatus(getPhrase("LOGIN_FAILED_NOT_PREMIUM"));
UserIO.getInstance().requestMessageDialog(0, getPhrase("LOGIN_ERROR"), getPhrase("LOGIN_FAILED"));
account.setValid(false);
return ai;
}
account.setProperty("cookies", Property.NULL);
return ai;
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = getJson(accountResponse, "userIsPremium");
String userPremiumExpire = getJson(accountResponse, "userPremiumExpire");
String userTrafficToday = getJson(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
Date date;
try {
date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
} catch (final Exception e) {
logger.log(java.util.logging.Level.SEVERE, "Exception occurred", e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String response = br.toString();
String success = getJson("success");
if ("false".equals(success)) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(getJson(response, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - hasło użytkownika w serwisie
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - <SUF>
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = getJson("success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(getJson("error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(getJson("error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = getJson("fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
private String unescape(final String s) {
/* we have to make sure the youtube plugin is loaded */
if (!yt_loaded.getAndSet(true)) {
JDUtilities.getPluginForHost("youtube.com");
}
return jd.plugins.hoster.Youtube.unescape(s);
}
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
/*
* *
* Wrapper<br/> Tries to return value of key from JSon response, from default 'br' Browser.
*
* @author raztoki
*/
private String getJson(final String key) {
return jd.plugins.hoster.K2SApi.JSonUtils.getJson(br.toString(), key);
}
private String getJson(final String source, final String key) {
return jd.plugins.hoster.K2SApi.JSonUtils.getJson(source, key);
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} | null |
5181_7 | Isimis/Personal_Learning_Projects | 5,999 | School_Excercice_Objective_language_Learning.java | import java.util.Arrays;
import java.util.Random;
public class School_Excercice_Objective_language_Learning {
public static void main(String[] args) {
System.out.println("Test obszernego zadania dodatkowego czas zacząć!\n");
System.out.println("Test klasy nr 1 - Dron");
System.out.println("Tworzymy 2 drony.");
Zad_Dfeo_1.Drone drone1 = new Zad_Dfeo_1.Drone("Orion", 500, 600, 2430);
Zad_Dfeo_1.Drone drone2 = new Zad_Dfeo_1.Drone("Andromeda", 350, 700, 1570);
System.out.println("Każdy ma unikalne id.");
System.out.println("Id drona numer 2:");
drone2.showId();
System.out.println("Id drona numer 1:");
drone1.showId();
System.out.println("Przentacja działania funkcji:");
System.out.println(drone2.checkFlyParameters());
drone2.fly(200);
drone2.revEngine();
System.out.println(drone2);
System.out.println("\nTest klasy nr 2 - RacingDrone");
System.out.println("Tworzymy 4 drony.");
Zad_Dfeo_1.RacingDrone racingDrone1 = new Zad_Dfeo_1.RacingDrone("Lacerta", 700, 900, 220, "Zieloni", 4);
Zad_Dfeo_1.RacingDrone racingDrone2 = new Zad_Dfeo_1.RacingDrone("Volans", 5050, 6000, 7430, "Czerwoni", 2);
Zad_Dfeo_1.RacingDrone racingDrone3 = new Zad_Dfeo_1.RacingDrone("Cetus", 509, 630, 27, "Zieloni", 3);
Zad_Dfeo_1.RacingDrone racingDrone4 = new Zad_Dfeo_1.RacingDrone("Copricorn", 800, 400, 930, "Czerwoni", 1);
System.out.println("Przentacja działania funkcji:");
Zad_Dfeo_1.RacingDrone[] racers = {racingDrone1, racingDrone2, racingDrone3, racingDrone4};
System.out.println("Najszybszy dron to: " + Zad_Dfeo_1.RacingDrone.race(racers));
racingDrone2.revEngine();
System.out.println(Arrays.toString(Zad_Dfeo_1.RacingDrone.sortByPosition(racers)));
System.out.println(racingDrone2);
System.out.println("\nTest klasy nr 3 - RacingDrone");
System.out.println("Tworzymy 2 drony.");
Zad_Dfeo_1.VampireDrone vampireDrone1 = new Zad_Dfeo_1.VampireDrone("Sirius", 7000, 9000, 2720, false);
Zad_Dfeo_1.VampireDrone vampireDrone2 = new Zad_Dfeo_1.VampireDrone("Vega", 50, 900, 730, true);
System.out.println("Przentacja działania funkcji:");
vampireDrone1.drainEnergy(racingDrone2);
vampireDrone1.TurnIntoBatDrone();
vampireDrone1.TurnIntoBatDrone();
vampireDrone1.drainEnergy(racingDrone2);
vampireDrone2.TurnIntoDrone();
vampireDrone2.TurnIntoDrone();
System.out.println(vampireDrone1);
System.out.println("\nTest klasy nr 4 i 5 - ChristmasDrone i Gift");
System.out.println("Tworzymy drona.");
Zad_Dfeo_1.Gift gift1 = new Zad_Dfeo_1.Gift("Piłka", 0.20);
Zad_Dfeo_1.ChristmasDrone christmasDrone1 = new Zad_Dfeo_1.ChristmasDrone("Baltasar", 700, 2000, 820, gift1);
System.out.println("Przentacja działania funkcji:");
gift1.prepere();
gift1.unpack();
System.out.println(gift1);
christmasDrone1.deliverGift();
System.out.println(christmasDrone1);
System.out.println("\nTest klasy nr 6 - DroneControleRoom");
System.out.println("Tworzymy obiekt.");
Zad_Dfeo_1.DroneControlRoom droneControlRoom1 = new Zad_Dfeo_1.DroneControlRoom();
System.out.println("Przentacja działania funkcji:");
droneControlRoom1.addNewDrone(drone1);
droneControlRoom1.addNewDrone(drone2);
droneControlRoom1.addNewDrone(vampireDrone2);
droneControlRoom1.addNewDrone(christmasDrone1);
droneControlRoom1.addNewDrone(racingDrone3);
droneControlRoom1.addNewDrone(racingDrone2);
droneControlRoom1.chargeAllDrones();
System.out.println("Tyle dronów może latać: " + droneControlRoom1.countDronesThatCanFly());
droneControlRoom1.sortAllDrones();
System.out.println("Najsilniejszy silnik ma dron: " + droneControlRoom1.findMostPowerful());
System.out.println("\nTest klasy nr 7 (autorskiej) - KillerDrone");
System.out.println("Tworzymy obiekt.");
Zad_Dfeo_1.KillerDrone killerDrone1 = new Zad_Dfeo_1.KillerDrone("Iscariota", 900, 2000, 520, "Sierp");
System.out.println("Przentacja działania funkcji:");
killerDrone1.kill(drone1);
killerDrone1.kill(racingDrone4);
killerDrone1.checkWantedPoster();
System.out.println(killerDrone1.playWithPolice(1) + " to liczba policjantów, którzy w dzisiejszym dniu brali udział w pościgu.");
System.out.println(killerDrone1);
System.out.println("\n\nDziękuję za uwagę!");
}
public static class Drone{
int uniqueId;
static int Id;
String name;
double weight;
// Podana w g
double enginePower;
// Podana w W
double batteryLevel;
// Podana w mAh
Drone(String name, double weight, double enginePower, double batteryLevel) {
this.name = name;
this.weight = weight;
this.enginePower = enginePower;
this.batteryLevel = batteryLevel;
Id++;
uniqueId = Id;
}
void showId() {
System.out.println(this.uniqueId);
}
public boolean checkFlyParameters() {
return this.enginePower > this.weight && this.batteryLevel > 0;
}
public void fly(double distance /* Podany w metrach */) {
if (this.batteryLevel >= distance / 10 /* Zakładamy, że 1 mAh wystarcza na 10 metrów lotu */ ) {
System.out.println("Let's fly!");
} else {
System.out.println("Battery level too low!");
}
}
public void revEngine() {
for (int i = 0; i < (int) (this.enginePower / this.weight); i++) {
System.out.println("Vroom");
}
}
@Override
public String toString() {
return "RacingDrone{" +
"name='" + name + '\'' +
", weight=" + weight +
", enginePower=" + enginePower +
", batteryLevel=" + batteryLevel + '\'' +
'}';
}
}
public static class RacingDrone extends Zad_Dfeo_1.Drone {
String racingTeam;
int positionInRanking;
RacingDrone(String name, double weight, double enginePower, double batteryLevel, String racingTeam, int positionInRanking) {
super(name, weight, enginePower, batteryLevel);
this.positionInRanking = positionInRanking;
this.racingTeam = racingTeam;
}
public static Zad_Dfeo_1.Drone race(Zad_Dfeo_1.Drone[] racers) {
Zad_Dfeo_1.Drone fastestDrone = racers[0];
for (int i = 1; i < racers.length; i++) {
if (racers[i].enginePower > fastestDrone.enginePower) {
fastestDrone = racers[i];
}
}
return fastestDrone;
}
public void revEngine() {
super.revEngine();
System.out.println("ZOOOOOM");
}
public static Zad_Dfeo_1.RacingDrone[] sortByPosition(Zad_Dfeo_1.RacingDrone[] racers) {
for (int j = 0; j < racers.length; j++){
for (int i = 0; i < racers.length - 1; i++)
if (racers[i].positionInRanking > racers[i + 1].positionInRanking) {
Zad_Dfeo_1.RacingDrone temp = racers[i];
racers[i] = racers[i + 1];
racers[i + 1] = temp;
} else if (racers[i].positionInRanking == racers[i + 1].positionInRanking) {
if (racers[i].enginePower > racers[i + 1].enginePower) {
Zad_Dfeo_1.RacingDrone temp = racers[i];
racers[i] = racers[i + 1];
racers[i + 1] = temp;
}
}
}
return racers;
}
@Override
public String toString() {
return "RacingDrone{" +
"name='" + name + '\'' +
", weight=" + weight +
", enginePower=" + enginePower +
", batteryLevel=" + batteryLevel + '\'' +
", racingTeam='" + racingTeam +
", positionInRanking='" + positionInRanking +
'}';
}
}
public static class VampireDrone extends Zad_Dfeo_1.Drone {
static String constructor = "Bram Stoker";
boolean isTransformed = false;
// W zadaniu jest isDoneBat, ale później występuje jako isTransformed, więc zostawiam tę opcję
// Mam nadzieję, że rozumiem ten zamysł poprawnie i niczego nie pomijam
VampireDrone(String name, double weight, double enginePower, double batteryLevel, boolean isTransformed) {
super(name, weight, enginePower, batteryLevel);
this.isTransformed = isTransformed;
}
public void drainEnergy(Zad_Dfeo_1.Drone drone) {
// Z tego co rozumiem z zadania, to jeśli isTransformed jest false, to dron otrzymuje funkcje wampiryczne, ale zostawiłęm to u mnie, że jeśli jest true to ma te funkcjie dla jaśniejszej czytelności z mojej strony przy pisaniu
if (this.isTransformed) {
this.batteryLevel = this.batteryLevel + (drone.batteryLevel / 2);
drone.batteryLevel = drone.batteryLevel / 2;
} else {
System.out.println("W formie drona nie można wysysać energii.");
}
}
public void TurnIntoBatDrone() {
if (!this.isTransformed) {
System.out.println("Od teraz to ja jestem władcą nocy!");
this.isTransformed = true;
this.weight = this.weight / 2;
this.batteryLevel = this.batteryLevel / 2;
} else {
System.out.println("Już jestem władcą nocy.");
}
}
public void TurnIntoDrone() {
// Dodałem od siebie funkcję powrotu do normalnego stanu
if (this.isTransformed) {
System.out.println("Powrót do formy słabeusza!");
this.weight = this.weight * 2;
this.batteryLevel = this.batteryLevel * 1.5;
this.isTransformed = false;
} else {
System.out.println("Już jestem słaby, bardziej nie mogę.");
}
}
@Override
public String toString() {
return "VampireDrone{" +
"name='" + name + '\'' +
", weight=" + weight +
", enginePower=" + enginePower +
", batteryLevel=" + batteryLevel + '\'' +
", isTransformed='" + isTransformed +
'}';
}
}
public static class ChristmasDrone extends Zad_Dfeo_1.Drone {
Zad_Dfeo_1.Gift gift;
ChristmasDrone(String name, double weight, double enginePower, double batteryLevel, Zad_Dfeo_1.Gift gift) {
super(name, weight, enginePower, batteryLevel);
this.gift = gift;
}
public void deliverGift() {
if (this.gift.weight + this.weight > this.enginePower) {
System.out.println("Paczka jest zbyt ciężka żeby ją dostarczyć.");
} else if (this.gift == null) {
System.out.println("Nie ma żadnej paczki do dostarczenia.");
} else {
System.out.println("Dostarczono paczkę o wadze " + this.gift.weight + "g.");
this.gift = null;
}
}
@Override
public String toString() {
return "ChristmasDrone{" +
"name='" + name + '\'' +
", weight=" + weight +
", enginePower=" + enginePower +
", batteryLevel=" + batteryLevel + '\'' +
", gift='" + gift +
'}';
}
}
public static class Gift {
String nameOfContent;
double weight;
boolean isReadyToBeDelivered = false;
Gift(String nameOfContent, double weight) {
this.nameOfContent = nameOfContent;
this.weight = weight;
}
public void prepere() {
this.isReadyToBeDelivered = true;
}
public void unpack() {
this.isReadyToBeDelivered = false;
System.out.println("W paczce znajduje się " + this.nameOfContent + "!");
}
@Override
public String toString() {
return "Gift{" +
"nameOfContent='" + nameOfContent + '\'' +
", weight=" + weight +
'}';
}
}
public static class DroneControlRoom{
Zad_Dfeo_1.Drone[] allDrones;
static double windPowerOutside = 3;
DroneControlRoom() {
this.allDrones = new Zad_Dfeo_1.Drone[1];
}
public int countDronesThatCanFly() {
getOutNulls();
int count = 0;
for (Zad_Dfeo_1.Drone drone: this.allDrones) {
if (drone.enginePower > drone.weight && drone.batteryLevel > 0) {
count++;
}
}
return count;
}
public void chargeAllDrones() {
getOutNulls();
for (Zad_Dfeo_1.Drone drone: this.allDrones) {
drone.batteryLevel += 20;
}
}
public void addNewDrone(Zad_Dfeo_1.Drone drone) {
Zad_Dfeo_1.Drone[] newAllDrones = new Zad_Dfeo_1.Drone[allDrones.length + 1];
for (int i = 0; i < allDrones.length; i++) {
newAllDrones[i] = allDrones[i];
}
allDrones = newAllDrones;
allDrones[allDrones.length - 1] = drone;
}
public void sortAllDrones() {
getOutNulls();
for (int i = 0; i < allDrones.length; i++) {
for (int j = 0; j < allDrones.length - 1; j++) {
if (allDrones[j].weight > allDrones[j + 1].weight) {
double temp = allDrones[j + 1].weight;
allDrones[j + 1].weight = allDrones[j].weight;
allDrones[j].weight = temp;
}
}
}
System.out.print(" Lista dronów posortowana po wadze (rosnąco): ");
for (Zad_Dfeo_1.Drone drone: allDrones) {
System.out.print(drone + ", ");
}
}
public void getOutNulls() {
int counter = 0;
for (int j = 0; j < allDrones.length; j++) {
if (allDrones[j] != null) {
counter++;
}
}
Zad_Dfeo_1.Drone[] newList = new Zad_Dfeo_1.Drone[counter];
int counter2 = 0;
for (int j = 0; j < allDrones.length; j++) {
if (allDrones[j] != null) {
newList[counter2] = allDrones[j];
counter2++;
}
}
allDrones = newList;
}
public Zad_Dfeo_1.Drone findMostPowerful(){
getOutNulls();
return findMostPowerful(0, allDrones[0]);
}
public Zad_Dfeo_1.Drone findMostPowerful(int currentIndex, Zad_Dfeo_1.Drone currentMostPowerful) {
if (currentIndex == allDrones.length) {
return currentMostPowerful;
}
if (allDrones[currentIndex].enginePower > currentMostPowerful.enginePower) {
currentMostPowerful = allDrones[currentIndex];
}
return findMostPowerful(currentIndex + 1, currentMostPowerful);
}
@Override
public String toString() {
return "DroneControlRoom{" +
"allDrones='" + Arrays.toString(allDrones) +
'}';
}
}
// Inwencja twórcza
public static class KillerDrone extends Zad_Dfeo_1.Drone {
int killCounter;
String weapon;
int reward;
KillerDrone(String name, double weight, double enginePower, double batteryLevel, String weapon) {
super(name, weight, enginePower, batteryLevel);
this.weapon = weapon;
}
public void kill(Zad_Dfeo_1.Drone drone) {
System.out.println(drone.name + " został zabity przy pomocy " + this.weapon + "!");
drone = null;
this.killCounter++;
reward += 10000;
}
public void checkWantedPoster() {
System.out.println("Obecna nagroda za głowę " + this.name + " wynosi " + this.reward + ".");
}
public int playWithPolice(int policeInPursuit) {
if (policeInPursuit > 20) {
System.out.println(this.name + " został schwytany!");
return policeInPursuit;
} else if (policeInPursuit > 14) {
System.out.println(this.name + " znów zabawił się z policją i uciekł!");
return policeInPursuit;
} else {
Random random = new Random();
return playWithPolice(policeInPursuit + random.nextInt(10));
}
}
@Override
public String toString() {
return "KillerDrone{" +
"name='" + name + '\'' +
", weight=" + weight +
", enginePower=" + enginePower +
", batteryLevel=" + batteryLevel + '\'' +
", weapon='" + weapon +
'}';
}
}
}
| // Z tego co rozumiem z zadania, to jeśli isTransformed jest false, to dron otrzymuje funkcje wampiryczne, ale zostawiłęm to u mnie, że jeśli jest true to ma te funkcjie dla jaśniejszej czytelności z mojej strony przy pisaniu
| import java.util.Arrays;
import java.util.Random;
public class School_Excercice_Objective_language_Learning {
public static void main(String[] args) {
System.out.println("Test obszernego zadania dodatkowego czas zacząć!\n");
System.out.println("Test klasy nr 1 - Dron");
System.out.println("Tworzymy 2 drony.");
Zad_Dfeo_1.Drone drone1 = new Zad_Dfeo_1.Drone("Orion", 500, 600, 2430);
Zad_Dfeo_1.Drone drone2 = new Zad_Dfeo_1.Drone("Andromeda", 350, 700, 1570);
System.out.println("Każdy ma unikalne id.");
System.out.println("Id drona numer 2:");
drone2.showId();
System.out.println("Id drona numer 1:");
drone1.showId();
System.out.println("Przentacja działania funkcji:");
System.out.println(drone2.checkFlyParameters());
drone2.fly(200);
drone2.revEngine();
System.out.println(drone2);
System.out.println("\nTest klasy nr 2 - RacingDrone");
System.out.println("Tworzymy 4 drony.");
Zad_Dfeo_1.RacingDrone racingDrone1 = new Zad_Dfeo_1.RacingDrone("Lacerta", 700, 900, 220, "Zieloni", 4);
Zad_Dfeo_1.RacingDrone racingDrone2 = new Zad_Dfeo_1.RacingDrone("Volans", 5050, 6000, 7430, "Czerwoni", 2);
Zad_Dfeo_1.RacingDrone racingDrone3 = new Zad_Dfeo_1.RacingDrone("Cetus", 509, 630, 27, "Zieloni", 3);
Zad_Dfeo_1.RacingDrone racingDrone4 = new Zad_Dfeo_1.RacingDrone("Copricorn", 800, 400, 930, "Czerwoni", 1);
System.out.println("Przentacja działania funkcji:");
Zad_Dfeo_1.RacingDrone[] racers = {racingDrone1, racingDrone2, racingDrone3, racingDrone4};
System.out.println("Najszybszy dron to: " + Zad_Dfeo_1.RacingDrone.race(racers));
racingDrone2.revEngine();
System.out.println(Arrays.toString(Zad_Dfeo_1.RacingDrone.sortByPosition(racers)));
System.out.println(racingDrone2);
System.out.println("\nTest klasy nr 3 - RacingDrone");
System.out.println("Tworzymy 2 drony.");
Zad_Dfeo_1.VampireDrone vampireDrone1 = new Zad_Dfeo_1.VampireDrone("Sirius", 7000, 9000, 2720, false);
Zad_Dfeo_1.VampireDrone vampireDrone2 = new Zad_Dfeo_1.VampireDrone("Vega", 50, 900, 730, true);
System.out.println("Przentacja działania funkcji:");
vampireDrone1.drainEnergy(racingDrone2);
vampireDrone1.TurnIntoBatDrone();
vampireDrone1.TurnIntoBatDrone();
vampireDrone1.drainEnergy(racingDrone2);
vampireDrone2.TurnIntoDrone();
vampireDrone2.TurnIntoDrone();
System.out.println(vampireDrone1);
System.out.println("\nTest klasy nr 4 i 5 - ChristmasDrone i Gift");
System.out.println("Tworzymy drona.");
Zad_Dfeo_1.Gift gift1 = new Zad_Dfeo_1.Gift("Piłka", 0.20);
Zad_Dfeo_1.ChristmasDrone christmasDrone1 = new Zad_Dfeo_1.ChristmasDrone("Baltasar", 700, 2000, 820, gift1);
System.out.println("Przentacja działania funkcji:");
gift1.prepere();
gift1.unpack();
System.out.println(gift1);
christmasDrone1.deliverGift();
System.out.println(christmasDrone1);
System.out.println("\nTest klasy nr 6 - DroneControleRoom");
System.out.println("Tworzymy obiekt.");
Zad_Dfeo_1.DroneControlRoom droneControlRoom1 = new Zad_Dfeo_1.DroneControlRoom();
System.out.println("Przentacja działania funkcji:");
droneControlRoom1.addNewDrone(drone1);
droneControlRoom1.addNewDrone(drone2);
droneControlRoom1.addNewDrone(vampireDrone2);
droneControlRoom1.addNewDrone(christmasDrone1);
droneControlRoom1.addNewDrone(racingDrone3);
droneControlRoom1.addNewDrone(racingDrone2);
droneControlRoom1.chargeAllDrones();
System.out.println("Tyle dronów może latać: " + droneControlRoom1.countDronesThatCanFly());
droneControlRoom1.sortAllDrones();
System.out.println("Najsilniejszy silnik ma dron: " + droneControlRoom1.findMostPowerful());
System.out.println("\nTest klasy nr 7 (autorskiej) - KillerDrone");
System.out.println("Tworzymy obiekt.");
Zad_Dfeo_1.KillerDrone killerDrone1 = new Zad_Dfeo_1.KillerDrone("Iscariota", 900, 2000, 520, "Sierp");
System.out.println("Przentacja działania funkcji:");
killerDrone1.kill(drone1);
killerDrone1.kill(racingDrone4);
killerDrone1.checkWantedPoster();
System.out.println(killerDrone1.playWithPolice(1) + " to liczba policjantów, którzy w dzisiejszym dniu brali udział w pościgu.");
System.out.println(killerDrone1);
System.out.println("\n\nDziękuję za uwagę!");
}
public static class Drone{
int uniqueId;
static int Id;
String name;
double weight;
// Podana w g
double enginePower;
// Podana w W
double batteryLevel;
// Podana w mAh
Drone(String name, double weight, double enginePower, double batteryLevel) {
this.name = name;
this.weight = weight;
this.enginePower = enginePower;
this.batteryLevel = batteryLevel;
Id++;
uniqueId = Id;
}
void showId() {
System.out.println(this.uniqueId);
}
public boolean checkFlyParameters() {
return this.enginePower > this.weight && this.batteryLevel > 0;
}
public void fly(double distance /* Podany w metrach */) {
if (this.batteryLevel >= distance / 10 /* Zakładamy, że 1 mAh wystarcza na 10 metrów lotu */ ) {
System.out.println("Let's fly!");
} else {
System.out.println("Battery level too low!");
}
}
public void revEngine() {
for (int i = 0; i < (int) (this.enginePower / this.weight); i++) {
System.out.println("Vroom");
}
}
@Override
public String toString() {
return "RacingDrone{" +
"name='" + name + '\'' +
", weight=" + weight +
", enginePower=" + enginePower +
", batteryLevel=" + batteryLevel + '\'' +
'}';
}
}
public static class RacingDrone extends Zad_Dfeo_1.Drone {
String racingTeam;
int positionInRanking;
RacingDrone(String name, double weight, double enginePower, double batteryLevel, String racingTeam, int positionInRanking) {
super(name, weight, enginePower, batteryLevel);
this.positionInRanking = positionInRanking;
this.racingTeam = racingTeam;
}
public static Zad_Dfeo_1.Drone race(Zad_Dfeo_1.Drone[] racers) {
Zad_Dfeo_1.Drone fastestDrone = racers[0];
for (int i = 1; i < racers.length; i++) {
if (racers[i].enginePower > fastestDrone.enginePower) {
fastestDrone = racers[i];
}
}
return fastestDrone;
}
public void revEngine() {
super.revEngine();
System.out.println("ZOOOOOM");
}
public static Zad_Dfeo_1.RacingDrone[] sortByPosition(Zad_Dfeo_1.RacingDrone[] racers) {
for (int j = 0; j < racers.length; j++){
for (int i = 0; i < racers.length - 1; i++)
if (racers[i].positionInRanking > racers[i + 1].positionInRanking) {
Zad_Dfeo_1.RacingDrone temp = racers[i];
racers[i] = racers[i + 1];
racers[i + 1] = temp;
} else if (racers[i].positionInRanking == racers[i + 1].positionInRanking) {
if (racers[i].enginePower > racers[i + 1].enginePower) {
Zad_Dfeo_1.RacingDrone temp = racers[i];
racers[i] = racers[i + 1];
racers[i + 1] = temp;
}
}
}
return racers;
}
@Override
public String toString() {
return "RacingDrone{" +
"name='" + name + '\'' +
", weight=" + weight +
", enginePower=" + enginePower +
", batteryLevel=" + batteryLevel + '\'' +
", racingTeam='" + racingTeam +
", positionInRanking='" + positionInRanking +
'}';
}
}
public static class VampireDrone extends Zad_Dfeo_1.Drone {
static String constructor = "Bram Stoker";
boolean isTransformed = false;
// W zadaniu jest isDoneBat, ale później występuje jako isTransformed, więc zostawiam tę opcję
// Mam nadzieję, że rozumiem ten zamysł poprawnie i niczego nie pomijam
VampireDrone(String name, double weight, double enginePower, double batteryLevel, boolean isTransformed) {
super(name, weight, enginePower, batteryLevel);
this.isTransformed = isTransformed;
}
public void drainEnergy(Zad_Dfeo_1.Drone drone) {
// Z tego <SUF>
if (this.isTransformed) {
this.batteryLevel = this.batteryLevel + (drone.batteryLevel / 2);
drone.batteryLevel = drone.batteryLevel / 2;
} else {
System.out.println("W formie drona nie można wysysać energii.");
}
}
public void TurnIntoBatDrone() {
if (!this.isTransformed) {
System.out.println("Od teraz to ja jestem władcą nocy!");
this.isTransformed = true;
this.weight = this.weight / 2;
this.batteryLevel = this.batteryLevel / 2;
} else {
System.out.println("Już jestem władcą nocy.");
}
}
public void TurnIntoDrone() {
// Dodałem od siebie funkcję powrotu do normalnego stanu
if (this.isTransformed) {
System.out.println("Powrót do formy słabeusza!");
this.weight = this.weight * 2;
this.batteryLevel = this.batteryLevel * 1.5;
this.isTransformed = false;
} else {
System.out.println("Już jestem słaby, bardziej nie mogę.");
}
}
@Override
public String toString() {
return "VampireDrone{" +
"name='" + name + '\'' +
", weight=" + weight +
", enginePower=" + enginePower +
", batteryLevel=" + batteryLevel + '\'' +
", isTransformed='" + isTransformed +
'}';
}
}
public static class ChristmasDrone extends Zad_Dfeo_1.Drone {
Zad_Dfeo_1.Gift gift;
ChristmasDrone(String name, double weight, double enginePower, double batteryLevel, Zad_Dfeo_1.Gift gift) {
super(name, weight, enginePower, batteryLevel);
this.gift = gift;
}
public void deliverGift() {
if (this.gift.weight + this.weight > this.enginePower) {
System.out.println("Paczka jest zbyt ciężka żeby ją dostarczyć.");
} else if (this.gift == null) {
System.out.println("Nie ma żadnej paczki do dostarczenia.");
} else {
System.out.println("Dostarczono paczkę o wadze " + this.gift.weight + "g.");
this.gift = null;
}
}
@Override
public String toString() {
return "ChristmasDrone{" +
"name='" + name + '\'' +
", weight=" + weight +
", enginePower=" + enginePower +
", batteryLevel=" + batteryLevel + '\'' +
", gift='" + gift +
'}';
}
}
public static class Gift {
String nameOfContent;
double weight;
boolean isReadyToBeDelivered = false;
Gift(String nameOfContent, double weight) {
this.nameOfContent = nameOfContent;
this.weight = weight;
}
public void prepere() {
this.isReadyToBeDelivered = true;
}
public void unpack() {
this.isReadyToBeDelivered = false;
System.out.println("W paczce znajduje się " + this.nameOfContent + "!");
}
@Override
public String toString() {
return "Gift{" +
"nameOfContent='" + nameOfContent + '\'' +
", weight=" + weight +
'}';
}
}
public static class DroneControlRoom{
Zad_Dfeo_1.Drone[] allDrones;
static double windPowerOutside = 3;
DroneControlRoom() {
this.allDrones = new Zad_Dfeo_1.Drone[1];
}
public int countDronesThatCanFly() {
getOutNulls();
int count = 0;
for (Zad_Dfeo_1.Drone drone: this.allDrones) {
if (drone.enginePower > drone.weight && drone.batteryLevel > 0) {
count++;
}
}
return count;
}
public void chargeAllDrones() {
getOutNulls();
for (Zad_Dfeo_1.Drone drone: this.allDrones) {
drone.batteryLevel += 20;
}
}
public void addNewDrone(Zad_Dfeo_1.Drone drone) {
Zad_Dfeo_1.Drone[] newAllDrones = new Zad_Dfeo_1.Drone[allDrones.length + 1];
for (int i = 0; i < allDrones.length; i++) {
newAllDrones[i] = allDrones[i];
}
allDrones = newAllDrones;
allDrones[allDrones.length - 1] = drone;
}
public void sortAllDrones() {
getOutNulls();
for (int i = 0; i < allDrones.length; i++) {
for (int j = 0; j < allDrones.length - 1; j++) {
if (allDrones[j].weight > allDrones[j + 1].weight) {
double temp = allDrones[j + 1].weight;
allDrones[j + 1].weight = allDrones[j].weight;
allDrones[j].weight = temp;
}
}
}
System.out.print(" Lista dronów posortowana po wadze (rosnąco): ");
for (Zad_Dfeo_1.Drone drone: allDrones) {
System.out.print(drone + ", ");
}
}
public void getOutNulls() {
int counter = 0;
for (int j = 0; j < allDrones.length; j++) {
if (allDrones[j] != null) {
counter++;
}
}
Zad_Dfeo_1.Drone[] newList = new Zad_Dfeo_1.Drone[counter];
int counter2 = 0;
for (int j = 0; j < allDrones.length; j++) {
if (allDrones[j] != null) {
newList[counter2] = allDrones[j];
counter2++;
}
}
allDrones = newList;
}
public Zad_Dfeo_1.Drone findMostPowerful(){
getOutNulls();
return findMostPowerful(0, allDrones[0]);
}
public Zad_Dfeo_1.Drone findMostPowerful(int currentIndex, Zad_Dfeo_1.Drone currentMostPowerful) {
if (currentIndex == allDrones.length) {
return currentMostPowerful;
}
if (allDrones[currentIndex].enginePower > currentMostPowerful.enginePower) {
currentMostPowerful = allDrones[currentIndex];
}
return findMostPowerful(currentIndex + 1, currentMostPowerful);
}
@Override
public String toString() {
return "DroneControlRoom{" +
"allDrones='" + Arrays.toString(allDrones) +
'}';
}
}
// Inwencja twórcza
public static class KillerDrone extends Zad_Dfeo_1.Drone {
int killCounter;
String weapon;
int reward;
KillerDrone(String name, double weight, double enginePower, double batteryLevel, String weapon) {
super(name, weight, enginePower, batteryLevel);
this.weapon = weapon;
}
public void kill(Zad_Dfeo_1.Drone drone) {
System.out.println(drone.name + " został zabity przy pomocy " + this.weapon + "!");
drone = null;
this.killCounter++;
reward += 10000;
}
public void checkWantedPoster() {
System.out.println("Obecna nagroda za głowę " + this.name + " wynosi " + this.reward + ".");
}
public int playWithPolice(int policeInPursuit) {
if (policeInPursuit > 20) {
System.out.println(this.name + " został schwytany!");
return policeInPursuit;
} else if (policeInPursuit > 14) {
System.out.println(this.name + " znów zabawił się z policją i uciekł!");
return policeInPursuit;
} else {
Random random = new Random();
return playWithPolice(policeInPursuit + random.nextInt(10));
}
}
@Override
public String toString() {
return "KillerDrone{" +
"name='" + name + '\'' +
", weight=" + weight +
", enginePower=" + enginePower +
", batteryLevel=" + batteryLevel + '\'' +
", weapon='" + weapon +
'}';
}
}
}
| null |
6631_22 | JPaxos/JPaxos | 3,939 | src/lsr/paxos/network/TcpConnection.java | package lsr.paxos.network;
import static lsr.common.ProcessDescriptor.processDescriptor;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.util.concurrent.ArrayBlockingQueue;
import lsr.common.KillOnExceptionHandler;
import lsr.common.PID;
import lsr.paxos.messages.Message;
import lsr.paxos.messages.MessageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class is responsible for handling stable TCP connection to other
* replica, provides two methods for establishing new connection: active and
* passive. In active mode we try to connect to other side creating new socket
* and connects. If passive mode is enabled, then we wait for socket from the
* <code>SocketServer</code> provided by <code>TcpNetwork</code>.
* <p>
* Every time new message is received from this connection, it is deserialized,
* and then all registered network listeners in related <code>TcpNetwork</code>
* are notified about it.
*
* @see TcpNetwork
*/
public class TcpConnection {
public static final int TCP_BUFFER_SIZE = 16 * 1024 * 1024;
private static final long MAX_QUEUE_OFFER_DELAY_MS = 25L;
private Socket socket;
private DataInputStream input;
private OutputStream output;
private final PID replica;
private volatile boolean connected = false;
private volatile long lastSndTs = 0L;
private volatile boolean writing = false;
private final Object connectedLock = new Object();
/** true if connection should be started by this replica; */
private final boolean active;
private final TcpNetwork network;
private final Thread senderThread;
private final Thread receiverThread;
private final ArrayBlockingQueue<byte[]> sendQueue = new ArrayBlockingQueue<byte[]>(512);
private final int peerId;
private boolean closing = false;
/**
* Creates a new TCP connection to specified replica.
*
* @param network - related <code>TcpNetwork</code>.
* @param replica - replica to connect to.
* @param peerId - ID of the replica on the other end of connection
* @param active - initiates connection if true; waits for remote connection
* otherwise.
*/
public TcpConnection(TcpNetwork network, final PID replica, int peerId, boolean active) {
this.network = network;
this.replica = replica;
this.peerId = peerId;
this.active = active;
logger.info("Creating connection: {} - {}", replica, active);
receiverThread = new Thread(new ReceiverThread(), "ReplicaIORcv-" + replica.getId());
senderThread = new Thread(new Sender(), "ReplicaIOSnd-" + replica.getId());
receiverThread.setUncaughtExceptionHandler(new KillOnExceptionHandler());
senderThread.setUncaughtExceptionHandler(new KillOnExceptionHandler());
receiverThread.setDaemon(true);
receiverThread.setPriority(Thread.MAX_PRIORITY);
senderThread.setDaemon(true);
senderThread.setPriority(Thread.MAX_PRIORITY);
}
/**
* Starts the receiver and sender thread.
*/
public synchronized void start() {
receiverThread.start();
senderThread.start();
}
public boolean isActive() {
return active;
}
final class Sender implements Runnable {
public void run() {
logger.debug("Sender thread started.");
try {
Socket lastSeenSocket = null;
while (true) {
if (Thread.interrupted()) {
if (!closing)
throw new RuntimeException("Sender " +
Thread.currentThread().getName() +
" thread has been interupted and stopped.");
return;
}
byte[] msg = sendQueue.take();
// ignore message if not connected
// Works without memory barrier because connected is
// volatile
if (!connected) {
// wait for connection
synchronized (connectedLock) {
while (!connected)
connectedLock.wait();
lastSeenSocket = socket;
}
}
try {
writing = true;
output.write(msg);
output.flush();
writing = false;
} catch (IOException e) {
logger.warn("Error sending message", e);
writing = false;
sendQueue.offer(msg);
close(lastSeenSocket);
synchronized (connectedLock) {
lastSeenSocket = socket;
}
}
lastSndTs = System.currentTimeMillis();
}
} catch (InterruptedException e) {
if (closing)
logger.info("Clean closing the {}", Thread.currentThread().getName());
else
throw new RuntimeException("Sender " + Thread.currentThread().getName() +
" thread has been interupted",
e);
}
}
}
/**
* Main loop used to connect and read from the socket.
*/
final class ReceiverThread implements Runnable {
public void run() {
do {
if (Thread.interrupted()) {
if (!closing)
throw new RuntimeException("Receiver thread has been interrupted.");
return;
}
logger.info("Waiting for tcp connection to {}", replica.getId());
Socket lastSeenSocket;
try {
if (active)
lastSeenSocket = connect();
else {
synchronized (connectedLock) {
while (!connected)
connectedLock.wait();
lastSeenSocket = socket;
}
}
} catch (InterruptedException e) {
if (!closing)
throw new RuntimeException("Receiver thread has been interrupted.");
break;
}
while (true) {
if (Thread.interrupted()) {
if (!closing)
throw new RuntimeException("Receiver thread has been interrupted.");
return;
}
try {
Message message = MessageFactory.create(input);
if (logger.isDebugEnabled()) {
logger.debug("Received [{}] {} size: {}", replica.getId(), message,
message.byteSize());
}
network.fireReceiveMessage(message, replica.getId());
} catch (EOFException e) {
// end of stream with socket occurred so close
// connection and try to establish it again
if (!closing) {
logger.info("Error reading message - EOF", e);
close(lastSeenSocket);
}
break;
} catch (IOException e) {
// problem with socket occurred so close connection and
// try to establish it again
if (!closing) {
logger.warn("Error reading message (?)", e);
close(lastSeenSocket);
}
break;
}
}
} while (active);
}
}
/**
* Sends specified binary packet using underlying TCP connection.
*
* @param message - binary packet to send
* @return true if sending message was successful
*/
public void send(byte[] message) {
if (connected) {
// FIXME: (JK) discuss what should be done here
while (!sendQueue.offer(message)) {
// if some messages are being sent, wait a while
if (!writing ||
System.currentTimeMillis() - lastSndTs <= MAX_QUEUE_OFFER_DELAY_MS) {
Thread.yield();
continue;
}
byte[] discarded = sendQueue.poll();
if (logger.isDebugEnabled()) {
logger.warn(
"TCP msg queue overfolw: Discarding message {} to send {}. Last send: {}, writing: {}",
discarded.toString(), message.toString(),
System.currentTimeMillis() - lastSndTs, writing);
} else {
logger.warn("TCP msg queue overfolw: Discarding a message to send anoter");
}
}
} else {
// keep last n messages
while (!sendQueue.offer(message)) {
sendQueue.poll();
}
}
}
/**
* Registers new socket to this TCP connection. Specified socket should be
* initialized connection with other replica. First method tries to close
* old connection and then set-up new one.
*
* @param socket - active socket connection
* @param input - input stream from this socket
* @param output - output stream from this socket
*/
public synchronized void setConnection(Socket socket, DataInputStream input,
DataOutputStream output) {
assert socket != null : "Invalid socket state";
logger.info("TCP connection accepted from {}", replica);
synchronized (connectedLock) {
// initialize new connection
this.socket = socket;
this.input = input;
this.output = output;
connected = true;
// wake up receiver and sender
connectedLock.notifyAll();
}
}
public void stopAsync() {
synchronized (connectedLock) {
close(socket);
receiverThread.interrupt();
senderThread.interrupt();
}
}
/**
* Stops current connection and stops all underlying threads.
*
* Note: This method waits until all threads are finished.
*
* @throws InterruptedException
*/
public void stop() throws InterruptedException {
stopAsync();
receiverThread.join();
senderThread.join();
}
/**
* Establishes connection to host specified by this object. If this is
* active connection then it will try to connect to other side. Otherwise we
* will wait until connection will be set-up using
* <code>setConnection</code> method. This method will return only if the
* connection is established and initialized properly.
*
* @return
*
* @throws InterruptedException
*/
@SuppressWarnings("resource")
private Socket connect() throws InterruptedException {
assert active;
Socket newSocket;
DataInputStream newInput;
OutputStream newOutput;
// this is active connection so we try to connect to host
while (true) {
try {
newSocket = new Socket();
newSocket.setReceiveBufferSize(TCP_BUFFER_SIZE);
newSocket.setSendBufferSize(TCP_BUFFER_SIZE);
logger.debug("RcvdBuffer: {}, SendBuffer: {}", newSocket.getReceiveBufferSize(),
newSocket.getSendBufferSize());
newSocket.setTcpNoDelay(true);
logger.info("Connecting to: {}", replica);
try {
newSocket.connect(new InetSocketAddress(replica.getHostname(),
replica.getReplicaPort()),
(int) processDescriptor.tcpReconnectTimeout);
} catch (ConnectException e) {
logger.info("TCP connection with replica {} failed: {}",
replica.getId(), e.getMessage());
Thread.sleep(processDescriptor.tcpReconnectTimeout);
continue;
} catch (SocketTimeoutException e) {
logger.info("TCP connection with replica {} timed out", replica.getId());
continue;
} catch (SocketException e) {
if (newSocket.isClosed()) {
logger.warn("Invoking connect() on closed socket. Quitting?");
return null;
}
logger.warn("TCP connection with replica {} failed: {}",
replica.getId(), e.getMessage());
Thread.sleep(processDescriptor.tcpReconnectTimeout);
continue;
} catch (IOException e) {
throw new RuntimeException("what else can be thrown here?", e);
}
newInput = new DataInputStream(new BufferedInputStream(newSocket.getInputStream()));
newOutput = newSocket.getOutputStream();
byte buf[] = new byte[4];
ByteBuffer.wrap(buf).putInt(processDescriptor.localId);
try {
newOutput.write(buf);
newOutput.flush();
} catch (SocketException e) {
/*- Caused by: java.net.SocketException: Połączenie zerwane przez drugą stronę (Write failed) -*/
logger.warn("TCP connection with replica {} failed: {}",
replica.getId(), e.getMessage());
continue;
}
// connection established
break;
} catch (IOException e) {
throw new RuntimeException("Unexpected error connecting to " + replica, e);
}
}
logger.info("TCP connect successfull to {}", replica);
// Wake up the sender thread
synchronized (connectedLock) {
socket = newSocket;
input = newInput;
output = newOutput;
connected = true;
// notify sender
connectedLock.notifyAll();
}
network.addConnection(peerId, this);
return newSocket;
}
/**
* Closes the connection.
*
* @param victim - close can race with many methods (e.g. connect), so tell
* it what you want to close to prevent races
*/
private void close(Socket victim) {
synchronized (connectedLock) {
if (socket != victim)
return;
if (active)
network.removeConnection(peerId, this);
closing = true;
connected = false;
if (socket != null) {
if (socket.isConnected())
try {
logger.info("Closing TCP connection to {}", replica);
socket.shutdownOutput();
socket.close();
logger.debug("TCP connection closed to {}", replica);
} catch (IOException e) {
logger.warn("Error closing socket", e);
}
socket = null;
}
}
}
private final static Logger logger = LoggerFactory.getLogger(TcpConnection.class);
}
| /*- Caused by: java.net.SocketException: Połączenie zerwane przez drugą stronę (Write failed) -*/ | package lsr.paxos.network;
import static lsr.common.ProcessDescriptor.processDescriptor;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.util.concurrent.ArrayBlockingQueue;
import lsr.common.KillOnExceptionHandler;
import lsr.common.PID;
import lsr.paxos.messages.Message;
import lsr.paxos.messages.MessageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class is responsible for handling stable TCP connection to other
* replica, provides two methods for establishing new connection: active and
* passive. In active mode we try to connect to other side creating new socket
* and connects. If passive mode is enabled, then we wait for socket from the
* <code>SocketServer</code> provided by <code>TcpNetwork</code>.
* <p>
* Every time new message is received from this connection, it is deserialized,
* and then all registered network listeners in related <code>TcpNetwork</code>
* are notified about it.
*
* @see TcpNetwork
*/
public class TcpConnection {
public static final int TCP_BUFFER_SIZE = 16 * 1024 * 1024;
private static final long MAX_QUEUE_OFFER_DELAY_MS = 25L;
private Socket socket;
private DataInputStream input;
private OutputStream output;
private final PID replica;
private volatile boolean connected = false;
private volatile long lastSndTs = 0L;
private volatile boolean writing = false;
private final Object connectedLock = new Object();
/** true if connection should be started by this replica; */
private final boolean active;
private final TcpNetwork network;
private final Thread senderThread;
private final Thread receiverThread;
private final ArrayBlockingQueue<byte[]> sendQueue = new ArrayBlockingQueue<byte[]>(512);
private final int peerId;
private boolean closing = false;
/**
* Creates a new TCP connection to specified replica.
*
* @param network - related <code>TcpNetwork</code>.
* @param replica - replica to connect to.
* @param peerId - ID of the replica on the other end of connection
* @param active - initiates connection if true; waits for remote connection
* otherwise.
*/
public TcpConnection(TcpNetwork network, final PID replica, int peerId, boolean active) {
this.network = network;
this.replica = replica;
this.peerId = peerId;
this.active = active;
logger.info("Creating connection: {} - {}", replica, active);
receiverThread = new Thread(new ReceiverThread(), "ReplicaIORcv-" + replica.getId());
senderThread = new Thread(new Sender(), "ReplicaIOSnd-" + replica.getId());
receiverThread.setUncaughtExceptionHandler(new KillOnExceptionHandler());
senderThread.setUncaughtExceptionHandler(new KillOnExceptionHandler());
receiverThread.setDaemon(true);
receiverThread.setPriority(Thread.MAX_PRIORITY);
senderThread.setDaemon(true);
senderThread.setPriority(Thread.MAX_PRIORITY);
}
/**
* Starts the receiver and sender thread.
*/
public synchronized void start() {
receiverThread.start();
senderThread.start();
}
public boolean isActive() {
return active;
}
final class Sender implements Runnable {
public void run() {
logger.debug("Sender thread started.");
try {
Socket lastSeenSocket = null;
while (true) {
if (Thread.interrupted()) {
if (!closing)
throw new RuntimeException("Sender " +
Thread.currentThread().getName() +
" thread has been interupted and stopped.");
return;
}
byte[] msg = sendQueue.take();
// ignore message if not connected
// Works without memory barrier because connected is
// volatile
if (!connected) {
// wait for connection
synchronized (connectedLock) {
while (!connected)
connectedLock.wait();
lastSeenSocket = socket;
}
}
try {
writing = true;
output.write(msg);
output.flush();
writing = false;
} catch (IOException e) {
logger.warn("Error sending message", e);
writing = false;
sendQueue.offer(msg);
close(lastSeenSocket);
synchronized (connectedLock) {
lastSeenSocket = socket;
}
}
lastSndTs = System.currentTimeMillis();
}
} catch (InterruptedException e) {
if (closing)
logger.info("Clean closing the {}", Thread.currentThread().getName());
else
throw new RuntimeException("Sender " + Thread.currentThread().getName() +
" thread has been interupted",
e);
}
}
}
/**
* Main loop used to connect and read from the socket.
*/
final class ReceiverThread implements Runnable {
public void run() {
do {
if (Thread.interrupted()) {
if (!closing)
throw new RuntimeException("Receiver thread has been interrupted.");
return;
}
logger.info("Waiting for tcp connection to {}", replica.getId());
Socket lastSeenSocket;
try {
if (active)
lastSeenSocket = connect();
else {
synchronized (connectedLock) {
while (!connected)
connectedLock.wait();
lastSeenSocket = socket;
}
}
} catch (InterruptedException e) {
if (!closing)
throw new RuntimeException("Receiver thread has been interrupted.");
break;
}
while (true) {
if (Thread.interrupted()) {
if (!closing)
throw new RuntimeException("Receiver thread has been interrupted.");
return;
}
try {
Message message = MessageFactory.create(input);
if (logger.isDebugEnabled()) {
logger.debug("Received [{}] {} size: {}", replica.getId(), message,
message.byteSize());
}
network.fireReceiveMessage(message, replica.getId());
} catch (EOFException e) {
// end of stream with socket occurred so close
// connection and try to establish it again
if (!closing) {
logger.info("Error reading message - EOF", e);
close(lastSeenSocket);
}
break;
} catch (IOException e) {
// problem with socket occurred so close connection and
// try to establish it again
if (!closing) {
logger.warn("Error reading message (?)", e);
close(lastSeenSocket);
}
break;
}
}
} while (active);
}
}
/**
* Sends specified binary packet using underlying TCP connection.
*
* @param message - binary packet to send
* @return true if sending message was successful
*/
public void send(byte[] message) {
if (connected) {
// FIXME: (JK) discuss what should be done here
while (!sendQueue.offer(message)) {
// if some messages are being sent, wait a while
if (!writing ||
System.currentTimeMillis() - lastSndTs <= MAX_QUEUE_OFFER_DELAY_MS) {
Thread.yield();
continue;
}
byte[] discarded = sendQueue.poll();
if (logger.isDebugEnabled()) {
logger.warn(
"TCP msg queue overfolw: Discarding message {} to send {}. Last send: {}, writing: {}",
discarded.toString(), message.toString(),
System.currentTimeMillis() - lastSndTs, writing);
} else {
logger.warn("TCP msg queue overfolw: Discarding a message to send anoter");
}
}
} else {
// keep last n messages
while (!sendQueue.offer(message)) {
sendQueue.poll();
}
}
}
/**
* Registers new socket to this TCP connection. Specified socket should be
* initialized connection with other replica. First method tries to close
* old connection and then set-up new one.
*
* @param socket - active socket connection
* @param input - input stream from this socket
* @param output - output stream from this socket
*/
public synchronized void setConnection(Socket socket, DataInputStream input,
DataOutputStream output) {
assert socket != null : "Invalid socket state";
logger.info("TCP connection accepted from {}", replica);
synchronized (connectedLock) {
// initialize new connection
this.socket = socket;
this.input = input;
this.output = output;
connected = true;
// wake up receiver and sender
connectedLock.notifyAll();
}
}
public void stopAsync() {
synchronized (connectedLock) {
close(socket);
receiverThread.interrupt();
senderThread.interrupt();
}
}
/**
* Stops current connection and stops all underlying threads.
*
* Note: This method waits until all threads are finished.
*
* @throws InterruptedException
*/
public void stop() throws InterruptedException {
stopAsync();
receiverThread.join();
senderThread.join();
}
/**
* Establishes connection to host specified by this object. If this is
* active connection then it will try to connect to other side. Otherwise we
* will wait until connection will be set-up using
* <code>setConnection</code> method. This method will return only if the
* connection is established and initialized properly.
*
* @return
*
* @throws InterruptedException
*/
@SuppressWarnings("resource")
private Socket connect() throws InterruptedException {
assert active;
Socket newSocket;
DataInputStream newInput;
OutputStream newOutput;
// this is active connection so we try to connect to host
while (true) {
try {
newSocket = new Socket();
newSocket.setReceiveBufferSize(TCP_BUFFER_SIZE);
newSocket.setSendBufferSize(TCP_BUFFER_SIZE);
logger.debug("RcvdBuffer: {}, SendBuffer: {}", newSocket.getReceiveBufferSize(),
newSocket.getSendBufferSize());
newSocket.setTcpNoDelay(true);
logger.info("Connecting to: {}", replica);
try {
newSocket.connect(new InetSocketAddress(replica.getHostname(),
replica.getReplicaPort()),
(int) processDescriptor.tcpReconnectTimeout);
} catch (ConnectException e) {
logger.info("TCP connection with replica {} failed: {}",
replica.getId(), e.getMessage());
Thread.sleep(processDescriptor.tcpReconnectTimeout);
continue;
} catch (SocketTimeoutException e) {
logger.info("TCP connection with replica {} timed out", replica.getId());
continue;
} catch (SocketException e) {
if (newSocket.isClosed()) {
logger.warn("Invoking connect() on closed socket. Quitting?");
return null;
}
logger.warn("TCP connection with replica {} failed: {}",
replica.getId(), e.getMessage());
Thread.sleep(processDescriptor.tcpReconnectTimeout);
continue;
} catch (IOException e) {
throw new RuntimeException("what else can be thrown here?", e);
}
newInput = new DataInputStream(new BufferedInputStream(newSocket.getInputStream()));
newOutput = newSocket.getOutputStream();
byte buf[] = new byte[4];
ByteBuffer.wrap(buf).putInt(processDescriptor.localId);
try {
newOutput.write(buf);
newOutput.flush();
} catch (SocketException e) {
/*- Caused by: <SUF>*/
logger.warn("TCP connection with replica {} failed: {}",
replica.getId(), e.getMessage());
continue;
}
// connection established
break;
} catch (IOException e) {
throw new RuntimeException("Unexpected error connecting to " + replica, e);
}
}
logger.info("TCP connect successfull to {}", replica);
// Wake up the sender thread
synchronized (connectedLock) {
socket = newSocket;
input = newInput;
output = newOutput;
connected = true;
// notify sender
connectedLock.notifyAll();
}
network.addConnection(peerId, this);
return newSocket;
}
/**
* Closes the connection.
*
* @param victim - close can race with many methods (e.g. connect), so tell
* it what you want to close to prevent races
*/
private void close(Socket victim) {
synchronized (connectedLock) {
if (socket != victim)
return;
if (active)
network.removeConnection(peerId, this);
closing = true;
connected = false;
if (socket != null) {
if (socket.isConnected())
try {
logger.info("Closing TCP connection to {}", replica);
socket.shutdownOutput();
socket.close();
logger.debug("TCP connection closed to {}", replica);
} catch (IOException e) {
logger.warn("Error closing socket", e);
}
socket = null;
}
}
}
private final static Logger logger = LoggerFactory.getLogger(TcpConnection.class);
}
| null |
8762_1 | Jblew/marines-mud | 3,222 | src/marinesmud/tap/commands/CommandRouter.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package marinesmud.tap.commands;
import java.util.Arrays;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import marinesmud.tap.commands.annotations.ForAdmins;
import marinesmud.tap.commands.annotations.MaxParameters;
import marinesmud.tap.commands.annotations.MinParameters;
import marinesmud.tap.commands.annotations.MinimalCommandLength;
import marinesmud.tap.commands.annotations.NoParameters;
import marinesmud.tap.commands.annotations.ParametersCount;
import marinesmud.tap.commands.annotations.RestPositionDisallowed;
import marinesmud.tap.commands.annotations.ShortDescription;
import marinesmud.tap.commands.annotations.SleepPositionDisallowed;
import marinesmud.tap.commands.annotations.StandPositionDisallowed;
import marinesmud.system.Config;
import pl.jblew.code.jutils.data.containers.tuples.FourTuple;
import marinesmud.tap.commands.annotations.Aliased;
import marinesmud.world.Position;
import marinesmud.tap.commands.annotations.FightPositionDisallowed;
import marinesmud.tap.TelnetGameplay;
import marinesmud.world.beings.Player;
import pl.jblew.code.jutils.utils.ExceptionUtils;
import pl.jblew.code.jutils.utils.TextUtils;
/**
*
* * @author jblew * @license Kod jest objęty licencją zawartą w pliku LICESNE
*/
class BooleanStringMethodObjectTuple extends FourTuple<Boolean, String, Method, Object> {
public BooleanStringMethodObjectTuple(Boolean b, String s, Method m, Object o) {
super(b, s, m, o);
}
}
public final class CommandRouter {
private final TelnetGameplay telnetGameplay;
private final Player player;
private String input = null;
private String commandName = null;
private String commandData = "";
private LinkedList<String> commandParams = new LinkedList<String>();
private BooleanStringMethodObjectTuple[] commands = null;
public CommandRouter(TelnetGameplay telnetGameplay, Player player) {
this.telnetGameplay = telnetGameplay;
this.player = player;
try {
commands = new BooleanStringMethodObjectTuple[]{
generateCommandTuple(false, "gecho", AdminCommands.getInstance()),
generateCommandTuple(false, "mtime", AdminCommands.getInstance()),
generateCommandTuple(false, "look", AreaCommands.getInstance()),
generateCommandTuple(false, "immtalk", AdminCommands.getInstance()),
generateCommandTuple(false, "say", CommunicationCommands.getInstance()),
generateCommandTuple(false, "help", HelpCommand.getInstance()),
generateCommandTuple(false, "idea", IdeaBugTodoCommands.getInstance()),
generateCommandTuple(false, "bug", IdeaBugTodoCommands.getInstance()),
generateCommandTuple(false, "todo", IdeaBugTodoCommands.getInstance()),
generateCommandTuple(false, "stand", PositionCommands.getInstance()),
generateCommandTuple(false, "rest", PositionCommands.getInstance()),
generateCommandTuple(false, "sleep", PositionCommands.getInstance()),
generateCommandTuple(false, "wake", PositionCommands.getInstance())
};
} catch (NoSuchMethodException ex) {
Logger.getLogger(CommandRouter.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(CommandRouter.class.getName()).log(Level.SEVERE, null, ex);
}
}
private BooleanStringMethodObjectTuple generateCommandTuple(boolean isAliased, String commandName, Object instance) throws NoSuchMethodException {
return (new BooleanStringMethodObjectTuple(isAliased, commandName, instance.getClass().getDeclaredMethod(commandName, CommandRouter.class), instance));
}
private BooleanStringMethodObjectTuple generateCommandTuple(boolean isAliased, String commandName, String methodName, Object instance) throws NoSuchMethodException {
return (new BooleanStringMethodObjectTuple(isAliased, commandName, instance.getClass().getDeclaredMethod(methodName, CommandRouter.class), instance));
}
public String command(String input_) {
String out = "";
String errorMessage = "";
boolean commandFine = false;
input = input_;
commandParams.clear();
commandName = "";
commandData = "";
String logEntry = "";
logEntry += "[" + player.getName() + "] " + input;
List<Map<String, String>> fastCommandShortcut = Config.getList("fast commands shortcuts");
for (Map<String, String> m : fastCommandShortcut) {
String shortcut = m.get("shortcut");
String command = m.get("command");
if (input.trim().equalsIgnoreCase(shortcut)) {
input = ("hh235h" + input).replace("hh235h" + shortcut, command);
logEntry += " FCS{" + command + "}";
} else if (input.trim().toLowerCase().startsWith(shortcut)) {
input = ("hh235h" + input).replace("hh235h" + shortcut, command + " ");
logEntry += " FCS{" + command + "=" + input + "}";
}
}
String[] inputParts = input.split(" ", 2);
commandName = inputParts[0];
if (inputParts.length > 1) {
commandData = inputParts[1].trim();
commandParams.addAll(Arrays.asList(commandData.split(" ")));
}
for (BooleanStringMethodObjectTuple command : getCommands()) {
try {
if (!command.first) {
if (!command.third.isAnnotationPresent(ShortDescription.class)) {
throw new MissingAnnotationException("Missing annotation ShortDescription in method " + command.third.getName() + "!");
}
if (!command.third.isAnnotationPresent(MinimalCommandLength.class)) {
throw new MissingAnnotationException("Missing annotation MinimalCommandLength in method " + command.third.getName() + "!");
}
}
if (command.second.startsWith(commandName) && commandName.length() >= command.third.getAnnotation(MinimalCommandLength.class).length()) {
Position position = player.getPosition();
if (command.third.isAnnotationPresent(StandPositionDisallowed.class) && position == Position.STAND) {
throw new CommandExecutionException(command.third.getAnnotation(StandPositionDisallowed.class).message());
}
if (command.third.isAnnotationPresent(RestPositionDisallowed.class) && position == Position.REST) {
throw new CommandExecutionException(command.third.getAnnotation(RestPositionDisallowed.class).message());
}
if (command.third.isAnnotationPresent(SleepPositionDisallowed.class) && position == Position.SLEEP) {
throw new CommandExecutionException(command.third.getAnnotation(SleepPositionDisallowed.class).message());
}
if (command.third.isAnnotationPresent(FightPositionDisallowed.class) && position == Position.FIGHT) {
throw new CommandExecutionException(command.third.getAnnotation(FightPositionDisallowed.class).message());
}
if (command.third.isAnnotationPresent(ForAdmins.class) && !player.isAdmin()) {
continue;
}
if (command.third.isAnnotationPresent(NoParameters.class) && commandParams.size() > 0) {
throw new CommandExecutionException(TextUtils.ucfirst(command.third.getName()) + " nie wymaga żadnych parametrów. " + commandParams.size() + " to zbyt dużo.");
}
if (command.third.isAnnotationPresent(MinParameters.class) && commandParams.size() < command.third.getAnnotation(MinParameters.class).count()) {
throw new CommandExecutionException(command.third.getAnnotation(MinParameters.class).message().replace("%minParametersCount", String.valueOf(command.third.getAnnotation(MinParameters.class).count())).replace("%methodName", command.third.getName()));
}
if (command.third.isAnnotationPresent(MaxParameters.class) && commandParams.size() > command.third.getAnnotation(MaxParameters.class).count()) {
throw new CommandExecutionException(command.third.getAnnotation(MaxParameters.class).message().replace("%maxParametersCount", String.valueOf(command.third.getAnnotation(MaxParameters.class).count())).replace("%methodName", command.third.getName()));
}
if (command.third.isAnnotationPresent(ParametersCount.class) && commandParams.size() > command.third.getAnnotation(ParametersCount.class).count()) {
throw new CommandExecutionException(command.third.getAnnotation(ParametersCount.class).tooManyMessage().replace("%wantedParametersCount", String.valueOf(command.third.getAnnotation(ParametersCount.class).count())).replace("%methodName", command.third.getName()));
}
if (command.third.isAnnotationPresent(ParametersCount.class) && commandParams.size() < command.third.getAnnotation(ParametersCount.class).count()) {
throw new CommandExecutionException(command.third.getAnnotation(ParametersCount.class).notEnoughMessage().replace("%wantedParametersCount", String.valueOf(command.third.getAnnotation(ParametersCount.class).count())).replace("%methodName", command.third.getName()));
}
out += command.third.invoke(command.fourth, this);
commandFine = true;
break; //if no exception was thrown
} else if (command.third.isAnnotationPresent(Aliased.class)) {
out += command.third.invoke(command.fourth, this);
commandFine = true;
break; //if no exception was thrown
}
} catch (IllegalAccessException ex) {
Logger.getLogger(CommandRouter.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(CommandRouter.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
if (ex.getCause() instanceof CommandExecutionException) {
errorMessage = ex.getMessage();
} else {
commandFine = true;
out += "Wystąpił błąd podczas wykonywania komendy. Przepraszamy.\n";
if (player.isAdmin()) {
out += ExceptionUtils.getLongDescription(ex.getCause()) + "\n";
ex.getCause().getStackTrace();
}
Logger.getLogger(CommandRouter.class.getName()).log(Level.SEVERE, null, ex.getCause());
break;
}
} catch (CommandExecutionException ex) {
errorMessage = ex.getMessage();
}
}
if (!commandFine) {
if (!errorMessage.isEmpty()) {
out += errorMessage.replace("%parametersCount", String.valueOf(commandParams.size())) + "\n";
} else {
out += "Masz jakiś problem!?\n";
}
}
Logger.getLogger("Commands").log(Level.INFO, logEntry);
return out;
}
public Player getPlayer() {
return player;
}
public String getCommandData() {
return commandData;
}
public String getCommandName() {
return commandName;
}
public List<String> getParams() {
return Collections.unmodifiableList(commandParams);
}
public String getInput() {
return input;
}
public void cleanCommands() {
}
public BooleanStringMethodObjectTuple[] getCommands() {
return commands;
}
public void setCommands(BooleanStringMethodObjectTuple[] commands) {
this.commands = commands;
}
}
| /**
*
* * @author jblew * @license Kod jest objęty licencją zawartą w pliku LICESNE
*/ | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package marinesmud.tap.commands;
import java.util.Arrays;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import marinesmud.tap.commands.annotations.ForAdmins;
import marinesmud.tap.commands.annotations.MaxParameters;
import marinesmud.tap.commands.annotations.MinParameters;
import marinesmud.tap.commands.annotations.MinimalCommandLength;
import marinesmud.tap.commands.annotations.NoParameters;
import marinesmud.tap.commands.annotations.ParametersCount;
import marinesmud.tap.commands.annotations.RestPositionDisallowed;
import marinesmud.tap.commands.annotations.ShortDescription;
import marinesmud.tap.commands.annotations.SleepPositionDisallowed;
import marinesmud.tap.commands.annotations.StandPositionDisallowed;
import marinesmud.system.Config;
import pl.jblew.code.jutils.data.containers.tuples.FourTuple;
import marinesmud.tap.commands.annotations.Aliased;
import marinesmud.world.Position;
import marinesmud.tap.commands.annotations.FightPositionDisallowed;
import marinesmud.tap.TelnetGameplay;
import marinesmud.world.beings.Player;
import pl.jblew.code.jutils.utils.ExceptionUtils;
import pl.jblew.code.jutils.utils.TextUtils;
/**
*
* * @author jblew <SUF>*/
class BooleanStringMethodObjectTuple extends FourTuple<Boolean, String, Method, Object> {
public BooleanStringMethodObjectTuple(Boolean b, String s, Method m, Object o) {
super(b, s, m, o);
}
}
public final class CommandRouter {
private final TelnetGameplay telnetGameplay;
private final Player player;
private String input = null;
private String commandName = null;
private String commandData = "";
private LinkedList<String> commandParams = new LinkedList<String>();
private BooleanStringMethodObjectTuple[] commands = null;
public CommandRouter(TelnetGameplay telnetGameplay, Player player) {
this.telnetGameplay = telnetGameplay;
this.player = player;
try {
commands = new BooleanStringMethodObjectTuple[]{
generateCommandTuple(false, "gecho", AdminCommands.getInstance()),
generateCommandTuple(false, "mtime", AdminCommands.getInstance()),
generateCommandTuple(false, "look", AreaCommands.getInstance()),
generateCommandTuple(false, "immtalk", AdminCommands.getInstance()),
generateCommandTuple(false, "say", CommunicationCommands.getInstance()),
generateCommandTuple(false, "help", HelpCommand.getInstance()),
generateCommandTuple(false, "idea", IdeaBugTodoCommands.getInstance()),
generateCommandTuple(false, "bug", IdeaBugTodoCommands.getInstance()),
generateCommandTuple(false, "todo", IdeaBugTodoCommands.getInstance()),
generateCommandTuple(false, "stand", PositionCommands.getInstance()),
generateCommandTuple(false, "rest", PositionCommands.getInstance()),
generateCommandTuple(false, "sleep", PositionCommands.getInstance()),
generateCommandTuple(false, "wake", PositionCommands.getInstance())
};
} catch (NoSuchMethodException ex) {
Logger.getLogger(CommandRouter.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(CommandRouter.class.getName()).log(Level.SEVERE, null, ex);
}
}
private BooleanStringMethodObjectTuple generateCommandTuple(boolean isAliased, String commandName, Object instance) throws NoSuchMethodException {
return (new BooleanStringMethodObjectTuple(isAliased, commandName, instance.getClass().getDeclaredMethod(commandName, CommandRouter.class), instance));
}
private BooleanStringMethodObjectTuple generateCommandTuple(boolean isAliased, String commandName, String methodName, Object instance) throws NoSuchMethodException {
return (new BooleanStringMethodObjectTuple(isAliased, commandName, instance.getClass().getDeclaredMethod(methodName, CommandRouter.class), instance));
}
public String command(String input_) {
String out = "";
String errorMessage = "";
boolean commandFine = false;
input = input_;
commandParams.clear();
commandName = "";
commandData = "";
String logEntry = "";
logEntry += "[" + player.getName() + "] " + input;
List<Map<String, String>> fastCommandShortcut = Config.getList("fast commands shortcuts");
for (Map<String, String> m : fastCommandShortcut) {
String shortcut = m.get("shortcut");
String command = m.get("command");
if (input.trim().equalsIgnoreCase(shortcut)) {
input = ("hh235h" + input).replace("hh235h" + shortcut, command);
logEntry += " FCS{" + command + "}";
} else if (input.trim().toLowerCase().startsWith(shortcut)) {
input = ("hh235h" + input).replace("hh235h" + shortcut, command + " ");
logEntry += " FCS{" + command + "=" + input + "}";
}
}
String[] inputParts = input.split(" ", 2);
commandName = inputParts[0];
if (inputParts.length > 1) {
commandData = inputParts[1].trim();
commandParams.addAll(Arrays.asList(commandData.split(" ")));
}
for (BooleanStringMethodObjectTuple command : getCommands()) {
try {
if (!command.first) {
if (!command.third.isAnnotationPresent(ShortDescription.class)) {
throw new MissingAnnotationException("Missing annotation ShortDescription in method " + command.third.getName() + "!");
}
if (!command.third.isAnnotationPresent(MinimalCommandLength.class)) {
throw new MissingAnnotationException("Missing annotation MinimalCommandLength in method " + command.third.getName() + "!");
}
}
if (command.second.startsWith(commandName) && commandName.length() >= command.third.getAnnotation(MinimalCommandLength.class).length()) {
Position position = player.getPosition();
if (command.third.isAnnotationPresent(StandPositionDisallowed.class) && position == Position.STAND) {
throw new CommandExecutionException(command.third.getAnnotation(StandPositionDisallowed.class).message());
}
if (command.third.isAnnotationPresent(RestPositionDisallowed.class) && position == Position.REST) {
throw new CommandExecutionException(command.third.getAnnotation(RestPositionDisallowed.class).message());
}
if (command.third.isAnnotationPresent(SleepPositionDisallowed.class) && position == Position.SLEEP) {
throw new CommandExecutionException(command.third.getAnnotation(SleepPositionDisallowed.class).message());
}
if (command.third.isAnnotationPresent(FightPositionDisallowed.class) && position == Position.FIGHT) {
throw new CommandExecutionException(command.third.getAnnotation(FightPositionDisallowed.class).message());
}
if (command.third.isAnnotationPresent(ForAdmins.class) && !player.isAdmin()) {
continue;
}
if (command.third.isAnnotationPresent(NoParameters.class) && commandParams.size() > 0) {
throw new CommandExecutionException(TextUtils.ucfirst(command.third.getName()) + " nie wymaga żadnych parametrów. " + commandParams.size() + " to zbyt dużo.");
}
if (command.third.isAnnotationPresent(MinParameters.class) && commandParams.size() < command.third.getAnnotation(MinParameters.class).count()) {
throw new CommandExecutionException(command.third.getAnnotation(MinParameters.class).message().replace("%minParametersCount", String.valueOf(command.third.getAnnotation(MinParameters.class).count())).replace("%methodName", command.third.getName()));
}
if (command.third.isAnnotationPresent(MaxParameters.class) && commandParams.size() > command.third.getAnnotation(MaxParameters.class).count()) {
throw new CommandExecutionException(command.third.getAnnotation(MaxParameters.class).message().replace("%maxParametersCount", String.valueOf(command.third.getAnnotation(MaxParameters.class).count())).replace("%methodName", command.third.getName()));
}
if (command.third.isAnnotationPresent(ParametersCount.class) && commandParams.size() > command.third.getAnnotation(ParametersCount.class).count()) {
throw new CommandExecutionException(command.third.getAnnotation(ParametersCount.class).tooManyMessage().replace("%wantedParametersCount", String.valueOf(command.third.getAnnotation(ParametersCount.class).count())).replace("%methodName", command.third.getName()));
}
if (command.third.isAnnotationPresent(ParametersCount.class) && commandParams.size() < command.third.getAnnotation(ParametersCount.class).count()) {
throw new CommandExecutionException(command.third.getAnnotation(ParametersCount.class).notEnoughMessage().replace("%wantedParametersCount", String.valueOf(command.third.getAnnotation(ParametersCount.class).count())).replace("%methodName", command.third.getName()));
}
out += command.third.invoke(command.fourth, this);
commandFine = true;
break; //if no exception was thrown
} else if (command.third.isAnnotationPresent(Aliased.class)) {
out += command.third.invoke(command.fourth, this);
commandFine = true;
break; //if no exception was thrown
}
} catch (IllegalAccessException ex) {
Logger.getLogger(CommandRouter.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(CommandRouter.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
if (ex.getCause() instanceof CommandExecutionException) {
errorMessage = ex.getMessage();
} else {
commandFine = true;
out += "Wystąpił błąd podczas wykonywania komendy. Przepraszamy.\n";
if (player.isAdmin()) {
out += ExceptionUtils.getLongDescription(ex.getCause()) + "\n";
ex.getCause().getStackTrace();
}
Logger.getLogger(CommandRouter.class.getName()).log(Level.SEVERE, null, ex.getCause());
break;
}
} catch (CommandExecutionException ex) {
errorMessage = ex.getMessage();
}
}
if (!commandFine) {
if (!errorMessage.isEmpty()) {
out += errorMessage.replace("%parametersCount", String.valueOf(commandParams.size())) + "\n";
} else {
out += "Masz jakiś problem!?\n";
}
}
Logger.getLogger("Commands").log(Level.INFO, logEntry);
return out;
}
public Player getPlayer() {
return player;
}
public String getCommandData() {
return commandData;
}
public String getCommandName() {
return commandName;
}
public List<String> getParams() {
return Collections.unmodifiableList(commandParams);
}
public String getInput() {
return input;
}
public void cleanCommands() {
}
public BooleanStringMethodObjectTuple[] getCommands() {
return commands;
}
public void setCommands(BooleanStringMethodObjectTuple[] commands) {
this.commands = commands;
}
}
| null |
10275_0 | Jeremylaby/PO_2023_SR1820_BARYCKI | 155 | Party_Animals/src/main/java/agh/ics/oop/model/ConsoleMapDisplay.java | package agh.ics.oop.model;
public class ConsoleMapDisplay implements MapChangeListener {
private int operationCounter = 0;
@Override
public synchronized void mapChanged(WorldMap worldMap, String message) {//Wiem że w zadaniu była podana innakolejność ale tak jest dla mnie bardziej czytelna
operationCounter++;
System.out.println("Map id: " + worldMap.getId());
System.out.println("Update nr " + operationCounter + ":");
System.out.println(message);
System.out.println(worldMap.toString());
}
}
| //Wiem że w zadaniu była podana innakolejność ale tak jest dla mnie bardziej czytelna | package agh.ics.oop.model;
public class ConsoleMapDisplay implements MapChangeListener {
private int operationCounter = 0;
@Override
public synchronized void mapChanged(WorldMap worldMap, String message) {//Wiem że <SUF>
operationCounter++;
System.out.println("Map id: " + worldMap.getId());
System.out.println("Update nr " + operationCounter + ":");
System.out.println(message);
System.out.println(worldMap.toString());
}
}
| null |
9383_6 | Job-Smart-Solutions/JSSDatabaseFramework | 7,753 | src/jss/database/FieldLister.java | package jss.database;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import jss.database.annotations.DbField;
import jss.database.annotations.DbForeignKey;
import jss.database.annotations.DbManyToOne;
import jss.database.annotations.DbOneToOne;
import jss.database.annotations.DbPrimaryKey;
import jss.database.annotations.DbTable;
import jss.database.annotations.DbView;
import jss.database.annotations.DbViewField;
import jss.database.annotations.DbViewObject;
import jss.database.mappers.SqlTypeMapper;
import jss.database.types.SqlType;
public class FieldLister {
private final Database db;
private final String tableName;// table name
private final Class<?> tableClass;// entity class
private final DbView dbView;
private final List<DbFieldInfo> dbFields = new ArrayList<>();
private final List<DbManyToOneInfo> dbManyToOne = new ArrayList<>();
private final List<DbOneToOneInfo> dbOneToOne = new ArrayList<>();
private final List<DbViewFieldInfo> dbViewFields = new ArrayList<>();
private final List<DbViewObjectInfo> dbViewObjects = new ArrayList<>();
private boolean lazyLoadedFields = false;// loaded fields by listFields()?
private boolean lazyLoadedDatabaseTypes = false;// loaded database types?
/**
* @param db database framework instance
* @param tableClass entity class
* @throws DatabaseException no DbTable or DbView annotation
*/
FieldLister(Database db, Class<?> tableClass) throws DatabaseException {
this.db = db;
// get table name and class
if (tableClass.isAnnotationPresent(DbView.class)) {// view
dbView = tableClass.getAnnotation(DbView.class);
this.tableName = dbView.name();
} else if (tableClass.isAnnotationPresent(DbTable.class)) {// table
this.tableName = tableClass.getAnnotation(DbTable.class).value();
dbView = null;
} else {
throw new DatabaseException("No 'DbTable' or 'DbView' annotation in class " + tableClass.getName());
}
this.tableClass = tableClass;
}
/**
* List fields from table class (and superclasses)
*
* @throws DatabaseException
*/
void listFields() throws DatabaseException {
if (lazyLoadedFields) {// if fields loaded, do nothing
return;
}
// listuj pola klasy oraz klas nadrzędnych
Class<?> clazz = tableClass;
if (isView()) {
do {
listFieldsForView(clazz);
clazz = clazz.getSuperclass();
} while (!clazz.equals(Object.class));
} else {// table
do {
listFields(clazz);
clazz = clazz.getSuperclass();
} while (!clazz.equals(Object.class));
}
lazyLoadedFields = true;// loaded fields
}
/**
* List fields from class - for table
*
* @param clazz class to list fields
* @throws DatabaseException
*/
private void listFields(Class<?> clazz) throws DatabaseException {
Field[] fields = clazz.getDeclaredFields();// pobierz wszystkie pola z klasy
for (Field field : fields) {
field.setAccessible(true); // możliwość dostępu nawet jeżeli pole jest prywatne
if (field.isAnnotationPresent(DbField.class)) {// database field
DbFieldInfo info = processDbField(field, clazz);
dbFields.add(info);
if (field.isAnnotationPresent(DbPrimaryKey.class)) {// primary key field
DbPrimaryKeyInfo pkInfo = processDbPrimaryKey(field);
info.primaryKeyInfo = pkInfo;
}
if (field.isAnnotationPresent(DbForeignKey.class)) {// foreign key field
DbForeignKeyInfo fkInfo = processDbForeignKey(field, clazz);
info.foreignKeyInfo = fkInfo;
}
} else if (field.isAnnotationPresent(DbManyToOne.class)) {// many to one collection
DbManyToOneInfo info = processDbManyToOne(field);
dbManyToOne.add(info);
} else if (field.isAnnotationPresent(DbOneToOne.class)) {// one to one relation
DbOneToOneInfo info = processDbOneToOne(field);
dbOneToOne.add(info);
}
} // for fields
}
/**
* List fields from class - for view
*
* @param clazz class to list fields
* @throws DatabaseException
*/
private void listFieldsForView(Class<?> clazz) throws DatabaseException {
Field[] fields = clazz.getDeclaredFields();// pobierz wszystkie pola z klasy
for (Field field : fields) {
field.setAccessible(true); // możliwość dostępu nawet jeżeli pole jest prywatne
if (field.isAnnotationPresent(DbViewField.class)) {// view field
DbViewFieldInfo info = processDbViewField(field, clazz);
dbViewFields.add(info);
} else if (field.isAnnotationPresent(DbViewObject.class)) {// view object
dbViewObjects.add(processDbViewObject(field, clazz));
}
}
}
/**
* Load database types
*
* @param mapper native type to SQL type mapper
* @throws DatabaseException cannot determine type, or error when listing fields
*/
void loadDatabaseTypes(SqlTypeMapper mapper) throws DatabaseException {
if (lazyLoadedDatabaseTypes) {// if loaded types, do nothing
return;
}
if (!lazyLoadedFields) {// if fields not loaded - load it
this.listFields();
}
for (DbFieldInfo fieldInfo : dbFields) {
Class<?> nativeType = fieldInfo.getNativeType();// native java type
// sql type
SqlType sqlType = fieldInfo.fieldAnnotation.type();
if (sqlType == SqlType.DEFAULT) {// default type - determine
sqlType = mapper.getSqlType(nativeType);
}
if (sqlType == SqlType.UNKNOWN) {// cannot determine type
throw new DatabaseException("Cannot determine SQL type of " + nativeType.getName());
}
fieldInfo.sqlType = sqlType;// SQL type
// get sql string type for current database
String fieldSqlStr = db.getDb().getTypeString(fieldInfo);
if (fieldSqlStr == null) {
throw new DatabaseException("Cannot get type " + fieldInfo.sqlType + " for database!");
}
DbField dbField = fieldInfo.getFieldAnnotation();
// replace string len value
int strLen = dbField.stringLen();
if (strLen == -1) {
strLen = db.getConfig().defaultStringLen;
}
fieldSqlStr = fieldSqlStr.replace("{strlen}", Integer.toString(strLen));
// replace decimal precision
int precistion = dbField.decimalPrecision();
if (precistion == -1) {
precistion = db.getConfig().defaultDecimalPrecision;
}
fieldSqlStr = fieldSqlStr.replace("{precision}", Integer.toString(precistion));
// replace decimal scale
int scale = dbField.decimalScale();
if (scale == -1) {
scale = db.getConfig().defaultDecimalScale;
}
fieldSqlStr = fieldSqlStr.replace("{scale}", Integer.toString(scale));
fieldInfo.sqlTypeString = fieldSqlStr;// SQL type string
}
}
/**
* Process DbField annotation
*
* @param field field in class
* @param clazz current processing class
* @return database field info
*/
private DbFieldInfo processDbField(Field field, Class<?> clazz) {
DbField dbField = field.getAnnotation(DbField.class);// pobierz element adnotacji
DbFieldInfo info = new DbFieldInfo();
info.fieldAnnotation = dbField;
info.clazz = clazz;
info.fieldInClass = field;
// in table name
info.inTableName = dbField.name();// custom name
if (info.inTableName.isEmpty()) {// if custom name empty, use class name
info.inTableName = field.getName();
}
return info;
}
/**
* Process DbPrimaryKey annotation
*
* @param field field info
* @return primary key info
* @throws DatabaseException
*/
private DbPrimaryKeyInfo processDbPrimaryKey(Field field) throws DatabaseException {
if (!field.isAnnotationPresent(DbField.class)) {
throw new DatabaseException("No annotation DbField on DbPrimaryKey!");
}
DbPrimaryKey dbPrimaryKey = field.getAnnotation(DbPrimaryKey.class);
DbPrimaryKeyInfo info = new DbPrimaryKeyInfo();
info.pkAnnotation = dbPrimaryKey;
return info;
}
/**
* Process DbForeignKey annotation
*
* @param field field in class
* @param clazz current processing class
* @return foreign key info
* @throws DatabaseException
*/
private DbForeignKeyInfo processDbForeignKey(Field field, Class<?> clazz) throws DatabaseException {
if (!field.isAnnotationPresent(DbField.class)) {
throw new DatabaseException("No annotation DbField on DbForeignKey!");
}
DbForeignKey dbForeignKey = field.getAnnotation(DbForeignKey.class);
DbForeignKeyInfo info = new DbForeignKeyInfo();
info.fkAnnotation = dbForeignKey;
// load this field - field in current class for place foreing object
if (!dbForeignKey.thisField().trim().equals("")) {
try {
info.thisField = getDeclaredField(clazz, dbForeignKey.thisField());
} catch (NoSuchFieldException e) {
String fname = field.getName();// field name
String cname = clazz.getName();// class name
throw new DatabaseException("Cannot set foreign field " + fname + " for class: " + cname, e);
}
} else {
info.thisField = null;// if not field for save foreign object, set null
}
// reference class
Class<?> refObj = dbForeignKey.refObject();
// check annotation DbTable
if (!refObj.isAnnotationPresent(DbTable.class)) {
throw new DatabaseException("No 'DbTable' annotation in foreign class: " + refObj.getName());
}
// get table name
DbTable foreignDbTable = refObj.getAnnotation(DbTable.class);
info.refTableName = foreignDbTable.value();
String refFieldName = dbForeignKey.refField();// field name
String refClassName = dbForeignKey.refObject().getName();// class name
// load foreign field
Field foreignField;
try {
foreignField = getDeclaredField(dbForeignKey.refObject(), dbForeignKey.refField());
} catch (NoSuchFieldException e) {
throw new DatabaseException("Cannot found foreign field " + refFieldName + " in class: " + refClassName, e);
}
// check foreign field annotation
if (!foreignField.isAnnotationPresent(DbField.class)) {
throw new DatabaseException("No DbField annotation: " + refClassName + "::" + refFieldName);
}
DbField dbForeignField = foreignField.getAnnotation(DbField.class);
// check is unique or primary key
// TODO
// save table column name
info.refInTableName = dbForeignField.name();// custom column name
if (info.refInTableName.isEmpty()) {// default column name
info.refInTableName = foreignField.getName();
}
return info;
}
/**
* Process DbManyToOne annotation
*
* @param field field info
* @throws DatabaseException
*/
private DbManyToOneInfo processDbManyToOne(Field field) throws DatabaseException {
DbManyToOne dbMany = field.getAnnotation(DbManyToOne.class);
// sprawdź, czy pole ManyToOne jest kolekcją
if (!Collection.class.isAssignableFrom(field.getType())) {// jeżeli nie jest - rzuć wyjątek
throw new DatabaseException("Field '" + field.getName() + "' in class '"
+ field.getDeclaringClass().getName() + "' ManyToOne relation is not a collection!");
}
DbManyToOneInfo info = new DbManyToOneInfo();
info.mtoAnnotation = dbMany;
info.fieldInClass = field;
// pobierz pole w klasie obcej
try {
Field refField = getDeclaredField(dbMany.refObject(), dbMany.refField());
if (!refField.isAnnotationPresent(DbField.class) || !refField.isAnnotationPresent(DbForeignKey.class)) {
throw new DatabaseException("Relation field " + refField.getName() + " has not FK annotation!");
}
DbForeignKey dbForKey = refField.getAnnotation(DbForeignKey.class);
// ustaw pole, do którego odwołuje się ManyToOne
if (!dbForKey.thisField().isEmpty()) {// jeżeli takowe istnieje
Field refFieldOnClass = getDeclaredField(dbMany.refObject(), dbForKey.thisField());
info.refFieldObj = refFieldOnClass;
}
info.refFieldKey = refField;
} catch (NoSuchFieldException e) {
throw new DatabaseException("DbManyToOne field not found!", e);
}
return info;
}
/**
* Process DbOneToOne annotation
*
* @param field field info
* @throws DatabaseException
*/
private DbOneToOneInfo processDbOneToOne(Field field) throws DatabaseException {
DbOneToOne dbOne = field.getAnnotation(DbOneToOne.class);
DbOneToOneInfo info = new DbOneToOneInfo();
info.otoAnnotation = dbOne;
info.fieldInClass = field;
// pobierz pole w klasie obcej
try {
Field refField = getDeclaredField(dbOne.refObject(), dbOne.refField());
if (!refField.isAnnotationPresent(DbField.class) || !refField.isAnnotationPresent(DbForeignKey.class)) {
throw new DatabaseException("Relation field " + refField.getName() + " has not FK annotation!");
}
DbForeignKey dbForKey = refField.getAnnotation(DbForeignKey.class);
// ustaw pole, do którego odwołuje się ManyToOne
if (!dbForKey.thisField().isEmpty()) {// jeżeli takowe istnieje
Field refFieldOnClass = getDeclaredField(dbOne.refObject(), dbForKey.thisField());
info.refFieldObj = refFieldOnClass;
}
info.refFieldKey = refField;
} catch (NoSuchFieldException e) {
throw new DatabaseException("DbOneToOne field not found!", e);
}
return info;
}
/**
* Process DbViewFiled annotation
*
* @param field field in class
* @param clazz current processing class
* @return DbViewField info
*/
private DbViewFieldInfo processDbViewField(Field field, Class<?> clazz) {
DbViewField dbViewField = field.getAnnotation(DbViewField.class);// pobierz element adnotacji
DbViewFieldInfo info = new DbViewFieldInfo();
info.fieldAnnotation = dbViewField;
// info.clazz = clazz;
info.fieldInClass = field;
// in table name
info.inQueryName = dbViewField.value();// custom name
if (info.inQueryName.isEmpty()) {// if custom name empty, use class name
info.inQueryName = field.getName();
}
return info;
}
/**
* Process DbViewObject annotation
*
* @param field field in class
* @param clazz current processing class
* @return DbViewObject info
*/
private DbViewObjectInfo processDbViewObject(Field field, Class<?> clazz) {
DbViewObject dbViewObject = field.getAnnotation(DbViewObject.class);// pobierz element adnotacji
DbViewObjectInfo info = new DbViewObjectInfo();
info.fieldAnnotation = dbViewObject;
// info.clazz = clazz;
info.fieldInClass = field;
return info;
}
/**
* Get declared field from class or superclass
*
* @param clazz class to start search
* @param field field name
* @return field in class
* @throws NoSuchFieldException field not found
*/
private Field getDeclaredField(Class<?> clazz, String field) throws NoSuchFieldException {
do {
try {
Field f = clazz.getDeclaredField(field);
f.setAccessible(true);
return f;
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
}
} while (!clazz.equals(Object.class));
throw new NoSuchFieldException("Field not found: " + field);
}
/**
* @return table name
*/
String getTableName() {
return tableName;
}
/**
* @return table class
*/
Class<?> getTableClass() {
return tableClass;
}
/**
* @return database fields in class
*/
List<DbFieldInfo> getDbFields() {
return new ArrayList<>(dbFields);// copy
}
/**
* @return database fields or view fields in class
*/
List<DbFieldOrViewInfo> getDbFieldOrViewInfo() {
List<DbFieldOrViewInfo> ret = new ArrayList<>(dbFields);// copy
ret.addAll(dbViewFields);
return ret;
}
/**
* @return database fields which are primary keys
*/
List<DbFieldInfo> getPrimaryKeys() {
List<DbFieldInfo> pkList = new ArrayList<>(2);
for (DbFieldInfo dfi : dbFields) {
if (dfi.getPrimaryKeyInfo() != null) {
pkList.add(dfi);
}
}
return pkList;
}
/**
* @return database fields which are foreign keys
*/
List<DbFieldInfo> getForeignKeys() {
List<DbFieldInfo> fkList = new ArrayList<>(2);
for (DbFieldInfo dfi : dbFields) {
if (dfi.getForeignKeyInfo() != null) {
fkList.add(dfi);
}
}
return fkList;
}
/**
* @return database fields which are indexes
*/
List<DbFieldInfo> getIndexes() {
List<DbFieldInfo> indexes = new ArrayList<>(2);
for (DbFieldInfo dfi : dbFields) {
if (dfi.fieldAnnotation.isIndex()) {
indexes.add(dfi);
}
}
return indexes;
}
/**
* Get field by name in class
*
* @param string field name in class
* @return field, or null if not found
*/
DbFieldOrViewInfo getFieldByInClassName(String name) {
for (DbFieldInfo df : dbFields) {
if (df.getFieldInClass().getName().equals(name)) {
return df;
}
}
for (DbViewFieldInfo df : dbViewFields) {
if (df.getFieldInClass().getName().equals(name)) {
return df;
}
}
return null;
}
/**
* @return fields for ManyToOne relations
*/
List<DbManyToOneInfo> getDbManyToOne() {
return dbManyToOne;
}
/**
* @return fields for OneToOne relations
*/
List<DbOneToOneInfo> getDbOneToOne() {
return dbOneToOne;
}
/**
* @return this is view?
*/
boolean isView() {
return dbView != null;
}
/**
* @return DbView annotation
*/
DbView getDbView() {
return dbView;
}
/**
* @return DbViewObject list info for view
*/
List<DbViewObjectInfo> getDbViewObjects() {
return dbViewObjects;
}
/**
* Database field info
*
* @author lukas
*/
public class DbFieldInfo implements DbFieldOrViewInfo {
DbFieldInfo() {// not public constructor
}
/**
* DbField annotation
*/
DbField fieldAnnotation;
/**
* Class in which the field is located (for superclasses support)
*/
Class<?> clazz;
/**
* Field in class
*/
Field fieldInClass;
/**
* Column name in table
*/
String inTableName;
/**
* SQL type
*/
SqlType sqlType;
/**
* SQL type string for current database type
*/
String sqlTypeString;
/**
* Primary key info
*/
DbPrimaryKeyInfo primaryKeyInfo;
/**
* Foreign key info
*/
DbForeignKeyInfo foreignKeyInfo;
/**
* @return DbField annotation
*/
public DbField getFieldAnnotation() {
return fieldAnnotation;
}
@Override
public Field getFieldInClass() {
return fieldInClass;
}
/**
* @return SQL type
*/
public SqlType getSqlType() {
return sqlType;
}
/**
* @return primary key info (or null)
*/
public DbPrimaryKeyInfo getPrimaryKeyInfo() {
return primaryKeyInfo;
}
/**
* @return foreign key info (or null)
*/
public DbForeignKeyInfo getForeignKeyInfo() {
return foreignKeyInfo;
}
@Override
public String getInQueryName() {
return tableName + '_' + inTableName;
}
@Override
public String getInTableName() {
return inTableName;
}
}
/**
* Primary key info
*
* @author lukas
*/
public class DbPrimaryKeyInfo {
DbPrimaryKeyInfo() {// not public constructor
}
/**
* DbPrimaryKey annotation
*/
DbPrimaryKey pkAnnotation;
/**
* @return DbPrimaryKey annotation
*/
public DbPrimaryKey getPkAnnotation() {
return pkAnnotation;
}
}
/**
* Foreign key info
*
* @author lukas
*/
public class DbForeignKeyInfo {
DbForeignKeyInfo() {// not public constructor
}
/**
* DbForeignKey annotation
*/
DbForeignKey fkAnnotation;
/**
* Field in class for store foreign object
*/
Field thisField;
/**
* Foreign table name
*/
String refTableName;
/**
* Foreign column name
*/
String refInTableName;
/**
* @return DbForeignKey annotation
*/
public DbForeignKey getFkAnnotation() {
return fkAnnotation;
}
}
/**
* Many to one info
*
* @author lukas
*/
public class DbManyToOneInfo {
DbManyToOneInfo() {// not public constructor
}
/**
* DbManyToOne annotation
*/
DbManyToOne mtoAnnotation;
/**
* Field in class
*/
Field fieldInClass;
/**
* Field in ref class - foreign key field
*/
Field refFieldKey;
/**
* Field in ref class - object field
*/
Field refFieldObj;
/**
* @return DbManyToOne annotation
*/
public DbManyToOne getMtoAnnotation() {
return mtoAnnotation;
}
}
/**
* One to one info
*
* @author lukas
*/
public class DbOneToOneInfo {
DbOneToOneInfo() {// not public constructor
}
/**
* DbOneToOne annotation
*/
DbOneToOne otoAnnotation;
/**
* Field in class
*/
Field fieldInClass;
/**
* Field in ref class - foreign key field
*/
Field refFieldKey;
/**
* Field in ref class - object field
*/
Field refFieldObj;
/**
* @return DbManyToOne annotation
*/
public DbOneToOne getOtoAnnotation() {
return otoAnnotation;
}
}
/**
* VIEW field info
*
* @author lukas
*/
public class DbViewFieldInfo implements DbFieldOrViewInfo {
DbViewFieldInfo() {
}
/**
* DbViewField annotation
*/
DbViewField fieldAnnotation;
/**
* Class in which the field is located (for superclasses support)
*/
// Class<?> clazz;
/**
* Field in class
*/
Field fieldInClass;
/**
* Column name in query
*/
String inQueryName;
@Override
public String getInQueryName() {
return inQueryName;
}
@Override
public String getInTableName() {
return inQueryName;
}
@Override
public Field getFieldInClass() {
return fieldInClass;
}
}
/**
* VIEW object info
*
* @author lukas
*/
public class DbViewObjectInfo {
DbViewObjectInfo() {
}
/**
* DbViewObject annotation
*/
DbViewObject fieldAnnotation;
/**
* Class in which the field is located (for superclasses support)
*/
// Class<?> clazz;
/**
* Field in class
*/
Field fieldInClass;
}
public interface DbFieldOrViewInfo {
/**
* @return name in query
*/
public String getInQueryName();
/**
* @return name in table
*/
public String getInTableName();
/**
* @return field in class
*/
public Field getFieldInClass();
/**
* @return native java type
*/
default public Class<?> getNativeType() {
return getFieldInClass().getType();
}
/**
* @param clazz native type to check
* @return is native type?
*/
default public boolean nativeTypeIs(Class<?> clazz) {
return getNativeType().isAssignableFrom(clazz);
}
}
}
| // listuj pola klasy oraz klas nadrzędnych | package jss.database;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import jss.database.annotations.DbField;
import jss.database.annotations.DbForeignKey;
import jss.database.annotations.DbManyToOne;
import jss.database.annotations.DbOneToOne;
import jss.database.annotations.DbPrimaryKey;
import jss.database.annotations.DbTable;
import jss.database.annotations.DbView;
import jss.database.annotations.DbViewField;
import jss.database.annotations.DbViewObject;
import jss.database.mappers.SqlTypeMapper;
import jss.database.types.SqlType;
public class FieldLister {
private final Database db;
private final String tableName;// table name
private final Class<?> tableClass;// entity class
private final DbView dbView;
private final List<DbFieldInfo> dbFields = new ArrayList<>();
private final List<DbManyToOneInfo> dbManyToOne = new ArrayList<>();
private final List<DbOneToOneInfo> dbOneToOne = new ArrayList<>();
private final List<DbViewFieldInfo> dbViewFields = new ArrayList<>();
private final List<DbViewObjectInfo> dbViewObjects = new ArrayList<>();
private boolean lazyLoadedFields = false;// loaded fields by listFields()?
private boolean lazyLoadedDatabaseTypes = false;// loaded database types?
/**
* @param db database framework instance
* @param tableClass entity class
* @throws DatabaseException no DbTable or DbView annotation
*/
FieldLister(Database db, Class<?> tableClass) throws DatabaseException {
this.db = db;
// get table name and class
if (tableClass.isAnnotationPresent(DbView.class)) {// view
dbView = tableClass.getAnnotation(DbView.class);
this.tableName = dbView.name();
} else if (tableClass.isAnnotationPresent(DbTable.class)) {// table
this.tableName = tableClass.getAnnotation(DbTable.class).value();
dbView = null;
} else {
throw new DatabaseException("No 'DbTable' or 'DbView' annotation in class " + tableClass.getName());
}
this.tableClass = tableClass;
}
/**
* List fields from table class (and superclasses)
*
* @throws DatabaseException
*/
void listFields() throws DatabaseException {
if (lazyLoadedFields) {// if fields loaded, do nothing
return;
}
// listuj pola <SUF>
Class<?> clazz = tableClass;
if (isView()) {
do {
listFieldsForView(clazz);
clazz = clazz.getSuperclass();
} while (!clazz.equals(Object.class));
} else {// table
do {
listFields(clazz);
clazz = clazz.getSuperclass();
} while (!clazz.equals(Object.class));
}
lazyLoadedFields = true;// loaded fields
}
/**
* List fields from class - for table
*
* @param clazz class to list fields
* @throws DatabaseException
*/
private void listFields(Class<?> clazz) throws DatabaseException {
Field[] fields = clazz.getDeclaredFields();// pobierz wszystkie pola z klasy
for (Field field : fields) {
field.setAccessible(true); // możliwość dostępu nawet jeżeli pole jest prywatne
if (field.isAnnotationPresent(DbField.class)) {// database field
DbFieldInfo info = processDbField(field, clazz);
dbFields.add(info);
if (field.isAnnotationPresent(DbPrimaryKey.class)) {// primary key field
DbPrimaryKeyInfo pkInfo = processDbPrimaryKey(field);
info.primaryKeyInfo = pkInfo;
}
if (field.isAnnotationPresent(DbForeignKey.class)) {// foreign key field
DbForeignKeyInfo fkInfo = processDbForeignKey(field, clazz);
info.foreignKeyInfo = fkInfo;
}
} else if (field.isAnnotationPresent(DbManyToOne.class)) {// many to one collection
DbManyToOneInfo info = processDbManyToOne(field);
dbManyToOne.add(info);
} else if (field.isAnnotationPresent(DbOneToOne.class)) {// one to one relation
DbOneToOneInfo info = processDbOneToOne(field);
dbOneToOne.add(info);
}
} // for fields
}
/**
* List fields from class - for view
*
* @param clazz class to list fields
* @throws DatabaseException
*/
private void listFieldsForView(Class<?> clazz) throws DatabaseException {
Field[] fields = clazz.getDeclaredFields();// pobierz wszystkie pola z klasy
for (Field field : fields) {
field.setAccessible(true); // możliwość dostępu nawet jeżeli pole jest prywatne
if (field.isAnnotationPresent(DbViewField.class)) {// view field
DbViewFieldInfo info = processDbViewField(field, clazz);
dbViewFields.add(info);
} else if (field.isAnnotationPresent(DbViewObject.class)) {// view object
dbViewObjects.add(processDbViewObject(field, clazz));
}
}
}
/**
* Load database types
*
* @param mapper native type to SQL type mapper
* @throws DatabaseException cannot determine type, or error when listing fields
*/
void loadDatabaseTypes(SqlTypeMapper mapper) throws DatabaseException {
if (lazyLoadedDatabaseTypes) {// if loaded types, do nothing
return;
}
if (!lazyLoadedFields) {// if fields not loaded - load it
this.listFields();
}
for (DbFieldInfo fieldInfo : dbFields) {
Class<?> nativeType = fieldInfo.getNativeType();// native java type
// sql type
SqlType sqlType = fieldInfo.fieldAnnotation.type();
if (sqlType == SqlType.DEFAULT) {// default type - determine
sqlType = mapper.getSqlType(nativeType);
}
if (sqlType == SqlType.UNKNOWN) {// cannot determine type
throw new DatabaseException("Cannot determine SQL type of " + nativeType.getName());
}
fieldInfo.sqlType = sqlType;// SQL type
// get sql string type for current database
String fieldSqlStr = db.getDb().getTypeString(fieldInfo);
if (fieldSqlStr == null) {
throw new DatabaseException("Cannot get type " + fieldInfo.sqlType + " for database!");
}
DbField dbField = fieldInfo.getFieldAnnotation();
// replace string len value
int strLen = dbField.stringLen();
if (strLen == -1) {
strLen = db.getConfig().defaultStringLen;
}
fieldSqlStr = fieldSqlStr.replace("{strlen}", Integer.toString(strLen));
// replace decimal precision
int precistion = dbField.decimalPrecision();
if (precistion == -1) {
precistion = db.getConfig().defaultDecimalPrecision;
}
fieldSqlStr = fieldSqlStr.replace("{precision}", Integer.toString(precistion));
// replace decimal scale
int scale = dbField.decimalScale();
if (scale == -1) {
scale = db.getConfig().defaultDecimalScale;
}
fieldSqlStr = fieldSqlStr.replace("{scale}", Integer.toString(scale));
fieldInfo.sqlTypeString = fieldSqlStr;// SQL type string
}
}
/**
* Process DbField annotation
*
* @param field field in class
* @param clazz current processing class
* @return database field info
*/
private DbFieldInfo processDbField(Field field, Class<?> clazz) {
DbField dbField = field.getAnnotation(DbField.class);// pobierz element adnotacji
DbFieldInfo info = new DbFieldInfo();
info.fieldAnnotation = dbField;
info.clazz = clazz;
info.fieldInClass = field;
// in table name
info.inTableName = dbField.name();// custom name
if (info.inTableName.isEmpty()) {// if custom name empty, use class name
info.inTableName = field.getName();
}
return info;
}
/**
* Process DbPrimaryKey annotation
*
* @param field field info
* @return primary key info
* @throws DatabaseException
*/
private DbPrimaryKeyInfo processDbPrimaryKey(Field field) throws DatabaseException {
if (!field.isAnnotationPresent(DbField.class)) {
throw new DatabaseException("No annotation DbField on DbPrimaryKey!");
}
DbPrimaryKey dbPrimaryKey = field.getAnnotation(DbPrimaryKey.class);
DbPrimaryKeyInfo info = new DbPrimaryKeyInfo();
info.pkAnnotation = dbPrimaryKey;
return info;
}
/**
* Process DbForeignKey annotation
*
* @param field field in class
* @param clazz current processing class
* @return foreign key info
* @throws DatabaseException
*/
private DbForeignKeyInfo processDbForeignKey(Field field, Class<?> clazz) throws DatabaseException {
if (!field.isAnnotationPresent(DbField.class)) {
throw new DatabaseException("No annotation DbField on DbForeignKey!");
}
DbForeignKey dbForeignKey = field.getAnnotation(DbForeignKey.class);
DbForeignKeyInfo info = new DbForeignKeyInfo();
info.fkAnnotation = dbForeignKey;
// load this field - field in current class for place foreing object
if (!dbForeignKey.thisField().trim().equals("")) {
try {
info.thisField = getDeclaredField(clazz, dbForeignKey.thisField());
} catch (NoSuchFieldException e) {
String fname = field.getName();// field name
String cname = clazz.getName();// class name
throw new DatabaseException("Cannot set foreign field " + fname + " for class: " + cname, e);
}
} else {
info.thisField = null;// if not field for save foreign object, set null
}
// reference class
Class<?> refObj = dbForeignKey.refObject();
// check annotation DbTable
if (!refObj.isAnnotationPresent(DbTable.class)) {
throw new DatabaseException("No 'DbTable' annotation in foreign class: " + refObj.getName());
}
// get table name
DbTable foreignDbTable = refObj.getAnnotation(DbTable.class);
info.refTableName = foreignDbTable.value();
String refFieldName = dbForeignKey.refField();// field name
String refClassName = dbForeignKey.refObject().getName();// class name
// load foreign field
Field foreignField;
try {
foreignField = getDeclaredField(dbForeignKey.refObject(), dbForeignKey.refField());
} catch (NoSuchFieldException e) {
throw new DatabaseException("Cannot found foreign field " + refFieldName + " in class: " + refClassName, e);
}
// check foreign field annotation
if (!foreignField.isAnnotationPresent(DbField.class)) {
throw new DatabaseException("No DbField annotation: " + refClassName + "::" + refFieldName);
}
DbField dbForeignField = foreignField.getAnnotation(DbField.class);
// check is unique or primary key
// TODO
// save table column name
info.refInTableName = dbForeignField.name();// custom column name
if (info.refInTableName.isEmpty()) {// default column name
info.refInTableName = foreignField.getName();
}
return info;
}
/**
* Process DbManyToOne annotation
*
* @param field field info
* @throws DatabaseException
*/
private DbManyToOneInfo processDbManyToOne(Field field) throws DatabaseException {
DbManyToOne dbMany = field.getAnnotation(DbManyToOne.class);
// sprawdź, czy pole ManyToOne jest kolekcją
if (!Collection.class.isAssignableFrom(field.getType())) {// jeżeli nie jest - rzuć wyjątek
throw new DatabaseException("Field '" + field.getName() + "' in class '"
+ field.getDeclaringClass().getName() + "' ManyToOne relation is not a collection!");
}
DbManyToOneInfo info = new DbManyToOneInfo();
info.mtoAnnotation = dbMany;
info.fieldInClass = field;
// pobierz pole w klasie obcej
try {
Field refField = getDeclaredField(dbMany.refObject(), dbMany.refField());
if (!refField.isAnnotationPresent(DbField.class) || !refField.isAnnotationPresent(DbForeignKey.class)) {
throw new DatabaseException("Relation field " + refField.getName() + " has not FK annotation!");
}
DbForeignKey dbForKey = refField.getAnnotation(DbForeignKey.class);
// ustaw pole, do którego odwołuje się ManyToOne
if (!dbForKey.thisField().isEmpty()) {// jeżeli takowe istnieje
Field refFieldOnClass = getDeclaredField(dbMany.refObject(), dbForKey.thisField());
info.refFieldObj = refFieldOnClass;
}
info.refFieldKey = refField;
} catch (NoSuchFieldException e) {
throw new DatabaseException("DbManyToOne field not found!", e);
}
return info;
}
/**
* Process DbOneToOne annotation
*
* @param field field info
* @throws DatabaseException
*/
private DbOneToOneInfo processDbOneToOne(Field field) throws DatabaseException {
DbOneToOne dbOne = field.getAnnotation(DbOneToOne.class);
DbOneToOneInfo info = new DbOneToOneInfo();
info.otoAnnotation = dbOne;
info.fieldInClass = field;
// pobierz pole w klasie obcej
try {
Field refField = getDeclaredField(dbOne.refObject(), dbOne.refField());
if (!refField.isAnnotationPresent(DbField.class) || !refField.isAnnotationPresent(DbForeignKey.class)) {
throw new DatabaseException("Relation field " + refField.getName() + " has not FK annotation!");
}
DbForeignKey dbForKey = refField.getAnnotation(DbForeignKey.class);
// ustaw pole, do którego odwołuje się ManyToOne
if (!dbForKey.thisField().isEmpty()) {// jeżeli takowe istnieje
Field refFieldOnClass = getDeclaredField(dbOne.refObject(), dbForKey.thisField());
info.refFieldObj = refFieldOnClass;
}
info.refFieldKey = refField;
} catch (NoSuchFieldException e) {
throw new DatabaseException("DbOneToOne field not found!", e);
}
return info;
}
/**
* Process DbViewFiled annotation
*
* @param field field in class
* @param clazz current processing class
* @return DbViewField info
*/
private DbViewFieldInfo processDbViewField(Field field, Class<?> clazz) {
DbViewField dbViewField = field.getAnnotation(DbViewField.class);// pobierz element adnotacji
DbViewFieldInfo info = new DbViewFieldInfo();
info.fieldAnnotation = dbViewField;
// info.clazz = clazz;
info.fieldInClass = field;
// in table name
info.inQueryName = dbViewField.value();// custom name
if (info.inQueryName.isEmpty()) {// if custom name empty, use class name
info.inQueryName = field.getName();
}
return info;
}
/**
* Process DbViewObject annotation
*
* @param field field in class
* @param clazz current processing class
* @return DbViewObject info
*/
private DbViewObjectInfo processDbViewObject(Field field, Class<?> clazz) {
DbViewObject dbViewObject = field.getAnnotation(DbViewObject.class);// pobierz element adnotacji
DbViewObjectInfo info = new DbViewObjectInfo();
info.fieldAnnotation = dbViewObject;
// info.clazz = clazz;
info.fieldInClass = field;
return info;
}
/**
* Get declared field from class or superclass
*
* @param clazz class to start search
* @param field field name
* @return field in class
* @throws NoSuchFieldException field not found
*/
private Field getDeclaredField(Class<?> clazz, String field) throws NoSuchFieldException {
do {
try {
Field f = clazz.getDeclaredField(field);
f.setAccessible(true);
return f;
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
}
} while (!clazz.equals(Object.class));
throw new NoSuchFieldException("Field not found: " + field);
}
/**
* @return table name
*/
String getTableName() {
return tableName;
}
/**
* @return table class
*/
Class<?> getTableClass() {
return tableClass;
}
/**
* @return database fields in class
*/
List<DbFieldInfo> getDbFields() {
return new ArrayList<>(dbFields);// copy
}
/**
* @return database fields or view fields in class
*/
List<DbFieldOrViewInfo> getDbFieldOrViewInfo() {
List<DbFieldOrViewInfo> ret = new ArrayList<>(dbFields);// copy
ret.addAll(dbViewFields);
return ret;
}
/**
* @return database fields which are primary keys
*/
List<DbFieldInfo> getPrimaryKeys() {
List<DbFieldInfo> pkList = new ArrayList<>(2);
for (DbFieldInfo dfi : dbFields) {
if (dfi.getPrimaryKeyInfo() != null) {
pkList.add(dfi);
}
}
return pkList;
}
/**
* @return database fields which are foreign keys
*/
List<DbFieldInfo> getForeignKeys() {
List<DbFieldInfo> fkList = new ArrayList<>(2);
for (DbFieldInfo dfi : dbFields) {
if (dfi.getForeignKeyInfo() != null) {
fkList.add(dfi);
}
}
return fkList;
}
/**
* @return database fields which are indexes
*/
List<DbFieldInfo> getIndexes() {
List<DbFieldInfo> indexes = new ArrayList<>(2);
for (DbFieldInfo dfi : dbFields) {
if (dfi.fieldAnnotation.isIndex()) {
indexes.add(dfi);
}
}
return indexes;
}
/**
* Get field by name in class
*
* @param string field name in class
* @return field, or null if not found
*/
DbFieldOrViewInfo getFieldByInClassName(String name) {
for (DbFieldInfo df : dbFields) {
if (df.getFieldInClass().getName().equals(name)) {
return df;
}
}
for (DbViewFieldInfo df : dbViewFields) {
if (df.getFieldInClass().getName().equals(name)) {
return df;
}
}
return null;
}
/**
* @return fields for ManyToOne relations
*/
List<DbManyToOneInfo> getDbManyToOne() {
return dbManyToOne;
}
/**
* @return fields for OneToOne relations
*/
List<DbOneToOneInfo> getDbOneToOne() {
return dbOneToOne;
}
/**
* @return this is view?
*/
boolean isView() {
return dbView != null;
}
/**
* @return DbView annotation
*/
DbView getDbView() {
return dbView;
}
/**
* @return DbViewObject list info for view
*/
List<DbViewObjectInfo> getDbViewObjects() {
return dbViewObjects;
}
/**
* Database field info
*
* @author lukas
*/
public class DbFieldInfo implements DbFieldOrViewInfo {
DbFieldInfo() {// not public constructor
}
/**
* DbField annotation
*/
DbField fieldAnnotation;
/**
* Class in which the field is located (for superclasses support)
*/
Class<?> clazz;
/**
* Field in class
*/
Field fieldInClass;
/**
* Column name in table
*/
String inTableName;
/**
* SQL type
*/
SqlType sqlType;
/**
* SQL type string for current database type
*/
String sqlTypeString;
/**
* Primary key info
*/
DbPrimaryKeyInfo primaryKeyInfo;
/**
* Foreign key info
*/
DbForeignKeyInfo foreignKeyInfo;
/**
* @return DbField annotation
*/
public DbField getFieldAnnotation() {
return fieldAnnotation;
}
@Override
public Field getFieldInClass() {
return fieldInClass;
}
/**
* @return SQL type
*/
public SqlType getSqlType() {
return sqlType;
}
/**
* @return primary key info (or null)
*/
public DbPrimaryKeyInfo getPrimaryKeyInfo() {
return primaryKeyInfo;
}
/**
* @return foreign key info (or null)
*/
public DbForeignKeyInfo getForeignKeyInfo() {
return foreignKeyInfo;
}
@Override
public String getInQueryName() {
return tableName + '_' + inTableName;
}
@Override
public String getInTableName() {
return inTableName;
}
}
/**
* Primary key info
*
* @author lukas
*/
public class DbPrimaryKeyInfo {
DbPrimaryKeyInfo() {// not public constructor
}
/**
* DbPrimaryKey annotation
*/
DbPrimaryKey pkAnnotation;
/**
* @return DbPrimaryKey annotation
*/
public DbPrimaryKey getPkAnnotation() {
return pkAnnotation;
}
}
/**
* Foreign key info
*
* @author lukas
*/
public class DbForeignKeyInfo {
DbForeignKeyInfo() {// not public constructor
}
/**
* DbForeignKey annotation
*/
DbForeignKey fkAnnotation;
/**
* Field in class for store foreign object
*/
Field thisField;
/**
* Foreign table name
*/
String refTableName;
/**
* Foreign column name
*/
String refInTableName;
/**
* @return DbForeignKey annotation
*/
public DbForeignKey getFkAnnotation() {
return fkAnnotation;
}
}
/**
* Many to one info
*
* @author lukas
*/
public class DbManyToOneInfo {
DbManyToOneInfo() {// not public constructor
}
/**
* DbManyToOne annotation
*/
DbManyToOne mtoAnnotation;
/**
* Field in class
*/
Field fieldInClass;
/**
* Field in ref class - foreign key field
*/
Field refFieldKey;
/**
* Field in ref class - object field
*/
Field refFieldObj;
/**
* @return DbManyToOne annotation
*/
public DbManyToOne getMtoAnnotation() {
return mtoAnnotation;
}
}
/**
* One to one info
*
* @author lukas
*/
public class DbOneToOneInfo {
DbOneToOneInfo() {// not public constructor
}
/**
* DbOneToOne annotation
*/
DbOneToOne otoAnnotation;
/**
* Field in class
*/
Field fieldInClass;
/**
* Field in ref class - foreign key field
*/
Field refFieldKey;
/**
* Field in ref class - object field
*/
Field refFieldObj;
/**
* @return DbManyToOne annotation
*/
public DbOneToOne getOtoAnnotation() {
return otoAnnotation;
}
}
/**
* VIEW field info
*
* @author lukas
*/
public class DbViewFieldInfo implements DbFieldOrViewInfo {
DbViewFieldInfo() {
}
/**
* DbViewField annotation
*/
DbViewField fieldAnnotation;
/**
* Class in which the field is located (for superclasses support)
*/
// Class<?> clazz;
/**
* Field in class
*/
Field fieldInClass;
/**
* Column name in query
*/
String inQueryName;
@Override
public String getInQueryName() {
return inQueryName;
}
@Override
public String getInTableName() {
return inQueryName;
}
@Override
public Field getFieldInClass() {
return fieldInClass;
}
}
/**
* VIEW object info
*
* @author lukas
*/
public class DbViewObjectInfo {
DbViewObjectInfo() {
}
/**
* DbViewObject annotation
*/
DbViewObject fieldAnnotation;
/**
* Class in which the field is located (for superclasses support)
*/
// Class<?> clazz;
/**
* Field in class
*/
Field fieldInClass;
}
public interface DbFieldOrViewInfo {
/**
* @return name in query
*/
public String getInQueryName();
/**
* @return name in table
*/
public String getInTableName();
/**
* @return field in class
*/
public Field getFieldInClass();
/**
* @return native java type
*/
default public Class<?> getNativeType() {
return getFieldInClass().getType();
}
/**
* @param clazz native type to check
* @return is native type?
*/
default public boolean nativeTypeIs(Class<?> clazz) {
return getNativeType().isAssignableFrom(clazz);
}
}
}
| null |
10059_0 | Jvsin/Monopoly | 4,145 | src/Game.java | import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
public class Game extends JFrame {
private final Player[] players;
private Player currentPlayer;
private final Board board;
private final JPanel gameInfoPanel = new JPanel();
private final JLabel textInfoGame = new JLabel();
private final JLabel titlePlayerPanel = new JLabel();
private final JPanel[] playersPanels;
private final JPanel playerInfoPanel = new JPanel();
private Field cardView;
private final JLabel dicePlaceholder = new JLabel();
private final JLabel dicePlaceholderSecond = new JLabel();
private Dice firstDice = new Dice();
private Dice secondDice = new Dice();
private int diceResult;
private static int PLAYER_NUMBER;
public int WINDOW_WIDTH = 1500;
public int WINDOW_HEIGHT = 1000;
private final int HOUSE_PRICE = 500; // TODO: Ekonomia -> koszt dobudowania domu
public Game() {
board = new Board();
players = new Player[PLAYER_NUMBER];
playersPanels = new JPanel[PLAYER_NUMBER];
if (PLAYER_NUMBER >= 1) {
players[0] = new Player(PlayersColors.BLUE);
playersPanels[0] = new JPanel();
board.setPawn(players[0], 0);
}
if (PLAYER_NUMBER >= 2) {
players[1] = new Player(PlayersColors.RED);
playersPanels[1] = new JPanel();
board.setPawn(players[1], 0);
}
if (PLAYER_NUMBER >= 3) {
players[2] = new Player(PlayersColors.GREEN);
playersPanels[2] = new JPanel();
board.setPawn(players[2], 0);
}
if (PLAYER_NUMBER == 4) {
players[3] = new Player(PlayersColors.YELLOW);
playersPanels[3] = new JPanel();
board.setPawn(players[3], 0);
}
currentPlayer = players[0];
setDefaultCard();
setWindowParameters();
}
public static void startMenu() {
Object[] options = {"2 graczy", "3 graczy", "4 graczy"};
int check = JOptionPane.showOptionDialog(null, "Wybierz ilość graczy: ", "Monopoly",
JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
if (check == 0)
PLAYER_NUMBER = 2;
else if (check == 1)
PLAYER_NUMBER = 3;
else
PLAYER_NUMBER = 4;
}
public void round() {
for (Player player : players) {
if (player.getPlayerStatus() != PlayerStatus.LOST) {
currentPlayer = player;
setInformation();
setDiceListeners();
System.out.println("wynik kostki:" + diceResult);
if (currentPlayer.getPlayerStatus() == PlayerStatus.IN_GAME) {
currentPlayer.playerMove(diceResult);
board.setPawn(currentPlayer, currentPlayer.getPosition());
}
setCardView();
triggerFieldRound(board.getField(currentPlayer.getPosition()));
System.out.println("pozycja gracza: " + currentPlayer.getPlayerColor() + " " + currentPlayer.getPosition());
diceResult = 0;
repaintBoard();
}
}
}
private void triggerFieldRound(Field field) {
switch (field.getFieldType()) {
case TAX -> triggerTax();
case JAIL -> triggerJail();
case NORMAL, BALL -> triggerNormal(field);
case CHANCE -> triggerChance();
case GO_TO_JAIL -> triggerGoToJail();
case START, PARKING -> {
}
}
}
private void infoPanel(String s) {
JFrame f = new JFrame();
JOptionPane.showMessageDialog(f, s);
}
private void triggerGoToJail() {
currentPlayer.blockPlayer();
infoPanel("Idziesz do więzienia.");
board.setPawn(currentPlayer, currentPlayer.getPosition());
}
private void triggerChance() {
Chance chance = board.getRandomChance();
infoPanel(chance.getContents());
currentPlayer.increaseMoney(chance.getMoney(currentPlayer.getMoneyInWallet()));
if (currentPlayer.getMoneyInWallet() < 0) {
// TODO: Opcja windykacji działek
}
}
private void triggerNormal(Field field) {
if (field.getOwner() == null) {
if (field.getBuyPrice() > currentPlayer.getMoneyInWallet()) {
infoPanel("Nie masz wystarczająco pieniędzy na zakup piłki.");
} else {
buyField(currentPlayer, field);
}
} else if (field.getOwner() != currentPlayer) {
int sleepPrice = (int) field.getSleepPrice();
infoPanel("Musisz zapłacić za postój " + sleepPrice);
currentPlayer.decreaseMoney(sleepPrice);
field.getOwner().increaseMoney(sleepPrice);
if (currentPlayer.getMoneyInWallet() < 0) {
// TODO: Opcja windykacji działek
}
} else if (field.getOwner() == currentPlayer
&& field.getFieldType() == FieldType.NORMAL
&& currentPlayer.isHavingAllCountry(field.getCountry())
&& currentPlayer.getMoneyInWallet() >= HOUSE_PRICE
&& field.getAccommodationLevel() < field.MAX_ACCOMMODATION_LEVEL) {
buildHouses(field);
}
}
private void triggerJail() {
if (diceResult == 12) {
infoPanel("Wychodzisz z więzienia.");
currentPlayer.unlockPlayer();
} else if (currentPlayer.getPlayerStatus() == PlayerStatus.IN_JAIL) {
infoPanel("Zostajesz w więzieniu");
}
}
private void triggerTax() {
int tax = (int) (board.getRandomChance().getRandomTax() * currentPlayer.getMoneyInWallet());
infoPanel("Musisz zapłacić podatek od swoich oszczędności w wysokości " + tax);
currentPlayer.decreaseMoney(tax);
if (currentPlayer.getMoneyInWallet() < 0) {
// TODO: Opcja windykacji działek
}
}
public void repaintBoard() {
setCardView();
board.repaint();
gameInfoPanel.repaint();
playerInfoPanel.repaint();
setPlayerMiniCards();
}
private void setDiceListeners() {
final CountDownLatch latch = new CountDownLatch(1);
firstDice.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
firstDice = (Dice) e.getSource();
diceResult = firstDice.diceThrow() + secondDice.diceThrow();
latch.countDown(); // Zwalnianie CountDownLatch po kliknięciu
}
});
secondDice.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
secondDice = (Dice) e.getSource();
diceResult = firstDice.diceThrow() + secondDice.diceThrow();
latch.countDown(); // Zwalnianie CountDownLatch po kliknięciu
}
});
try {
latch.await(); // Oczekiwanie na kliknięcie
} catch (InterruptedException e) {
e.printStackTrace();
}
firstDice.removeMouseListener(firstDice.getMouseListeners()[0]);
secondDice.removeMouseListener(secondDice.getMouseListeners()[0]);
}
private void setInformation() {
textInfoGame.setText("Ruch: " + currentPlayer.getPlayerColor());
}
private void setCardView() {
Field temp = board.getField(currentPlayer.getPosition());
Image image = temp.getFieldCard();
cardView.setFieldCard(image);
cardView.repaint();
}
private void setDefaultCard() {
Image image = new ImageIcon("./assets/Cards/defaultCard.png").getImage();
cardView = board.getField(0);
cardView.setFieldCard(image);
cardView.repaint();
}
private void setPlayerMiniCards() {
for (int i = 0; i < PLAYER_NUMBER; i++) {
ArrayList<Field> fieldsToDisplay = new ArrayList<>();
for (Field owns : players[i].getOwnedFields()) {
owns.setFieldCard(owns.getMiniFieldCard());
owns.setPreferredSize(new Dimension(100, 30));
owns.setBounds(0, 0, 100, 30);
fieldsToDisplay.add(owns);
}
for (Field field : fieldsToDisplay) {
playersPanels[i].add(field, BorderLayout.SOUTH);
}
fieldsToDisplay.clear();
}
}
public void setDiceView(int diceResult, Dice dicePlaceholder) {
dicePlaceholder.setIcon(Dice.diceViews[diceResult - 1]);
}
private void buyField(Player player, Field field) {
Object[] options = {"Tak", "Nie"};
int check = JOptionPane.showOptionDialog(null, "Czy chcesz kupić pole " + field.getFieldName() + "?", "Monopoly",
JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
if (check == 0) {
field.setOwner(player);
player.buyField(field);
infoPanel("Gratulacje zakupu " + field.getFieldName());
}
}
private void buildHouses(Field field) {
Object[] options = {"Tak", "Nie"};
int check = JOptionPane.showOptionDialog(null, "Czy podnieść poziom na polu " + field.getFieldName() + " za " + HOUSE_PRICE + "?",
"Monopoly", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
if (check == 0) {
field.increaseAccommodationLevel();
currentPlayer.decreaseMoney(HOUSE_PRICE);
infoPanel("Właśnie podwyższyłeś poziom pola " + field.getFieldType() + " na " + field.getAccommodationLevel());
}
}
private void setPlayersPanelView() {
playerInfoPanel.setPreferredSize(new Dimension(300, 900));
playerInfoPanel.setBounds(1200, 0, 300, 900);
playerInfoPanel.setBackground(new Color(227, 139, 27));
titlePlayerPanel.setPreferredSize(new Dimension(200, 20));
titlePlayerPanel.setBackground(new Color(255, 255, 255));
titlePlayerPanel.setForeground(new Color(236, 245, 133));
titlePlayerPanel.setHorizontalAlignment(JLabel.CENTER);
titlePlayerPanel.setFont(new Font("Arial", Font.BOLD, 20));
titlePlayerPanel.setText("PLAYERS PANELS:");
playerInfoPanel.add(titlePlayerPanel, BorderLayout.CENTER);
int counter = 0;
for (JPanel panel : playersPanels) {
panel.setPreferredSize(new Dimension(300, 200));
panel.setBackground(new Color(236, 245, 133));
JLabel text = new JLabel();
text.setPreferredSize(new Dimension(300, 15));
text.setForeground(new Color(227, 139, 27));
text.setFont(new Font("Arial", Font.BOLD, 15));
text.setText("Player " + players[counter].getPlayerColor());
text.setHorizontalAlignment(JLabel.CENTER);
panel.add(text);
playerInfoPanel.add(panel, BorderLayout.SOUTH);
counter++;
}
}
private void setWindowParameters() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
this.setLayout(null);
this.setVisible(true);
this.setTitle("MONOPOLY - WORLD CUP EDITION");
cardView.setPreferredSize(new Dimension(317, 457));
cardView.setHorizontalAlignment(JLabel.CENTER);
firstDice.setForeground(Color.white);
firstDice.setPreferredSize(new Dimension(90, 90));
firstDice.setBounds(50, 0, 90, 90);
secondDice.setForeground(Color.white);
secondDice.setPreferredSize(new Dimension(90, 90));
secondDice.setBounds(50, 0, 90, 90);
dicePlaceholder.setPreferredSize(new Dimension(200, 100));
dicePlaceholder.setHorizontalAlignment(JLabel.LEFT);
dicePlaceholder.add(firstDice);
setDiceView(1, firstDice);
dicePlaceholderSecond.setPreferredSize(new Dimension(200, 100));
dicePlaceholderSecond.setHorizontalAlignment(JLabel.RIGHT);
dicePlaceholderSecond.add(secondDice);
setDiceView(4, secondDice);
textInfoGame.setPreferredSize(new Dimension(200, 50));
textInfoGame.setBackground(new Color(255, 255, 255));
textInfoGame.setForeground(new Color(241, 3, 3));
textInfoGame.setHorizontalAlignment(JLabel.CENTER);
textInfoGame.setFont(new Font("Arial", Font.BOLD, 10));
textInfoGame.setText("Ruch gracza: " + currentPlayer.getPlayerColor());
gameInfoPanel.setPreferredSize(new Dimension(300, 900));
gameInfoPanel.setBackground(Color.YELLOW);
gameInfoPanel.setBounds(0, 0, 300, 900);
gameInfoPanel.add(textInfoGame, BorderLayout.CENTER);
gameInfoPanel.add(cardView);
gameInfoPanel.add(dicePlaceholder);
gameInfoPanel.add(dicePlaceholderSecond);
setPlayersPanelView();
this.add(gameInfoPanel, BorderLayout.WEST);
this.add(board, BorderLayout.CENTER);
this.add(playerInfoPanel, BorderLayout.EAST);
this.repaint();
}
}
| // TODO: Ekonomia -> koszt dobudowania domu | import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
public class Game extends JFrame {
private final Player[] players;
private Player currentPlayer;
private final Board board;
private final JPanel gameInfoPanel = new JPanel();
private final JLabel textInfoGame = new JLabel();
private final JLabel titlePlayerPanel = new JLabel();
private final JPanel[] playersPanels;
private final JPanel playerInfoPanel = new JPanel();
private Field cardView;
private final JLabel dicePlaceholder = new JLabel();
private final JLabel dicePlaceholderSecond = new JLabel();
private Dice firstDice = new Dice();
private Dice secondDice = new Dice();
private int diceResult;
private static int PLAYER_NUMBER;
public int WINDOW_WIDTH = 1500;
public int WINDOW_HEIGHT = 1000;
private final int HOUSE_PRICE = 500; // TODO: Ekonomia <SUF>
public Game() {
board = new Board();
players = new Player[PLAYER_NUMBER];
playersPanels = new JPanel[PLAYER_NUMBER];
if (PLAYER_NUMBER >= 1) {
players[0] = new Player(PlayersColors.BLUE);
playersPanels[0] = new JPanel();
board.setPawn(players[0], 0);
}
if (PLAYER_NUMBER >= 2) {
players[1] = new Player(PlayersColors.RED);
playersPanels[1] = new JPanel();
board.setPawn(players[1], 0);
}
if (PLAYER_NUMBER >= 3) {
players[2] = new Player(PlayersColors.GREEN);
playersPanels[2] = new JPanel();
board.setPawn(players[2], 0);
}
if (PLAYER_NUMBER == 4) {
players[3] = new Player(PlayersColors.YELLOW);
playersPanels[3] = new JPanel();
board.setPawn(players[3], 0);
}
currentPlayer = players[0];
setDefaultCard();
setWindowParameters();
}
public static void startMenu() {
Object[] options = {"2 graczy", "3 graczy", "4 graczy"};
int check = JOptionPane.showOptionDialog(null, "Wybierz ilość graczy: ", "Monopoly",
JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
if (check == 0)
PLAYER_NUMBER = 2;
else if (check == 1)
PLAYER_NUMBER = 3;
else
PLAYER_NUMBER = 4;
}
public void round() {
for (Player player : players) {
if (player.getPlayerStatus() != PlayerStatus.LOST) {
currentPlayer = player;
setInformation();
setDiceListeners();
System.out.println("wynik kostki:" + diceResult);
if (currentPlayer.getPlayerStatus() == PlayerStatus.IN_GAME) {
currentPlayer.playerMove(diceResult);
board.setPawn(currentPlayer, currentPlayer.getPosition());
}
setCardView();
triggerFieldRound(board.getField(currentPlayer.getPosition()));
System.out.println("pozycja gracza: " + currentPlayer.getPlayerColor() + " " + currentPlayer.getPosition());
diceResult = 0;
repaintBoard();
}
}
}
private void triggerFieldRound(Field field) {
switch (field.getFieldType()) {
case TAX -> triggerTax();
case JAIL -> triggerJail();
case NORMAL, BALL -> triggerNormal(field);
case CHANCE -> triggerChance();
case GO_TO_JAIL -> triggerGoToJail();
case START, PARKING -> {
}
}
}
private void infoPanel(String s) {
JFrame f = new JFrame();
JOptionPane.showMessageDialog(f, s);
}
private void triggerGoToJail() {
currentPlayer.blockPlayer();
infoPanel("Idziesz do więzienia.");
board.setPawn(currentPlayer, currentPlayer.getPosition());
}
private void triggerChance() {
Chance chance = board.getRandomChance();
infoPanel(chance.getContents());
currentPlayer.increaseMoney(chance.getMoney(currentPlayer.getMoneyInWallet()));
if (currentPlayer.getMoneyInWallet() < 0) {
// TODO: Opcja windykacji działek
}
}
private void triggerNormal(Field field) {
if (field.getOwner() == null) {
if (field.getBuyPrice() > currentPlayer.getMoneyInWallet()) {
infoPanel("Nie masz wystarczająco pieniędzy na zakup piłki.");
} else {
buyField(currentPlayer, field);
}
} else if (field.getOwner() != currentPlayer) {
int sleepPrice = (int) field.getSleepPrice();
infoPanel("Musisz zapłacić za postój " + sleepPrice);
currentPlayer.decreaseMoney(sleepPrice);
field.getOwner().increaseMoney(sleepPrice);
if (currentPlayer.getMoneyInWallet() < 0) {
// TODO: Opcja windykacji działek
}
} else if (field.getOwner() == currentPlayer
&& field.getFieldType() == FieldType.NORMAL
&& currentPlayer.isHavingAllCountry(field.getCountry())
&& currentPlayer.getMoneyInWallet() >= HOUSE_PRICE
&& field.getAccommodationLevel() < field.MAX_ACCOMMODATION_LEVEL) {
buildHouses(field);
}
}
private void triggerJail() {
if (diceResult == 12) {
infoPanel("Wychodzisz z więzienia.");
currentPlayer.unlockPlayer();
} else if (currentPlayer.getPlayerStatus() == PlayerStatus.IN_JAIL) {
infoPanel("Zostajesz w więzieniu");
}
}
private void triggerTax() {
int tax = (int) (board.getRandomChance().getRandomTax() * currentPlayer.getMoneyInWallet());
infoPanel("Musisz zapłacić podatek od swoich oszczędności w wysokości " + tax);
currentPlayer.decreaseMoney(tax);
if (currentPlayer.getMoneyInWallet() < 0) {
// TODO: Opcja windykacji działek
}
}
public void repaintBoard() {
setCardView();
board.repaint();
gameInfoPanel.repaint();
playerInfoPanel.repaint();
setPlayerMiniCards();
}
private void setDiceListeners() {
final CountDownLatch latch = new CountDownLatch(1);
firstDice.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
firstDice = (Dice) e.getSource();
diceResult = firstDice.diceThrow() + secondDice.diceThrow();
latch.countDown(); // Zwalnianie CountDownLatch po kliknięciu
}
});
secondDice.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
secondDice = (Dice) e.getSource();
diceResult = firstDice.diceThrow() + secondDice.diceThrow();
latch.countDown(); // Zwalnianie CountDownLatch po kliknięciu
}
});
try {
latch.await(); // Oczekiwanie na kliknięcie
} catch (InterruptedException e) {
e.printStackTrace();
}
firstDice.removeMouseListener(firstDice.getMouseListeners()[0]);
secondDice.removeMouseListener(secondDice.getMouseListeners()[0]);
}
private void setInformation() {
textInfoGame.setText("Ruch: " + currentPlayer.getPlayerColor());
}
private void setCardView() {
Field temp = board.getField(currentPlayer.getPosition());
Image image = temp.getFieldCard();
cardView.setFieldCard(image);
cardView.repaint();
}
private void setDefaultCard() {
Image image = new ImageIcon("./assets/Cards/defaultCard.png").getImage();
cardView = board.getField(0);
cardView.setFieldCard(image);
cardView.repaint();
}
private void setPlayerMiniCards() {
for (int i = 0; i < PLAYER_NUMBER; i++) {
ArrayList<Field> fieldsToDisplay = new ArrayList<>();
for (Field owns : players[i].getOwnedFields()) {
owns.setFieldCard(owns.getMiniFieldCard());
owns.setPreferredSize(new Dimension(100, 30));
owns.setBounds(0, 0, 100, 30);
fieldsToDisplay.add(owns);
}
for (Field field : fieldsToDisplay) {
playersPanels[i].add(field, BorderLayout.SOUTH);
}
fieldsToDisplay.clear();
}
}
public void setDiceView(int diceResult, Dice dicePlaceholder) {
dicePlaceholder.setIcon(Dice.diceViews[diceResult - 1]);
}
private void buyField(Player player, Field field) {
Object[] options = {"Tak", "Nie"};
int check = JOptionPane.showOptionDialog(null, "Czy chcesz kupić pole " + field.getFieldName() + "?", "Monopoly",
JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
if (check == 0) {
field.setOwner(player);
player.buyField(field);
infoPanel("Gratulacje zakupu " + field.getFieldName());
}
}
private void buildHouses(Field field) {
Object[] options = {"Tak", "Nie"};
int check = JOptionPane.showOptionDialog(null, "Czy podnieść poziom na polu " + field.getFieldName() + " za " + HOUSE_PRICE + "?",
"Monopoly", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
if (check == 0) {
field.increaseAccommodationLevel();
currentPlayer.decreaseMoney(HOUSE_PRICE);
infoPanel("Właśnie podwyższyłeś poziom pola " + field.getFieldType() + " na " + field.getAccommodationLevel());
}
}
private void setPlayersPanelView() {
playerInfoPanel.setPreferredSize(new Dimension(300, 900));
playerInfoPanel.setBounds(1200, 0, 300, 900);
playerInfoPanel.setBackground(new Color(227, 139, 27));
titlePlayerPanel.setPreferredSize(new Dimension(200, 20));
titlePlayerPanel.setBackground(new Color(255, 255, 255));
titlePlayerPanel.setForeground(new Color(236, 245, 133));
titlePlayerPanel.setHorizontalAlignment(JLabel.CENTER);
titlePlayerPanel.setFont(new Font("Arial", Font.BOLD, 20));
titlePlayerPanel.setText("PLAYERS PANELS:");
playerInfoPanel.add(titlePlayerPanel, BorderLayout.CENTER);
int counter = 0;
for (JPanel panel : playersPanels) {
panel.setPreferredSize(new Dimension(300, 200));
panel.setBackground(new Color(236, 245, 133));
JLabel text = new JLabel();
text.setPreferredSize(new Dimension(300, 15));
text.setForeground(new Color(227, 139, 27));
text.setFont(new Font("Arial", Font.BOLD, 15));
text.setText("Player " + players[counter].getPlayerColor());
text.setHorizontalAlignment(JLabel.CENTER);
panel.add(text);
playerInfoPanel.add(panel, BorderLayout.SOUTH);
counter++;
}
}
private void setWindowParameters() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
this.setLayout(null);
this.setVisible(true);
this.setTitle("MONOPOLY - WORLD CUP EDITION");
cardView.setPreferredSize(new Dimension(317, 457));
cardView.setHorizontalAlignment(JLabel.CENTER);
firstDice.setForeground(Color.white);
firstDice.setPreferredSize(new Dimension(90, 90));
firstDice.setBounds(50, 0, 90, 90);
secondDice.setForeground(Color.white);
secondDice.setPreferredSize(new Dimension(90, 90));
secondDice.setBounds(50, 0, 90, 90);
dicePlaceholder.setPreferredSize(new Dimension(200, 100));
dicePlaceholder.setHorizontalAlignment(JLabel.LEFT);
dicePlaceholder.add(firstDice);
setDiceView(1, firstDice);
dicePlaceholderSecond.setPreferredSize(new Dimension(200, 100));
dicePlaceholderSecond.setHorizontalAlignment(JLabel.RIGHT);
dicePlaceholderSecond.add(secondDice);
setDiceView(4, secondDice);
textInfoGame.setPreferredSize(new Dimension(200, 50));
textInfoGame.setBackground(new Color(255, 255, 255));
textInfoGame.setForeground(new Color(241, 3, 3));
textInfoGame.setHorizontalAlignment(JLabel.CENTER);
textInfoGame.setFont(new Font("Arial", Font.BOLD, 10));
textInfoGame.setText("Ruch gracza: " + currentPlayer.getPlayerColor());
gameInfoPanel.setPreferredSize(new Dimension(300, 900));
gameInfoPanel.setBackground(Color.YELLOW);
gameInfoPanel.setBounds(0, 0, 300, 900);
gameInfoPanel.add(textInfoGame, BorderLayout.CENTER);
gameInfoPanel.add(cardView);
gameInfoPanel.add(dicePlaceholder);
gameInfoPanel.add(dicePlaceholderSecond);
setPlayersPanelView();
this.add(gameInfoPanel, BorderLayout.WEST);
this.add(board, BorderLayout.CENTER);
this.add(playerInfoPanel, BorderLayout.EAST);
this.repaint();
}
}
| null |
6682_3 | KKozlowski/Komponentowe2015 | 605 | src/Klasa.java | import java.io.File;
import java.io.IOException;
public class Klasa {
public static void main(String[] args) {
try {
Window frame = new Window();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// TODO Auto-generated method stub
// System.out.println("Hello world !!!");
// dodawanie liczb
/*
* double a=4; // deklaracja zmiennej double b=5; int c=0;
* System.out.println(a+b);
*
* // dzielenie z instrukcja warunkowa if (b!=0)
* System.out.println(a/b); else
* System.out.println("Nie dzielimy przez zero!");
*
* System.out.println(a*b); System.out.println(c+b);
*/
// Wprowadzanie liczb przez okna dialogowe
/*
* String txt1; //deklaracja zmiennej tekstowej txt1 =
* JOptionPane.showInputDialog("Wprowadz pierwsza liczbe");
*
* String txt2; //deklaracja zmiennej tekstowej txt2 =
* JOptionPane.showInputDialog("Wprowadz druga liczbe");
*
* System.out.println(txt1 + txt2); // ???
*
*
*
* // Konwersja tekstu na liczbe double liczba1 =
* Double.parseDouble(txt1); int liczba2 = Integer.parseInt(txt2);
*
* System.out.println(liczba1 + liczba2); System.out.println(silnia(3));
*/
//Inputter inp = new Inputter();
//int liczbaWierszy = inp.GetInt("Ile wierszy trojkata?");
//TrojkatNewtona trojkat = new TrojkatNewtona(liczbaWierszy);
//TrojkatPascala trojkat = new TrojkatPascala();
//trojkat.print();
//Arg2 argumenty = new Arg2(args);
/*Tablica tab = new Tablica();
tab.Randomizuj(Integer.parseInt(args[0]), Integer.parseInt(args[1]));*/ | // Wprowadzanie liczb przez okna dialogowe
| import java.io.File;
import java.io.IOException;
public class Klasa {
public static void main(String[] args) {
try {
Window frame = new Window();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// TODO Auto-generated method stub
// System.out.println("Hello world !!!");
// dodawanie liczb
/*
* double a=4; // deklaracja zmiennej double b=5; int c=0;
* System.out.println(a+b);
*
* // dzielenie z instrukcja warunkowa if (b!=0)
* System.out.println(a/b); else
* System.out.println("Nie dzielimy przez zero!");
*
* System.out.println(a*b); System.out.println(c+b);
*/
// Wprowadzanie liczb <SUF>
/*
* String txt1; //deklaracja zmiennej tekstowej txt1 =
* JOptionPane.showInputDialog("Wprowadz pierwsza liczbe");
*
* String txt2; //deklaracja zmiennej tekstowej txt2 =
* JOptionPane.showInputDialog("Wprowadz druga liczbe");
*
* System.out.println(txt1 + txt2); // ???
*
*
*
* // Konwersja tekstu na liczbe double liczba1 =
* Double.parseDouble(txt1); int liczba2 = Integer.parseInt(txt2);
*
* System.out.println(liczba1 + liczba2); System.out.println(silnia(3));
*/
//Inputter inp = new Inputter();
//int liczbaWierszy = inp.GetInt("Ile wierszy trojkata?");
//TrojkatNewtona trojkat = new TrojkatNewtona(liczbaWierszy);
//TrojkatPascala trojkat = new TrojkatPascala();
//trojkat.print();
//Arg2 argumenty = new Arg2(args);
/*Tablica tab = new Tablica();
tab.Randomizuj(Integer.parseInt(args[0]), Integer.parseInt(args[1]));*/ | null |
7258_18 | KNJPJATK/GrupaPodstawowsza | 578 | spotkanie_05/src/Spotkanie05.java | /**
* Created by Kamil on 2015-11-19.
*/
public class Spotkanie05 {
public static void main(String[] args){
// Rozmowa o pracy domowej Zadania4
// https://gist.github.com/
//
// Zmienne instancyjne przechowują stan obiektu.
// Metody umożliwiają zmienianie stanu.
// Enkapsulacja danych, hermetyzacja:
// * zmienne instancyjne powinny być oznaczone jako private
// * jeśli potrzebny jest dostęp do tych zmiennych, możemy udostępnić gettery/settery.
// przykład gettera:
// public double getSaldo(){
// return saldo;
// };
// setter:
// public double setSaldo(double saldo){
// this.saldo = saldo;
// }
// W klasie konto nie mamy settera, ponieważ:
// zgodnie z zasadą enkapsulacji, wszelkie operacje na zmiennej 'saldo' powinna wykonywać klasa Konto
// (to jest jej odpowiedzialność)
// Aby zaimplementować wpłaty/wypłaty
// nie powinnno się tego robić w jakimś zewnętrznym kodzie, który: pobiera saldo z settera, dodaje/zmniejsza saldo, a następnie ustawia nowe saldo.
// Powwinno się tę funkcjonalność umieścić w klasie Konto, np. w dwóch metodach: wplac(double kwota) oraz wyplac(double kwota)
// Obiekt niemutowalny - nie zmienia stanu:
// - Wartość ustalamy w konstruktorze, i tylko tam.
// - żadnej z metod obiektu nie wolno zmieniać jego stanu. W szczególności: obiekt nie może mieć setterów.
// Override
// Pisząc własną implementację metody equals() musimy przeimplementować także hashCode
}
}
| // - żadnej z metod obiektu nie wolno zmieniać jego stanu. W szczególności: obiekt nie może mieć setterów. | /**
* Created by Kamil on 2015-11-19.
*/
public class Spotkanie05 {
public static void main(String[] args){
// Rozmowa o pracy domowej Zadania4
// https://gist.github.com/
//
// Zmienne instancyjne przechowują stan obiektu.
// Metody umożliwiają zmienianie stanu.
// Enkapsulacja danych, hermetyzacja:
// * zmienne instancyjne powinny być oznaczone jako private
// * jeśli potrzebny jest dostęp do tych zmiennych, możemy udostępnić gettery/settery.
// przykład gettera:
// public double getSaldo(){
// return saldo;
// };
// setter:
// public double setSaldo(double saldo){
// this.saldo = saldo;
// }
// W klasie konto nie mamy settera, ponieważ:
// zgodnie z zasadą enkapsulacji, wszelkie operacje na zmiennej 'saldo' powinna wykonywać klasa Konto
// (to jest jej odpowiedzialność)
// Aby zaimplementować wpłaty/wypłaty
// nie powinnno się tego robić w jakimś zewnętrznym kodzie, który: pobiera saldo z settera, dodaje/zmniejsza saldo, a następnie ustawia nowe saldo.
// Powwinno się tę funkcjonalność umieścić w klasie Konto, np. w dwóch metodach: wplac(double kwota) oraz wyplac(double kwota)
// Obiekt niemutowalny - nie zmienia stanu:
// - Wartość ustalamy w konstruktorze, i tylko tam.
// - żadnej <SUF>
// Override
// Pisząc własną implementację metody equals() musimy przeimplementować także hashCode
}
}
| null |
6273_2 | KPyda/Django | 1,124 | DjangoTest/src/eltharis/wsn/showAllActivity.java | /*
* 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 eltharis.wsn;
import eltharis.wsn.classes.User;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import eltharis.wsn.classes.UserArray;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.simpleframework.xml.*;
import org.simpleframework.xml.core.Persister;
/**
*
* @author eltharis
*/
public class showAllActivity extends ListActivity {
private ArrayAdapter<User> adapter;
private User[] users;
private String executeGET() throws Exception {
HttpClient httpclient = new DefaultHttpClient(); //Korzystamy z Apache, który jest w Android
HttpResponse response = httpclient.execute(new HttpGet("https://agile-depths-5530.herokuapp.com/usershow/")); //każemy mu wykonać GETa
StatusLine statusline = response.getStatusLine(); //sprawdzamy status
Toast toast = Toast.makeText(getApplicationContext(), "HTTP Response: " + Integer.toString(statusline.getStatusCode()), Toast.LENGTH_LONG);
toast.show(); //prosty Toast z HttpStatusCode
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out); //zapisujemy dane HTTP do ByteArrayOutputStream
String responseString = out.toString();
out.close(); //zamykamy OutputStream
return responseString;
}
private void showAll(String httpResponse) {
// TextView tv = (TextView)findViewById(R.id.tv);
// tv.setText(httpResponse);
Serializer ser = new Persister();
try {
UserArray ua = ser.read(UserArray.class, httpResponse);
users = ua.getUsers();
} catch (Exception ex) {
Logger.getLogger(showAllActivity.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
try {
String response = executeGET();
showAll(response);
} catch (Exception e) {
Toast toast = Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG); //do debuggowania
toast.show();
}
adapter = new ArrayAdapter<User>(this,
android.R.layout.simple_list_item_1, users);
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { //nasłuchiwanie, czy jakiś z użytkowników był naciśnięty
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String username = ((TextView) view).getText().toString();
Toast.makeText(getBaseContext(), username, Toast.LENGTH_SHORT).show();
User selected = null;
for (User u : users) {
if (u.getUsername().equals(username)) {
selected = u;
break;
}
}
if (selected != null) {
Intent intent = new Intent(getBaseContext(), showIDActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("id", selected.getId()); //dodajemy jako Extra do intentu. Są to tak jakby parametry
getBaseContext().startActivity(intent); //zaczynamy intent
}
}
});
}
}
| //Korzystamy z Apache, który jest w Android | /*
* 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 eltharis.wsn;
import eltharis.wsn.classes.User;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import eltharis.wsn.classes.UserArray;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.simpleframework.xml.*;
import org.simpleframework.xml.core.Persister;
/**
*
* @author eltharis
*/
public class showAllActivity extends ListActivity {
private ArrayAdapter<User> adapter;
private User[] users;
private String executeGET() throws Exception {
HttpClient httpclient = new DefaultHttpClient(); //Korzystamy z <SUF>
HttpResponse response = httpclient.execute(new HttpGet("https://agile-depths-5530.herokuapp.com/usershow/")); //każemy mu wykonać GETa
StatusLine statusline = response.getStatusLine(); //sprawdzamy status
Toast toast = Toast.makeText(getApplicationContext(), "HTTP Response: " + Integer.toString(statusline.getStatusCode()), Toast.LENGTH_LONG);
toast.show(); //prosty Toast z HttpStatusCode
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out); //zapisujemy dane HTTP do ByteArrayOutputStream
String responseString = out.toString();
out.close(); //zamykamy OutputStream
return responseString;
}
private void showAll(String httpResponse) {
// TextView tv = (TextView)findViewById(R.id.tv);
// tv.setText(httpResponse);
Serializer ser = new Persister();
try {
UserArray ua = ser.read(UserArray.class, httpResponse);
users = ua.getUsers();
} catch (Exception ex) {
Logger.getLogger(showAllActivity.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
try {
String response = executeGET();
showAll(response);
} catch (Exception e) {
Toast toast = Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG); //do debuggowania
toast.show();
}
adapter = new ArrayAdapter<User>(this,
android.R.layout.simple_list_item_1, users);
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { //nasłuchiwanie, czy jakiś z użytkowników był naciśnięty
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String username = ((TextView) view).getText().toString();
Toast.makeText(getBaseContext(), username, Toast.LENGTH_SHORT).show();
User selected = null;
for (User u : users) {
if (u.getUsername().equals(username)) {
selected = u;
break;
}
}
if (selected != null) {
Intent intent = new Intent(getBaseContext(), showIDActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("id", selected.getId()); //dodajemy jako Extra do intentu. Są to tak jakby parametry
getBaseContext().startActivity(intent); //zaczynamy intent
}
}
});
}
}
| null |
9531_0 | Kajzelek/System-zarz-dzaj-cy-plac-wk-o-wiatow- | 3,800 | src/main/java/com/janikcrew/szkola/DemoApplication.java | package com.janikcrew.szkola;
import com.janikcrew.szkola.dao.BudzetDAO;
import com.janikcrew.szkola.dao.BudzetDAOImpl;
import com.janikcrew.szkola.dao.KlasaDAO;
import com.janikcrew.szkola.dao.OsobaDAO;
import com.janikcrew.szkola.entity.*;
import com.janikcrew.szkola.service.*;
import jakarta.persistence.EntityManager;
import org.springframework.aop.scope.ScopedProxyUtils;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cglib.core.Local;
import org.springframework.context.annotation.Bean;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(BudzetService budzetService, OsobaService osobaService,
KlasaService klasaService, PrzedmiotService przedmiotService,
WiadomoscService wiadomoscService, UwagaService uwagaService,
AdminService adminService, GodzinaLekcyjnaService godzinaLekcyjnaService,
MiejsceService miejsceService, DyzurService dyzurService) {
return runner -> {
//utworzOsobe(osobaService);
//testTransakcji(budzetService);
//testUtworzeniaNauczyciela(budzetService, osobaService);
//testUtworzeniaKlasy(osobaService, klasaService);
//testUtworzeniaUcznia(osobaService, klasaService);
//testDodaniaUczniaDoKlasy(klasaService, osobaService);
//testUtworzeniaPrzedmiotu(przedmiotService, klasaService, osobaService);
//testUsunieciaPrzedmiotu(przedmiotService);
//testDzialaniaKlasy(przedmiotService, osobaService, klasaService);
//testUtworzeniaWiadomosci(wiadomoscService, osobaService);
//utworzUwage(uwagaService, osobaService);
//testUtworzeniaKalendarza(adminService);
//testUsunieciaKalendarza(adminService);
//testUtworzeniaGodzinyLekcyjnej(godzinaLekcyjnaService, osobaService, przedmiotService, klasaService, miejsceService);
//testUsunieciaGodzinyLekcyjnej(godzinaLekcyjnaService);
//testDodaniaZastepstwa(godzinaLekcyjnaService, osobaService);
//testDodaniaZastepujacejSali(miejsceService, godzinaLekcyjnaService);
//testDodaniaZdarzenia(godzinaLekcyjnaService);
//testDodaniaMiejsca(miejsceService);
//testModyfikacjiNazwySali(miejsceService);
testUtworzeniaDyzuru(dyzurService);
};
}
private void testUtworzeniaDyzuru(DyzurService dyzurService) {
}
private void testUsunieciaKalendarza(AdminService adminService) {
adminService.wyczyscKalendarz();
}
private void testDodaniaZastepujacejSali(MiejsceService miejsceService, GodzinaLekcyjnaService godzinaLekcyjnaService) {
int idGodzinyLekcyjnej = 15;
int idSaliZastepujacej = 5;
godzinaLekcyjnaService.dodajZastepujacaSale(idGodzinyLekcyjnej, idSaliZastepujacej);
}
private void testModyfikacjiNazwySali(MiejsceService miejsceService) {
String staraNazwa = "Sala Gimnastyczna nr 21";
String nowaNazwa = "Sala gimnastyczna nr 21";
miejsceService.aktualizujMiejsce(staraNazwa, nowaNazwa);
}
private void testDodaniaMiejsca(MiejsceService miejsceService) {
String miejsce = "Sala nr 1";
miejsceService.dodajMiejsce(miejsce);
}
private void testUsunieciaGodzinyLekcyjnej(GodzinaLekcyjnaService godzinaLekcyjnaService) {
int idPrzedmiotu = 3;
godzinaLekcyjnaService.usunGodzineZPlanuByIdPrzedmiotu(idPrzedmiotu);
}
private void testDodaniaZdarzenia(GodzinaLekcyjnaService godzinaLekcyjnaService) {
String zdarzenie = "Klasowe wyjście do kina";
godzinaLekcyjnaService.dodajZdarzenieDoGodzinyLekcyjnej(16, zdarzenie);
}
private void testDodaniaZastepstwa(GodzinaLekcyjnaService godzinaLekcyjnaService, OsobaService osobaService) {
godzinaLekcyjnaService.dodajZastepstwoDoGodzinyLekcyjnej(16, 2);
}
private void testUtworzeniaGodzinyLekcyjnej(GodzinaLekcyjnaService godzinaLekcyjnaService, OsobaService osobaService, PrzedmiotService przedmiotService, KlasaService klasaService, MiejsceService miejsceService) {
Nauczyciel nauczyciel = (Nauczyciel) osobaService.findOsobaById(7);
Przedmiot przedmiot = przedmiotService.findPrzedmiotById(3);
Klasa klasa = klasaService.findKlasaByName("1a");
Miejsce miejsce = miejsceService.findMiejsceById(1);
String dzien = "poniedziałek";
String godzRozpoczecia = "08:00:00";
String dataRozpoczecia = "2023-09-04";
godzinaLekcyjnaService.dodajGodzinaLekcyjnaDoPlanuLekcji(przedmiot, klasa, miejsce, dzien, godzRozpoczecia, dataRozpoczecia);
}
private void testUtworzeniaKalendarza(AdminService adminService) {
adminService.utworzKalendarzNaRokSzkolny();
}
private void utworzUwage(UwagaService uwagaService, OsobaService osobaService) {
Nauczyciel nauczyciel = (Nauczyciel) osobaService.findOsobaById(7);
Uczen uczen = (Uczen) osobaService.findOsobaById(9);
Uwaga uwaga = new Uwaga("NEGATYWNA", "Przeklinanie", "Łukasz przeklinał na lekcji niemieckiego");
uwagaService.utworzUwage(uwaga, nauczyciel, uczen);
}
private void testUtworzeniaWiadomosci(WiadomoscService wiadomoscService, OsobaService osobaService) {
Admin admin = (Admin) osobaService.findOsobaById(1);
Nauczyciel nauczyciel = (Nauczyciel) osobaService.findOsobaById(2);
Wiadomosc wiadomosc = new Wiadomosc("Szanowny Dyrektorze! ", "Dziękuję za przyjęcie do pracy! ");
wiadomoscService.utworzWiadomosc(wiadomosc, nauczyciel, admin);
}
private void testUsunieciaPrzedmiotu(PrzedmiotService przedmiotService) {
int id = 2;
przedmiotService.deletePrzedmiotById(id);
}
private void testDzialaniaKlasy(PrzedmiotService przedmiotService, OsobaService osobaService, KlasaService klasaService) {
Klasa klasa = klasaService.findKlasaByName("1a");
for(Przedmiot przedmiot : klasa.getListaPrzedmiotow()) {
System.out.println(przedmiot.getNazwa());
}
}
private void testUtworzeniaPrzedmiotu(PrzedmiotService przedmiotService, KlasaService klasaService, OsobaService osobaService) {
Przedmiot przedmiot = new Przedmiot("język niemiecki");
String nazwaKlasy = "1a";
int idNauczyciela = 7;
Klasa klasa = klasaService.findKlasaByName(nazwaKlasy);
Nauczyciel nauczyciel = (Nauczyciel) osobaService.findOsobaById(idNauczyciela);
przedmiotService.dodajPrzedmiot(przedmiot, nauczyciel, klasa);
}
private void testDodaniaUczniaDoKlasy(KlasaService klasaService, OsobaService osobaService) {
int id = 3;
int id1 = 6;
String name = "1a";
Klasa klasa = klasaService.findKlasaByName(name);
Uczen uczen = (Uczen) osobaService.findOsobaById(id);
Uczen uczen1 = (Uczen) osobaService.findOsobaById(id1);
klasaService.dodajUcznia(klasa, uczen, uczen1);
}
private void utworzOsobe(OsobaService osobaService) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
Uczen uczen = new Uczen("02256745432", "Kacper", "Łukawski", "[email protected]", LocalDate.parse("2002-12-12"));
Rodzic rodzic = new Rodzic("694785655678", "Maria", "Łukawska", "[email protected]", LocalDate.parse("1969-04-24", formatter));
osobaService.dodajRodzicaUcznia(rodzic, uczen);
}
private void testUtworzeniaUcznia(OsobaService osobaService, KlasaService klasaService) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
Uczen uczen = new Uczen("02222787564", "Łukasz", "Królicki", "[email protected]", LocalDate.parse("2002-02-27", formatter));
Rodzic rodzic = new Rodzic("68983746738", "Grażyna", "Królicka", "[email protected]", LocalDate.parse("1968-11-23", formatter));
Klasa klasa = klasaService.findKlasaByName("1a");
osobaService.dodajRodzicaUcznia(rodzic, uczen);
klasaService.dodajUcznia(klasa, uczen);
}
private void testUtworzeniaKlasy(OsobaService osobaService, KlasaService klasaService) {
int id = 2;
Nauczyciel nauczyciel = (Nauczyciel) osobaService.findOsobaById(id);
Klasa klasa = new Klasa("1a");
klasaService.dodajKlase(klasa, nauczyciel);
}
private void testUtworzeniaNauczyciela(BudzetService budzetService, OsobaService osobaService) {
int id = 2;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//osobaService.dodajUzytkownika(nauczyciel);
osobaService.dodajNauczyciela(new Nauczyciel("57829485748", "Donald", "Tusk", "[email protected]", LocalDate.parse("1957-06-06", formatter)));
}
public void testTransakcji(BudzetService budzetService) throws Exception {
int id = 1;
Budzet budzet = budzetService.findBudzetById(id);
//Transakcja transakcja = new Transakcja("WYDATEK", 20000.0, LocalDate.now(), LocalTime.now(), "Malowanie pomieszczeń");
//budzetService.dodajTransakcjeDoBudzetu(budzet, transakcja);
budzetService.znajdzListeTransakcjiBudzetu(budzet);
for(Transakcja transakcja : budzet.getListaTransakcji())
System.out.println(transakcja);
}
}
| //testUtworzeniaPrzedmiotu(przedmiotService, klasaService, osobaService); | package com.janikcrew.szkola;
import com.janikcrew.szkola.dao.BudzetDAO;
import com.janikcrew.szkola.dao.BudzetDAOImpl;
import com.janikcrew.szkola.dao.KlasaDAO;
import com.janikcrew.szkola.dao.OsobaDAO;
import com.janikcrew.szkola.entity.*;
import com.janikcrew.szkola.service.*;
import jakarta.persistence.EntityManager;
import org.springframework.aop.scope.ScopedProxyUtils;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cglib.core.Local;
import org.springframework.context.annotation.Bean;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(BudzetService budzetService, OsobaService osobaService,
KlasaService klasaService, PrzedmiotService przedmiotService,
WiadomoscService wiadomoscService, UwagaService uwagaService,
AdminService adminService, GodzinaLekcyjnaService godzinaLekcyjnaService,
MiejsceService miejsceService, DyzurService dyzurService) {
return runner -> {
//utworzOsobe(osobaService);
//testTransakcji(budzetService);
//testUtworzeniaNauczyciela(budzetService, osobaService);
//testUtworzeniaKlasy(osobaService, klasaService);
//testUtworzeniaUcznia(osobaService, klasaService);
//testDodaniaUczniaDoKlasy(klasaService, osobaService);
//testUtworzeniaPrzedmiotu(przedmiotService, klasaService, <SUF>
//testUsunieciaPrzedmiotu(przedmiotService);
//testDzialaniaKlasy(przedmiotService, osobaService, klasaService);
//testUtworzeniaWiadomosci(wiadomoscService, osobaService);
//utworzUwage(uwagaService, osobaService);
//testUtworzeniaKalendarza(adminService);
//testUsunieciaKalendarza(adminService);
//testUtworzeniaGodzinyLekcyjnej(godzinaLekcyjnaService, osobaService, przedmiotService, klasaService, miejsceService);
//testUsunieciaGodzinyLekcyjnej(godzinaLekcyjnaService);
//testDodaniaZastepstwa(godzinaLekcyjnaService, osobaService);
//testDodaniaZastepujacejSali(miejsceService, godzinaLekcyjnaService);
//testDodaniaZdarzenia(godzinaLekcyjnaService);
//testDodaniaMiejsca(miejsceService);
//testModyfikacjiNazwySali(miejsceService);
testUtworzeniaDyzuru(dyzurService);
};
}
private void testUtworzeniaDyzuru(DyzurService dyzurService) {
}
private void testUsunieciaKalendarza(AdminService adminService) {
adminService.wyczyscKalendarz();
}
private void testDodaniaZastepujacejSali(MiejsceService miejsceService, GodzinaLekcyjnaService godzinaLekcyjnaService) {
int idGodzinyLekcyjnej = 15;
int idSaliZastepujacej = 5;
godzinaLekcyjnaService.dodajZastepujacaSale(idGodzinyLekcyjnej, idSaliZastepujacej);
}
private void testModyfikacjiNazwySali(MiejsceService miejsceService) {
String staraNazwa = "Sala Gimnastyczna nr 21";
String nowaNazwa = "Sala gimnastyczna nr 21";
miejsceService.aktualizujMiejsce(staraNazwa, nowaNazwa);
}
private void testDodaniaMiejsca(MiejsceService miejsceService) {
String miejsce = "Sala nr 1";
miejsceService.dodajMiejsce(miejsce);
}
private void testUsunieciaGodzinyLekcyjnej(GodzinaLekcyjnaService godzinaLekcyjnaService) {
int idPrzedmiotu = 3;
godzinaLekcyjnaService.usunGodzineZPlanuByIdPrzedmiotu(idPrzedmiotu);
}
private void testDodaniaZdarzenia(GodzinaLekcyjnaService godzinaLekcyjnaService) {
String zdarzenie = "Klasowe wyjście do kina";
godzinaLekcyjnaService.dodajZdarzenieDoGodzinyLekcyjnej(16, zdarzenie);
}
private void testDodaniaZastepstwa(GodzinaLekcyjnaService godzinaLekcyjnaService, OsobaService osobaService) {
godzinaLekcyjnaService.dodajZastepstwoDoGodzinyLekcyjnej(16, 2);
}
private void testUtworzeniaGodzinyLekcyjnej(GodzinaLekcyjnaService godzinaLekcyjnaService, OsobaService osobaService, PrzedmiotService przedmiotService, KlasaService klasaService, MiejsceService miejsceService) {
Nauczyciel nauczyciel = (Nauczyciel) osobaService.findOsobaById(7);
Przedmiot przedmiot = przedmiotService.findPrzedmiotById(3);
Klasa klasa = klasaService.findKlasaByName("1a");
Miejsce miejsce = miejsceService.findMiejsceById(1);
String dzien = "poniedziałek";
String godzRozpoczecia = "08:00:00";
String dataRozpoczecia = "2023-09-04";
godzinaLekcyjnaService.dodajGodzinaLekcyjnaDoPlanuLekcji(przedmiot, klasa, miejsce, dzien, godzRozpoczecia, dataRozpoczecia);
}
private void testUtworzeniaKalendarza(AdminService adminService) {
adminService.utworzKalendarzNaRokSzkolny();
}
private void utworzUwage(UwagaService uwagaService, OsobaService osobaService) {
Nauczyciel nauczyciel = (Nauczyciel) osobaService.findOsobaById(7);
Uczen uczen = (Uczen) osobaService.findOsobaById(9);
Uwaga uwaga = new Uwaga("NEGATYWNA", "Przeklinanie", "Łukasz przeklinał na lekcji niemieckiego");
uwagaService.utworzUwage(uwaga, nauczyciel, uczen);
}
private void testUtworzeniaWiadomosci(WiadomoscService wiadomoscService, OsobaService osobaService) {
Admin admin = (Admin) osobaService.findOsobaById(1);
Nauczyciel nauczyciel = (Nauczyciel) osobaService.findOsobaById(2);
Wiadomosc wiadomosc = new Wiadomosc("Szanowny Dyrektorze! ", "Dziękuję za przyjęcie do pracy! ");
wiadomoscService.utworzWiadomosc(wiadomosc, nauczyciel, admin);
}
private void testUsunieciaPrzedmiotu(PrzedmiotService przedmiotService) {
int id = 2;
przedmiotService.deletePrzedmiotById(id);
}
private void testDzialaniaKlasy(PrzedmiotService przedmiotService, OsobaService osobaService, KlasaService klasaService) {
Klasa klasa = klasaService.findKlasaByName("1a");
for(Przedmiot przedmiot : klasa.getListaPrzedmiotow()) {
System.out.println(przedmiot.getNazwa());
}
}
private void testUtworzeniaPrzedmiotu(PrzedmiotService przedmiotService, KlasaService klasaService, OsobaService osobaService) {
Przedmiot przedmiot = new Przedmiot("język niemiecki");
String nazwaKlasy = "1a";
int idNauczyciela = 7;
Klasa klasa = klasaService.findKlasaByName(nazwaKlasy);
Nauczyciel nauczyciel = (Nauczyciel) osobaService.findOsobaById(idNauczyciela);
przedmiotService.dodajPrzedmiot(przedmiot, nauczyciel, klasa);
}
private void testDodaniaUczniaDoKlasy(KlasaService klasaService, OsobaService osobaService) {
int id = 3;
int id1 = 6;
String name = "1a";
Klasa klasa = klasaService.findKlasaByName(name);
Uczen uczen = (Uczen) osobaService.findOsobaById(id);
Uczen uczen1 = (Uczen) osobaService.findOsobaById(id1);
klasaService.dodajUcznia(klasa, uczen, uczen1);
}
private void utworzOsobe(OsobaService osobaService) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
Uczen uczen = new Uczen("02256745432", "Kacper", "Łukawski", "[email protected]", LocalDate.parse("2002-12-12"));
Rodzic rodzic = new Rodzic("694785655678", "Maria", "Łukawska", "[email protected]", LocalDate.parse("1969-04-24", formatter));
osobaService.dodajRodzicaUcznia(rodzic, uczen);
}
private void testUtworzeniaUcznia(OsobaService osobaService, KlasaService klasaService) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
Uczen uczen = new Uczen("02222787564", "Łukasz", "Królicki", "[email protected]", LocalDate.parse("2002-02-27", formatter));
Rodzic rodzic = new Rodzic("68983746738", "Grażyna", "Królicka", "[email protected]", LocalDate.parse("1968-11-23", formatter));
Klasa klasa = klasaService.findKlasaByName("1a");
osobaService.dodajRodzicaUcznia(rodzic, uczen);
klasaService.dodajUcznia(klasa, uczen);
}
private void testUtworzeniaKlasy(OsobaService osobaService, KlasaService klasaService) {
int id = 2;
Nauczyciel nauczyciel = (Nauczyciel) osobaService.findOsobaById(id);
Klasa klasa = new Klasa("1a");
klasaService.dodajKlase(klasa, nauczyciel);
}
private void testUtworzeniaNauczyciela(BudzetService budzetService, OsobaService osobaService) {
int id = 2;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//osobaService.dodajUzytkownika(nauczyciel);
osobaService.dodajNauczyciela(new Nauczyciel("57829485748", "Donald", "Tusk", "[email protected]", LocalDate.parse("1957-06-06", formatter)));
}
public void testTransakcji(BudzetService budzetService) throws Exception {
int id = 1;
Budzet budzet = budzetService.findBudzetById(id);
//Transakcja transakcja = new Transakcja("WYDATEK", 20000.0, LocalDate.now(), LocalTime.now(), "Malowanie pomieszczeń");
//budzetService.dodajTransakcjeDoBudzetu(budzet, transakcja);
budzetService.znajdzListeTransakcjiBudzetu(budzet);
for(Transakcja transakcja : budzet.getListaTransakcji())
System.out.println(transakcja);
}
}
| null |
5800_2 | KarajuSs/PolskaGRA | 3,533 | src/games/stendhal/server/maps/zakopane/church/WikaryNPC.java | /* $Id: WikaryNPC.java,v 1.25 2011/06/21 02:28:01 Legolas Exp $ */
/***************************************************************************
* (C) Copyright 2003-2010 - Stendhal *
***************************************************************************
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
//Zrobiony na podstawie GateKeeperNPC z Sedah city
package games.stendhal.server.maps.zakopane.church;
import games.stendhal.common.Rand;
import games.stendhal.common.grammar.ItemParserResult;
import games.stendhal.common.parser.Sentence;
import games.stendhal.server.core.config.ZoneConfigurator;
import games.stendhal.server.core.engine.SingletonRepository;
import games.stendhal.server.core.engine.StendhalRPZone;
import games.stendhal.server.entity.item.Item;
import games.stendhal.server.entity.npc.ChatAction;
import games.stendhal.server.core.pathfinder.FixedPath;
import games.stendhal.server.core.pathfinder.Node;
import games.stendhal.server.entity.npc.EventRaiser;
import games.stendhal.server.entity.npc.SpeakerNPC;
import games.stendhal.server.entity.npc.action.BehaviourAction;
import games.stendhal.server.entity.npc.behaviour.impl.Behaviour;
import games.stendhal.server.entity.player.Player;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Builds a gatekeeper NPC Bribe him with at least 300 money to get the key for
* the Sedah city walls. He stands in the doorway of the gatehouse till the
* interior is made.
*
* @author kymara
*/
public class WikaryNPC implements ZoneConfigurator {
/**
* Configure a zone.
*
* @param zone
* The zone to be configured.
* @param attributes
* Configuration attributes.
*/
@Override
public void configureZone(final StendhalRPZone zone, final Map<String, String> attributes) {
buildNPC(zone);
}
private void buildNPC(final StendhalRPZone zone) {
final SpeakerNPC npc = new SpeakerNPC("Wikary") {
@Override
protected void createPath() {
List<Node> nodes = new LinkedList<Node>();
nodes.add(new Node(3, 12));
nodes.add(new Node(8, 12));
nodes.add(new Node(8, 11));
nodes.add(new Node(10, 11));
nodes.add(new Node(10, 10));
nodes.add(new Node(13, 10));
nodes.add(new Node(13, 11));
nodes.add(new Node(15, 11));
nodes.add(new Node(15, 12));
nodes.add(new Node(20, 12));
nodes.add(new Node(15, 12));
nodes.add(new Node(15, 11));
nodes.add(new Node(13, 11));
nodes.add(new Node(13, 10));
nodes.add(new Node(10, 10));
nodes.add(new Node(10, 11));
nodes.add(new Node(8, 11));
nodes.add(new Node(8, 12));
setPath(new FixedPath(nodes, true));
}
@Override
protected void createDialog() {
addGreeting(null, new ChatAction() {
@Override
public void fire(final Player player, final Sentence sentence, final EventRaiser raiser) {
if (player.isEquipped("gigantyczny eliksir")) {
// give some money to get
// giant potion
if (Rand.throwCoin() == 1) {
raiser.say("Widzę, że potrzebujesz więcej.");
} else {
raiser.say("Witaj ponownie.");
}
} else {
raiser.say("Witaj! Czyżbyś przybył tutaj, aby złożyć #'datek'?");
}
}
});
addReply("nic", "Dobrze.");
addJob("Jestem wikarym w Zakopanem. Zbieram pieniądze na zakup organów do kaplicy, zapytaj mnie o #ofertę, aby dowiedzieć się jak mogę Cię wynagrodzić za ten gest.");
addHelp("Wspomóż zakup organów do kaplicy, mówiąc #datek #<ilość> #money lub zdejmij klątwę z siebie, mówiąc #zdejmij #<ilość> #money");
addQuest("Jedyną rzecz jaką potrzebuje to #datek na organy do kaplicy. Po za tym za nie wielką opłatą mogę #zdjąć z Ciebie piętno zabójcy.");
addOffer("Dam ci miksturę, która cię uleczy w zamian za drobny #datek na organy.");
addReply("datek", null,
new BehaviourAction(new Behaviour("money"), Arrays.asList("charity", "datek"), "offer") {
@Override
public void fireSentenceError(Player player, Sentence sentence, EventRaiser raiser) {
raiser.say(sentence.getErrorString() + " Próbujesz mnie oszukać?");
}
@Override
public void fireRequestOK(final ItemParserResult res, final Player player, final Sentence sentence, final EventRaiser raiser) {
final int amount = res.getAmount();
if (sentence.getExpressions().size() == 1) {
// player only said 'datek'
raiser.say("Nie masz tyle pieniędzy, aby wesprzeć zakup organów. Przyjdź kiedy indziej.");
} else {
if (amount < 4000) {
// Less than 4000 is not money for him
raiser.say("Nie masz tyle pieniędzy, aby wesprzeć zakup organów. Przyjdź kiedy indziej.");
} else {
if (player.isEquipped("money", amount)) {
player.drop("money", amount);
raiser.say("Bóg Ci zapłać. Jesteśmy coraz bliżej zakupu nowych organów!");
final Item drink = SingletonRepository.getEntityManager().getItem(
"gigantyczny eliksir");
player.equipOrPutOnGround(drink);
} else {
// player gave enough but doesn't have
// the cash
raiser.say("Nie masz " + amount + " money, aby wesprzeć zakup organów. Przyjdź kiedy indziej.");
}
}
}
}
@Override
public void fireRequestError(final ItemParserResult res, final Player player, final Sentence sentence, final EventRaiser raiser) {
if (res.getChosenItemName() == null) {
fireRequestOK(res, player, sentence, raiser);
} else {
// This bit is just in case the player says 'datek X potatoes', not money
raiser.say("Potrzebuję pieniędzy na zakup organów.");
}
}
});
addReply("zdejmij", null,
new BehaviourAction(new Behaviour("money"), Arrays.asList("remove", "zdejmij"), "offer") {
@Override
public void fireSentenceError(Player player, Sentence sentence, EventRaiser raiser) {
raiser.say(sentence.getErrorString() + " Próbujesz mnie oszukać?");
}
@Override
public void fireRequestOK(final ItemParserResult res, final Player player, final Sentence sentence, final EventRaiser raiser) {
final int amount = res.getAmount();
if (sentence.getExpressions().size() == 1) {
// player only said 'zdejmij'
raiser.say("Nie masz tyle pieniędzy, abym mógł zdjąć z Ciebie piętno zabójcy. Przyjdź kiedy indziej.");
} else {
if (amount < 100000) {
// Less than 100000 is not money for him
raiser.say("Nie masz tyle pieniędzy, abym mógł zdjąć z Ciebie piętno zabójcy. Przyjdź kiedy indziej.");
} else {
if (player.isEquipped("money", amount)) {
player.drop("money", amount);
player.rehabilitate();
raiser.say("Zdjąłem z Ciebie piętno zabójcy. Uważaj na siebie!");
} else {
// player gave enough but doesn't have
// the cash
raiser.say("Nie masz " + amount + " money, abym mógł zdjąć z Ciebie piętno zabójcy.");
}
}
}
}
@Override
public void fireRequestError(final ItemParserResult res, final Player player, final Sentence sentence, final EventRaiser raiser) {
if (res.getChosenItemName() == null) {
fireRequestOK(res, player, sentence, raiser);
} else {
// This bit is just in case the player says 'datek X potatoes', not money
raiser.say("Potrzebuję pieniędzy na zakup organów.");
}
}
});
addGoodbye("Bywaj!");
}
};
npc.setDescription("Oto Wikary. Zbiera pieniądze na zakup organów do kaplicy.");
/*
* We don't seem to be using the recruiter images that lenocas made for
* the Fado Raid area so I'm going to put him to use here. If the raid
* part ever gets done, this image can change.
*/
npc.setEntityClass("npcwikary");
npc.setPosition(3, 12);
npc.initHP(100);
zone.add(npc);
}
}
| //Zrobiony na podstawie GateKeeperNPC z Sedah city | /* $Id: WikaryNPC.java,v 1.25 2011/06/21 02:28:01 Legolas Exp $ */
/***************************************************************************
* (C) Copyright 2003-2010 - Stendhal *
***************************************************************************
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
//Zrobiony na <SUF>
package games.stendhal.server.maps.zakopane.church;
import games.stendhal.common.Rand;
import games.stendhal.common.grammar.ItemParserResult;
import games.stendhal.common.parser.Sentence;
import games.stendhal.server.core.config.ZoneConfigurator;
import games.stendhal.server.core.engine.SingletonRepository;
import games.stendhal.server.core.engine.StendhalRPZone;
import games.stendhal.server.entity.item.Item;
import games.stendhal.server.entity.npc.ChatAction;
import games.stendhal.server.core.pathfinder.FixedPath;
import games.stendhal.server.core.pathfinder.Node;
import games.stendhal.server.entity.npc.EventRaiser;
import games.stendhal.server.entity.npc.SpeakerNPC;
import games.stendhal.server.entity.npc.action.BehaviourAction;
import games.stendhal.server.entity.npc.behaviour.impl.Behaviour;
import games.stendhal.server.entity.player.Player;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Builds a gatekeeper NPC Bribe him with at least 300 money to get the key for
* the Sedah city walls. He stands in the doorway of the gatehouse till the
* interior is made.
*
* @author kymara
*/
public class WikaryNPC implements ZoneConfigurator {
/**
* Configure a zone.
*
* @param zone
* The zone to be configured.
* @param attributes
* Configuration attributes.
*/
@Override
public void configureZone(final StendhalRPZone zone, final Map<String, String> attributes) {
buildNPC(zone);
}
private void buildNPC(final StendhalRPZone zone) {
final SpeakerNPC npc = new SpeakerNPC("Wikary") {
@Override
protected void createPath() {
List<Node> nodes = new LinkedList<Node>();
nodes.add(new Node(3, 12));
nodes.add(new Node(8, 12));
nodes.add(new Node(8, 11));
nodes.add(new Node(10, 11));
nodes.add(new Node(10, 10));
nodes.add(new Node(13, 10));
nodes.add(new Node(13, 11));
nodes.add(new Node(15, 11));
nodes.add(new Node(15, 12));
nodes.add(new Node(20, 12));
nodes.add(new Node(15, 12));
nodes.add(new Node(15, 11));
nodes.add(new Node(13, 11));
nodes.add(new Node(13, 10));
nodes.add(new Node(10, 10));
nodes.add(new Node(10, 11));
nodes.add(new Node(8, 11));
nodes.add(new Node(8, 12));
setPath(new FixedPath(nodes, true));
}
@Override
protected void createDialog() {
addGreeting(null, new ChatAction() {
@Override
public void fire(final Player player, final Sentence sentence, final EventRaiser raiser) {
if (player.isEquipped("gigantyczny eliksir")) {
// give some money to get
// giant potion
if (Rand.throwCoin() == 1) {
raiser.say("Widzę, że potrzebujesz więcej.");
} else {
raiser.say("Witaj ponownie.");
}
} else {
raiser.say("Witaj! Czyżbyś przybył tutaj, aby złożyć #'datek'?");
}
}
});
addReply("nic", "Dobrze.");
addJob("Jestem wikarym w Zakopanem. Zbieram pieniądze na zakup organów do kaplicy, zapytaj mnie o #ofertę, aby dowiedzieć się jak mogę Cię wynagrodzić za ten gest.");
addHelp("Wspomóż zakup organów do kaplicy, mówiąc #datek #<ilość> #money lub zdejmij klątwę z siebie, mówiąc #zdejmij #<ilość> #money");
addQuest("Jedyną rzecz jaką potrzebuje to #datek na organy do kaplicy. Po za tym za nie wielką opłatą mogę #zdjąć z Ciebie piętno zabójcy.");
addOffer("Dam ci miksturę, która cię uleczy w zamian za drobny #datek na organy.");
addReply("datek", null,
new BehaviourAction(new Behaviour("money"), Arrays.asList("charity", "datek"), "offer") {
@Override
public void fireSentenceError(Player player, Sentence sentence, EventRaiser raiser) {
raiser.say(sentence.getErrorString() + " Próbujesz mnie oszukać?");
}
@Override
public void fireRequestOK(final ItemParserResult res, final Player player, final Sentence sentence, final EventRaiser raiser) {
final int amount = res.getAmount();
if (sentence.getExpressions().size() == 1) {
// player only said 'datek'
raiser.say("Nie masz tyle pieniędzy, aby wesprzeć zakup organów. Przyjdź kiedy indziej.");
} else {
if (amount < 4000) {
// Less than 4000 is not money for him
raiser.say("Nie masz tyle pieniędzy, aby wesprzeć zakup organów. Przyjdź kiedy indziej.");
} else {
if (player.isEquipped("money", amount)) {
player.drop("money", amount);
raiser.say("Bóg Ci zapłać. Jesteśmy coraz bliżej zakupu nowych organów!");
final Item drink = SingletonRepository.getEntityManager().getItem(
"gigantyczny eliksir");
player.equipOrPutOnGround(drink);
} else {
// player gave enough but doesn't have
// the cash
raiser.say("Nie masz " + amount + " money, aby wesprzeć zakup organów. Przyjdź kiedy indziej.");
}
}
}
}
@Override
public void fireRequestError(final ItemParserResult res, final Player player, final Sentence sentence, final EventRaiser raiser) {
if (res.getChosenItemName() == null) {
fireRequestOK(res, player, sentence, raiser);
} else {
// This bit is just in case the player says 'datek X potatoes', not money
raiser.say("Potrzebuję pieniędzy na zakup organów.");
}
}
});
addReply("zdejmij", null,
new BehaviourAction(new Behaviour("money"), Arrays.asList("remove", "zdejmij"), "offer") {
@Override
public void fireSentenceError(Player player, Sentence sentence, EventRaiser raiser) {
raiser.say(sentence.getErrorString() + " Próbujesz mnie oszukać?");
}
@Override
public void fireRequestOK(final ItemParserResult res, final Player player, final Sentence sentence, final EventRaiser raiser) {
final int amount = res.getAmount();
if (sentence.getExpressions().size() == 1) {
// player only said 'zdejmij'
raiser.say("Nie masz tyle pieniędzy, abym mógł zdjąć z Ciebie piętno zabójcy. Przyjdź kiedy indziej.");
} else {
if (amount < 100000) {
// Less than 100000 is not money for him
raiser.say("Nie masz tyle pieniędzy, abym mógł zdjąć z Ciebie piętno zabójcy. Przyjdź kiedy indziej.");
} else {
if (player.isEquipped("money", amount)) {
player.drop("money", amount);
player.rehabilitate();
raiser.say("Zdjąłem z Ciebie piętno zabójcy. Uważaj na siebie!");
} else {
// player gave enough but doesn't have
// the cash
raiser.say("Nie masz " + amount + " money, abym mógł zdjąć z Ciebie piętno zabójcy.");
}
}
}
}
@Override
public void fireRequestError(final ItemParserResult res, final Player player, final Sentence sentence, final EventRaiser raiser) {
if (res.getChosenItemName() == null) {
fireRequestOK(res, player, sentence, raiser);
} else {
// This bit is just in case the player says 'datek X potatoes', not money
raiser.say("Potrzebuję pieniędzy na zakup organów.");
}
}
});
addGoodbye("Bywaj!");
}
};
npc.setDescription("Oto Wikary. Zbiera pieniądze na zakup organów do kaplicy.");
/*
* We don't seem to be using the recruiter images that lenocas made for
* the Fado Raid area so I'm going to put him to use here. If the raid
* part ever gets done, this image can change.
*/
npc.setEntityClass("npcwikary");
npc.setPosition(3, 12);
npc.initHP(100);
zone.add(npc);
}
}
| null |
4469_2 | KarolWojnar/ProgramowanieOb | 578 | src/PO_lab2_Swing.java | import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class PO_lab2_Swing {
private JPanel Panel1;
private JButton startButton;
private JButton stopButton;
private JLabel LabA;
private JTextField textFieldA;
private JTextField textFieldB;
private JLabel WynikLab;
private JLabel DataLabel;
double stopnie;
double wynik;
// public static void main(String[] args) {
// PO_lab2_Swing okienko = new PO_lab2_Swing();
// okienko.setVisible(true);//wyswietla ramke
// }
// public PO_lab2_Swing()
// {
// super("Moja pierwsza aplikacja");
// this.setContentPane(this.Panel1);//wysw. na ekranie
// this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//zamkniecie okna
// this.setSize(300, 400);//rozmiar okienka
// this.pack();//pozwala spakować wszystko i dostosuje wielkość
// }
//sposob 2
public static void main(String[] args) {
PO_lab2_Swing okienko2 = new PO_lab2_Swing();
}
public PO_lab2_Swing()
{
JFrame frame = new JFrame("Moja pierwsza apka");
frame.setContentPane(this.Panel1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(500, 500);
// frame.pack();
stopButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
stopnie = Double.parseDouble(textFieldA.getText());
wynik = stopnie+32;
WynikLab.setText(String.valueOf(stopnie)+" na Fahreneity to: "+ String.valueOf(wynik));
}
});
}
}
| // super("Moja pierwsza aplikacja");
| import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class PO_lab2_Swing {
private JPanel Panel1;
private JButton startButton;
private JButton stopButton;
private JLabel LabA;
private JTextField textFieldA;
private JTextField textFieldB;
private JLabel WynikLab;
private JLabel DataLabel;
double stopnie;
double wynik;
// public static void main(String[] args) {
// PO_lab2_Swing okienko = new PO_lab2_Swing();
// okienko.setVisible(true);//wyswietla ramke
// }
// public PO_lab2_Swing()
// {
// super("Moja pierwsza <SUF>
// this.setContentPane(this.Panel1);//wysw. na ekranie
// this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//zamkniecie okna
// this.setSize(300, 400);//rozmiar okienka
// this.pack();//pozwala spakować wszystko i dostosuje wielkość
// }
//sposob 2
public static void main(String[] args) {
PO_lab2_Swing okienko2 = new PO_lab2_Swing();
}
public PO_lab2_Swing()
{
JFrame frame = new JFrame("Moja pierwsza apka");
frame.setContentPane(this.Panel1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(500, 500);
// frame.pack();
stopButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
stopnie = Double.parseDouble(textFieldA.getText());
wynik = stopnie+32;
WynikLab.setText(String.valueOf(stopnie)+" na Fahreneity to: "+ String.valueOf(wynik));
}
});
}
}
| null |
6149_0 | Karolk99/ProjektPO | 320 | src/World.java | import java.io.IOException;
import java.util.*;
public class World {
public static void main( String[] args ) throws InterruptedException, IOException {
int width = 20;
int height = 20;
int moveEnergy = 1;
int grassEnregy = 5;
int startEnergy = 5;
double jungleRatio = 0.4;
int firstAnimals = 10;
int amountofGrass = 50;
Simulation pierwsza = new Simulation(width,height,moveEnergy,grassEnregy,startEnergy,jungleRatio, firstAnimals, amountofGrass);
MapVisualizer visualizer = new MapVisualizer(pierwsza.getMap());
int days = 1000;
for(int i = 0; i< days; i++) {
System.out.println(visualizer.draw(new Vector2d(0, 0), new Vector2d(19, 19)));
pierwsza.oneDay();
Thread.sleep(100);
}
}
}
// przepraszam ze nie nakłada się jedno na drugie ale nie potrafiłem sobie z tym poradzić | // przepraszam ze nie nakłada się jedno na drugie ale nie potrafiłem sobie z tym poradzić | import java.io.IOException;
import java.util.*;
public class World {
public static void main( String[] args ) throws InterruptedException, IOException {
int width = 20;
int height = 20;
int moveEnergy = 1;
int grassEnregy = 5;
int startEnergy = 5;
double jungleRatio = 0.4;
int firstAnimals = 10;
int amountofGrass = 50;
Simulation pierwsza = new Simulation(width,height,moveEnergy,grassEnregy,startEnergy,jungleRatio, firstAnimals, amountofGrass);
MapVisualizer visualizer = new MapVisualizer(pierwsza.getMap());
int days = 1000;
for(int i = 0; i< days; i++) {
System.out.println(visualizer.draw(new Vector2d(0, 0), new Vector2d(19, 19)));
pierwsza.oneDay();
Thread.sleep(100);
}
}
}
// przepraszam ze <SUF> | null |
6901_0 | Krzysztof-Switek/kodilla-course | 344 | kodilla-collections/src/main/java/com/kodilla/collections/lists/homework/CarsListApplication.java | package com.kodilla.collections.lists.homework;
import com.kodilla.collections.arrays.homework.Car;
import java.util.ArrayList;
import java.util.List;
public class CarsListApplication {
public static void main(String[] args) {
List<Car> cars = new ArrayList<>(); // carList intelij podpowiada - dlaczego?
cars.add(new Car("VW", "T4",1997,150));
cars.add(new Car("Citroen", "Picasso",2020,180));
cars.add(new Car("Ford", "Fiesta",2006,130));
cars.add(new Car("Toyota", "Proace",2023,170));
for (Car addedCars : cars) {
System.out.println(addedCars);
}
// usuwam T4
cars.remove(0);
System.out.println(cars);
// usuwam toyota
Car carToRemove = new Car("Toyota", "Proace",2023,170);
cars.remove(carToRemove);
System.out.println(cars);
System.out.println("Długość listy cars to: " + cars.size());
}
}
| // carList intelij podpowiada - dlaczego? | package com.kodilla.collections.lists.homework;
import com.kodilla.collections.arrays.homework.Car;
import java.util.ArrayList;
import java.util.List;
public class CarsListApplication {
public static void main(String[] args) {
List<Car> cars = new ArrayList<>(); // carList intelij <SUF>
cars.add(new Car("VW", "T4",1997,150));
cars.add(new Car("Citroen", "Picasso",2020,180));
cars.add(new Car("Ford", "Fiesta",2006,130));
cars.add(new Car("Toyota", "Proace",2023,170));
for (Car addedCars : cars) {
System.out.println(addedCars);
}
// usuwam T4
cars.remove(0);
System.out.println(cars);
// usuwam toyota
Car carToRemove = new Car("Toyota", "Proace",2023,170);
cars.remove(carToRemove);
System.out.println(cars);
System.out.println("Długość listy cars to: " + cars.size());
}
}
| null |
3402_3 | Liby99/Tillerinobot | 2,936 | tillerinobot/src/main/java/tillerino/tillerinobot/lang/Polski.java | package tillerino.tillerinobot.lang;
import java.util.List;
import java.util.Random;
import org.tillerino.osuApiModel.Mods;
import org.tillerino.osuApiModel.OsuApiUser;
import tillerino.tillerinobot.BeatmapMeta;
import tillerino.tillerinobot.IRCBot.IRCBotUser;
import tillerino.tillerinobot.RecommendationsManager.Recommendation;
/**
* Polish language implementation by https://osu.ppy.sh/u/pawwit
*/
public class Polski implements Language {
@Override
public String unknownBeatmap() {
return "Przykro mi, nie znam tej mapy. Możliwe że jest ona nowa albo nierankingowa.";
}
@Override
public String internalException(String marker) {
return "Ugh... Wygląda na to że Tillerino (człowiek) uszkodził moje obwody."
+ "Gdyby wkrótce tego nie zauważył, Możesz go poinformować? Znajdziesz go na @Tillerino lub /u/Tillerino? (odwołanie "
+ marker + ")";
}
@Override
public String externalException(String marker) {
return "Co jest?! Odpowiedź serwera osu nie ma sensu. Możesz mi powiedzieć co to znaczy \"0011101001010000\"?"
+ " Tillerino (człowiek) mówi, żeby się tym nie przejmować oraz że powinniśmy spróbować jeszcze raz."
+ " Jeśli jesteś bardzo zaniepokojony z jakiegoś powodu, możesz mu powiedzieć o tym na @Tillerino lub /u/Tillerino. (odwołanie "
+ marker + ")";
}
@Override
public String noInformationForModsShort() {
return "brak danych dla wskazanych modów";
}
@Override
public void welcomeUser(IRCBotUser user, OsuApiUser apiUser, long inactiveTime) {
if(inactiveTime < 60 * 1000) {
user.message("beep boop");
} else if(inactiveTime < 24 * 60 * 60 * 1000) {
user.message("Witaj ponownie, " + apiUser.getUserName() + ".");
} else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) {
user.message(apiUser.getUserName() + "...");
user.message("...czy to Ty? Minęło sporo czasu!");
user.message("Dobrze znowu Cie widzieć. Chcesz usłyszeć kilka rekomendacji?");
} else {
String[] messages = {
"wygląda na to że chcesz jakieś rekomendacje.",
"jak dobrze Cie widzieć! :)",
"mój ulubiony człowiek. (Nie mów o tym innym ludziom!)",
"jakie miłe zaskoczenie! ^.^",
"Miałem nadzieję, że się pojawisz. Jesteś fajniejszy niż inni ludzie :3 (nie mówi im że Ci to powiedziałem!)",
"jak się masz?",
};
Random random = new Random();
String message = messages[random.nextInt(messages.length)];
user.message(apiUser.getUserName() + ", " + message);
}
}
@Override
public String unknownCommand(String command) {
return "nieznana komenda \"" + command
+ "\". jeśli potrzebujesz pomocy napisz \"!help\" !";
}
@Override
public String noInformationForMods() {
return "Przykro mi, nie mogę dostarczyć informacji dla tych modów w tym momencie.";
}
@Override
public String malformattedMods(String mods) {
return "Coś się nie zgadza. Mody mogą być dowolną kombinacją DT HR HD HT EZ NC FL SO NF. Łącz je nie używając spacji, ani żadnych znaków. Przykład: !with HDHR, !with DTEZ";
}
@Override
public String noLastSongInfo() {
return "Nie pamiętam żebyś pytał się ostatnio o jakąś piosenkę...";
}
@Override
public String tryWithMods() {
return "Spróbuj zagrać tą mapę z modami!";
}
@Override
public String tryWithMods(List<Mods> mods) {
return "Spróbuj zagrać tą mapę z " + Mods.toShortNamesContinuous(mods);
}
/**
* The user's IRC nick name could not be resolved to an osu user id. The
* message should suggest to contact @Tillerinobot or /u/Tillerino.
*
* @param exceptionMarker
* a marker to reference the created log entry. six or eight
* characters.
* @param name
* the irc nick which could not be resolved
* @return
*/
public String unresolvableName(String exceptionMarker, String name) {
return "Twoja nazwa wydaje mi się jakaś dziwna. Jesteś zbanowany? Jeśli nie napisz na @Tillerino lub /u/Tillerino (odwołanie "
+ exceptionMarker + ")";
}
@Override
public String excuseForError() {
return "Wybacz, widziałem piękną sekwencję zer i jedynek przez co się trochę rozkojarzyłem. Mógłbyś powtórzyć co chciałeś?";
}
@Override
public String complaint() {
return "Twoje zgłoszenie zostało wypełnione. Tillerino zerknie na nie jak tylko będzie mógł.";
}
@Override
public void hug(final IRCBotUser user, OsuApiUser apiUser) {
user.message("Chodź tu!");
user.action("przytula " + apiUser.getUserName());
}
@Override
public String help() {
return "Hej! Jestem robotem który zabił Tillerino, aby przejąc jego konto. Tylko żartowałem, czasem używam tego konta."
+ " Sprawdź https://twitter.com/Tillerinobot żeby zobaczyć najnowsze aktualizacje!"
+ " Odwiedź https://github.com/Tillerino/Tillerinobot/wiki żeby poznać komendy!";
}
@Override
public String faq() {
return "Wejdź na https://github.com/Tillerino/Tillerinobot/wiki/FAQ aby zobaczyć FAQ!";
}
@Override
public String featureRankRestricted(String feature, int minRank, OsuApiUser user) {
return "Przepraszam, ale w tym momencie " + feature + " jest dostępna tylko dla ludzi którzy przekroczyli pozycję " + minRank + " w rankingu.";
}
@Override
public String mixedNomodAndMods() {
return "Jak chcesz połączyć brak modów z modami?";
}
@Override
public String outOfRecommendations() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do"
+ " Skończyły mi się pomysł co mogę Ci jeszcze polecić]."
+ " Sprawdź inne opcje polecania albo użyj komendy !reset. Jeśli nie wiesz o co mi chodzi wpisz !help.";
}
@Override
public String notRanked() {
return "Wygląda na to, że ta mapa nie jest rankingowa.";
}
@Override
public void optionalCommentOnNP(IRCBotUser user,
OsuApiUser apiUser, BeatmapMeta meta) {
// regular Tillerino doesn't comment on this
// return "Ok, zapamiętam tą mapę!";
}
@Override
public void optionalCommentOnWith(IRCBotUser user, OsuApiUser apiUser,
BeatmapMeta meta) {
// regular Tillerino doesn't comment on this
// return "Ok, zapamiętam te mody";
}
@Override
public void optionalCommentOnRecommendation(IRCBotUser user,
OsuApiUser apiUser, Recommendation meta) {
// regular Tillerino doesn't comment on this
// I have no idea what Tillerino can say with recommendation
}
@Override
public boolean isChanged() {
return false;
}
@Override
public void setChanged(boolean changed) {
}
@Override
public String invalidAccuracy(String acc) {
return "Nieprawidłowa celność: \"" + acc + "\"";
}
@Override
public void optionalCommentOnLanguage(IRCBotUser user, OsuApiUser apiUser) {
user.message("Pawwit nauczył mnie jak mówić po polsku, jeśli uważasz, że gdzieś się pomylił napisz do niego na osu!");
}
@Override
public String invalidChoice(String invalid, String choices) {
return "Wybacz, nie wiem co \"" + invalid
+ "\" znaczy. Spróbuj: " + choices + "!";
}
@Override
public String setFormat() {
return "Składnia polecenia \"!set\" jest następująca \"!set opcja wartość\". Wpisz !help jeśli potrzebujesz więcej wskazówek.";
}
@Override
public String apiTimeoutException() {
return new Default().apiTimeoutException();
}
@Override
public String noRecentPlays() {
return new Default().noRecentPlays();
}
@Override
public String isSetId() {
return new Default().isSetId();
}
@Override
public String getPatience() {
return new Default().getPatience();
}
} | //github.com/Tillerino/Tillerinobot/wiki żeby poznać komendy!"; | package tillerino.tillerinobot.lang;
import java.util.List;
import java.util.Random;
import org.tillerino.osuApiModel.Mods;
import org.tillerino.osuApiModel.OsuApiUser;
import tillerino.tillerinobot.BeatmapMeta;
import tillerino.tillerinobot.IRCBot.IRCBotUser;
import tillerino.tillerinobot.RecommendationsManager.Recommendation;
/**
* Polish language implementation by https://osu.ppy.sh/u/pawwit
*/
public class Polski implements Language {
@Override
public String unknownBeatmap() {
return "Przykro mi, nie znam tej mapy. Możliwe że jest ona nowa albo nierankingowa.";
}
@Override
public String internalException(String marker) {
return "Ugh... Wygląda na to że Tillerino (człowiek) uszkodził moje obwody."
+ "Gdyby wkrótce tego nie zauważył, Możesz go poinformować? Znajdziesz go na @Tillerino lub /u/Tillerino? (odwołanie "
+ marker + ")";
}
@Override
public String externalException(String marker) {
return "Co jest?! Odpowiedź serwera osu nie ma sensu. Możesz mi powiedzieć co to znaczy \"0011101001010000\"?"
+ " Tillerino (człowiek) mówi, żeby się tym nie przejmować oraz że powinniśmy spróbować jeszcze raz."
+ " Jeśli jesteś bardzo zaniepokojony z jakiegoś powodu, możesz mu powiedzieć o tym na @Tillerino lub /u/Tillerino. (odwołanie "
+ marker + ")";
}
@Override
public String noInformationForModsShort() {
return "brak danych dla wskazanych modów";
}
@Override
public void welcomeUser(IRCBotUser user, OsuApiUser apiUser, long inactiveTime) {
if(inactiveTime < 60 * 1000) {
user.message("beep boop");
} else if(inactiveTime < 24 * 60 * 60 * 1000) {
user.message("Witaj ponownie, " + apiUser.getUserName() + ".");
} else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) {
user.message(apiUser.getUserName() + "...");
user.message("...czy to Ty? Minęło sporo czasu!");
user.message("Dobrze znowu Cie widzieć. Chcesz usłyszeć kilka rekomendacji?");
} else {
String[] messages = {
"wygląda na to że chcesz jakieś rekomendacje.",
"jak dobrze Cie widzieć! :)",
"mój ulubiony człowiek. (Nie mów o tym innym ludziom!)",
"jakie miłe zaskoczenie! ^.^",
"Miałem nadzieję, że się pojawisz. Jesteś fajniejszy niż inni ludzie :3 (nie mówi im że Ci to powiedziałem!)",
"jak się masz?",
};
Random random = new Random();
String message = messages[random.nextInt(messages.length)];
user.message(apiUser.getUserName() + ", " + message);
}
}
@Override
public String unknownCommand(String command) {
return "nieznana komenda \"" + command
+ "\". jeśli potrzebujesz pomocy napisz \"!help\" !";
}
@Override
public String noInformationForMods() {
return "Przykro mi, nie mogę dostarczyć informacji dla tych modów w tym momencie.";
}
@Override
public String malformattedMods(String mods) {
return "Coś się nie zgadza. Mody mogą być dowolną kombinacją DT HR HD HT EZ NC FL SO NF. Łącz je nie używając spacji, ani żadnych znaków. Przykład: !with HDHR, !with DTEZ";
}
@Override
public String noLastSongInfo() {
return "Nie pamiętam żebyś pytał się ostatnio o jakąś piosenkę...";
}
@Override
public String tryWithMods() {
return "Spróbuj zagrać tą mapę z modami!";
}
@Override
public String tryWithMods(List<Mods> mods) {
return "Spróbuj zagrać tą mapę z " + Mods.toShortNamesContinuous(mods);
}
/**
* The user's IRC nick name could not be resolved to an osu user id. The
* message should suggest to contact @Tillerinobot or /u/Tillerino.
*
* @param exceptionMarker
* a marker to reference the created log entry. six or eight
* characters.
* @param name
* the irc nick which could not be resolved
* @return
*/
public String unresolvableName(String exceptionMarker, String name) {
return "Twoja nazwa wydaje mi się jakaś dziwna. Jesteś zbanowany? Jeśli nie napisz na @Tillerino lub /u/Tillerino (odwołanie "
+ exceptionMarker + ")";
}
@Override
public String excuseForError() {
return "Wybacz, widziałem piękną sekwencję zer i jedynek przez co się trochę rozkojarzyłem. Mógłbyś powtórzyć co chciałeś?";
}
@Override
public String complaint() {
return "Twoje zgłoszenie zostało wypełnione. Tillerino zerknie na nie jak tylko będzie mógł.";
}
@Override
public void hug(final IRCBotUser user, OsuApiUser apiUser) {
user.message("Chodź tu!");
user.action("przytula " + apiUser.getUserName());
}
@Override
public String help() {
return "Hej! Jestem robotem który zabił Tillerino, aby przejąc jego konto. Tylko żartowałem, czasem używam tego konta."
+ " Sprawdź https://twitter.com/Tillerinobot żeby zobaczyć najnowsze aktualizacje!"
+ " Odwiedź https://github.com/Tillerino/Tillerinobot/wiki żeby <SUF>
}
@Override
public String faq() {
return "Wejdź na https://github.com/Tillerino/Tillerinobot/wiki/FAQ aby zobaczyć FAQ!";
}
@Override
public String featureRankRestricted(String feature, int minRank, OsuApiUser user) {
return "Przepraszam, ale w tym momencie " + feature + " jest dostępna tylko dla ludzi którzy przekroczyli pozycję " + minRank + " w rankingu.";
}
@Override
public String mixedNomodAndMods() {
return "Jak chcesz połączyć brak modów z modami?";
}
@Override
public String outOfRecommendations() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do"
+ " Skończyły mi się pomysł co mogę Ci jeszcze polecić]."
+ " Sprawdź inne opcje polecania albo użyj komendy !reset. Jeśli nie wiesz o co mi chodzi wpisz !help.";
}
@Override
public String notRanked() {
return "Wygląda na to, że ta mapa nie jest rankingowa.";
}
@Override
public void optionalCommentOnNP(IRCBotUser user,
OsuApiUser apiUser, BeatmapMeta meta) {
// regular Tillerino doesn't comment on this
// return "Ok, zapamiętam tą mapę!";
}
@Override
public void optionalCommentOnWith(IRCBotUser user, OsuApiUser apiUser,
BeatmapMeta meta) {
// regular Tillerino doesn't comment on this
// return "Ok, zapamiętam te mody";
}
@Override
public void optionalCommentOnRecommendation(IRCBotUser user,
OsuApiUser apiUser, Recommendation meta) {
// regular Tillerino doesn't comment on this
// I have no idea what Tillerino can say with recommendation
}
@Override
public boolean isChanged() {
return false;
}
@Override
public void setChanged(boolean changed) {
}
@Override
public String invalidAccuracy(String acc) {
return "Nieprawidłowa celność: \"" + acc + "\"";
}
@Override
public void optionalCommentOnLanguage(IRCBotUser user, OsuApiUser apiUser) {
user.message("Pawwit nauczył mnie jak mówić po polsku, jeśli uważasz, że gdzieś się pomylił napisz do niego na osu!");
}
@Override
public String invalidChoice(String invalid, String choices) {
return "Wybacz, nie wiem co \"" + invalid
+ "\" znaczy. Spróbuj: " + choices + "!";
}
@Override
public String setFormat() {
return "Składnia polecenia \"!set\" jest następująca \"!set opcja wartość\". Wpisz !help jeśli potrzebujesz więcej wskazówek.";
}
@Override
public String apiTimeoutException() {
return new Default().apiTimeoutException();
}
@Override
public String noRecentPlays() {
return new Default().noRecentPlays();
}
@Override
public String isSetId() {
return new Default().isSetId();
}
@Override
public String getPatience() {
return new Default().getPatience();
}
} | null |
3161_0 | M4GiK/ztp-projects | 854 | Plate/Plate.java | /**
* Project Praca domowa 01 – plate.
* Copyright Michał Szczygieł
* Created at Oct 16, 2013.
*/
import java.util.ArrayList;
import java.util.Collections;
/**
* Class, counting cost for cutting plate.
*
* @author Michał Szczygieł <[email protected]>
*
*/
public class Plate {
/**
* Variable stores data with weights for horizontal cuts.
*/
private ArrayList<Integer> arrayX = null;
/**
* Variable stores data with weights for vertical cuts.
*/
private ArrayList<Integer> arrayY = null;
/**
* Constructor for Plate class. Automatically set arrays with values for vertical and horizontal cuts.
*
* @param arrayX
* @param arrayY
*/
public Plate(ArrayList<Integer> arrayX, ArrayList<Integer> arrayY) {
setArrayX(arrayX);
setArrayY(arrayY);
}
/**
* Method counts cost of cuts.
*
* @return cost of cuts.
*/
public String cutCost() {
// Arrays needs sort, to finding optimal cost.
Collections.sort(getArrayX());
Collections.sort(getArrayY());
int accumulator = 0;
int horizontalLines = 1;
int verticalLines = 1;
int sizeX = getArrayX().size();
int sizeY = getArrayY().size();
int numberOfIterations = sizeX + sizeY;
for (int i = 0; i < numberOfIterations; i++) {
int maxX = 0;
int maxY = 0;
if (getArrayX().size() > 0) {
maxX = Collections.max(getArrayX());
}
if (getArrayY().size() > 0) {
maxY = Collections.max(getArrayY());
}
if (maxX > maxY) {
if (getArrayX().size() > 0) {
accumulator += maxX * horizontalLines;
getArrayX().remove(sizeX - 1);
verticalLines++;
sizeX--;
}
} else {
if (getArrayY().size() > 0) {
accumulator += maxY * verticalLines;
getArrayY().remove(sizeY - 1);
horizontalLines++;
sizeY--;
}
}
}
return "Koszt cięcia : " + accumulator;
}
/**
* @return the arrayX
*/
public ArrayList<Integer> getArrayX() {
return arrayX;
}
/**
* @return the arrayY
*/
public ArrayList<Integer> getArrayY() {
return arrayY;
}
/**
* @param arrayX
* the arrayX to set
*/
public void setArrayX(ArrayList<Integer> arrayX) {
this.arrayX = arrayX;
}
/**
* @param arrayY
* the arrayY to set
*/
public void setArrayY(ArrayList<Integer> arrayY) {
this.arrayY = arrayY;
}
}
| /**
* Project Praca domowa 01 – plate.
* Copyright Michał Szczygieł
* Created at Oct 16, 2013.
*/ | /**
* Project Praca domowa <SUF>*/
import java.util.ArrayList;
import java.util.Collections;
/**
* Class, counting cost for cutting plate.
*
* @author Michał Szczygieł <[email protected]>
*
*/
public class Plate {
/**
* Variable stores data with weights for horizontal cuts.
*/
private ArrayList<Integer> arrayX = null;
/**
* Variable stores data with weights for vertical cuts.
*/
private ArrayList<Integer> arrayY = null;
/**
* Constructor for Plate class. Automatically set arrays with values for vertical and horizontal cuts.
*
* @param arrayX
* @param arrayY
*/
public Plate(ArrayList<Integer> arrayX, ArrayList<Integer> arrayY) {
setArrayX(arrayX);
setArrayY(arrayY);
}
/**
* Method counts cost of cuts.
*
* @return cost of cuts.
*/
public String cutCost() {
// Arrays needs sort, to finding optimal cost.
Collections.sort(getArrayX());
Collections.sort(getArrayY());
int accumulator = 0;
int horizontalLines = 1;
int verticalLines = 1;
int sizeX = getArrayX().size();
int sizeY = getArrayY().size();
int numberOfIterations = sizeX + sizeY;
for (int i = 0; i < numberOfIterations; i++) {
int maxX = 0;
int maxY = 0;
if (getArrayX().size() > 0) {
maxX = Collections.max(getArrayX());
}
if (getArrayY().size() > 0) {
maxY = Collections.max(getArrayY());
}
if (maxX > maxY) {
if (getArrayX().size() > 0) {
accumulator += maxX * horizontalLines;
getArrayX().remove(sizeX - 1);
verticalLines++;
sizeX--;
}
} else {
if (getArrayY().size() > 0) {
accumulator += maxY * verticalLines;
getArrayY().remove(sizeY - 1);
horizontalLines++;
sizeY--;
}
}
}
return "Koszt cięcia : " + accumulator;
}
/**
* @return the arrayX
*/
public ArrayList<Integer> getArrayX() {
return arrayX;
}
/**
* @return the arrayY
*/
public ArrayList<Integer> getArrayY() {
return arrayY;
}
/**
* @param arrayX
* the arrayX to set
*/
public void setArrayX(ArrayList<Integer> arrayX) {
this.arrayX = arrayX;
}
/**
* @param arrayY
* the arrayY to set
*/
public void setArrayY(ArrayList<Integer> arrayY) {
this.arrayY = arrayY;
}
}
| null |
6905_0 | MaksymilianGalas/zadania_java | 134 | lab09/zad3/Main.java | package zad3;
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("C:\\Users\\makse\\IdeaProjects\\lab09\\src\\zad3\\slownik.txt"); // nie wiem dlaczego inaczej nie działa :))
Slownik<String, String> slownik = Slownik.wczytajSlownik(file);
System.out.println(slownik.toString());
}
}
| // nie wiem dlaczego inaczej nie działa :))
| package zad3;
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("C:\\Users\\makse\\IdeaProjects\\lab09\\src\\zad3\\slownik.txt"); // nie wiem <SUF>
Slownik<String, String> slownik = Slownik.wczytajSlownik(file);
System.out.println(slownik.toString());
}
}
| null |
8298_2 | MaksymilianWojcik/JavaMastering | 306 | src/JawnaInicjalizacjaStatyczna/Inicjalizacja.java | package JawnaInicjalizacjaStatyczna;
public class Inicjalizacja {
public static void main(String[] args) {
System.out.println("Inside main");
Cups.cup1.f(99); //(1)
}
//static Cups cups1 = new Cups(); //(2)
//static Cups cups2 = new Cups(); //(2)
}
/*
* Output:
* Cup(1)
* Cup(2)
* f(99)
*
* Statyczne inicjalizatory klasy Cup wykonuja sie, gdy nastapi odwolanie do statycznego
* obiektu cup1 w wierszu (1) lub jezeli wiersz ten zostanie umieszczony w komentarzu, a
* wiersze (2) odkomentowane. Jesli oba sa zakomentowane, to wiadomo - inicjalizacja
* statyczna klasy Cup nie nastapi nigdy. Gdy oba sa odkomentowane, to tak czy siak
* nie ma to znacznenia, bo inicjalizacja statyczny wystapi i tak tylko raz.
*/
| /*
* Output:
* Cup(1)
* Cup(2)
* f(99)
*
* Statyczne inicjalizatory klasy Cup wykonuja sie, gdy nastapi odwolanie do statycznego
* obiektu cup1 w wierszu (1) lub jezeli wiersz ten zostanie umieszczony w komentarzu, a
* wiersze (2) odkomentowane. Jesli oba sa zakomentowane, to wiadomo - inicjalizacja
* statyczna klasy Cup nie nastapi nigdy. Gdy oba sa odkomentowane, to tak czy siak
* nie ma to znacznenia, bo inicjalizacja statyczny wystapi i tak tylko raz.
*/ | package JawnaInicjalizacjaStatyczna;
public class Inicjalizacja {
public static void main(String[] args) {
System.out.println("Inside main");
Cups.cup1.f(99); //(1)
}
//static Cups cups1 = new Cups(); //(2)
//static Cups cups2 = new Cups(); //(2)
}
/*
* Output:
* <SUF>*/
| null |
8364_0 | MaksymilianWojcik/Mastering_RecyclerView | 4,776 | app/src/main/java/com/example/mwojcik/recyclerviewone/RecyclerViewAdapter.java | package com.example.mwojcik.recyclerviewone;
import android.support.annotation.NonNull;
import android.support.v7.recyclerview.extensions.AsyncListDiffer;
import android.support.v7.util.DiffUtil;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
/***
* RecyclerView jest to ViewGroup zastpęujący ListView i GridView dostępny w support-v7. Powinniśmy używać go kiedy tylko
* posiadamy kolekcje danych ktorej elementy mogą się zmieniać podczas runtimeu na podstawie akcji użytkownika lub eventów
* sieciowych.
*
* Zeby używać RecyclverView musimy poznać pracę z:
* - RecyclerView.Adapter - do obsługi kolekcji danych i powiązaniach ich do widoku (view).
* - LayoutManager - Pomaga pozycjonować itemy (np. horyzontalnie)
* - ItemAnimator - Pomaga z animacją itemów dla powszechnych operacji jak np. dodawanie czy odejmowanie.
*
* Przeciwnie do ListView tutaj ViewHolder jest wymagany w Adapterach. W listView adapterach nie były one wymagane, chociaż
* zwiększają perforemance. W RecyclerView są one wymagane i używamy do tego RecyclerView.Adapter.
* Co jeszcze warte uwagi, ListView mają adaptery dla rożnych źródeł danych (np. ArrayAdapter czy CursorAdapter). RecyclerView
* natomiast wymaga customowej implementacji żeby wspierać takie dane w adapterze.
*
*
* RecyclerViewAdapter
* Służy do populacji danych do RecyclerView. Jego rolą jest po prostu konwertowanie obiektu na danej pozycji do wstawienia
* w row_item. W RecyclerView adapter wymaga obiektu ViewHoldera, który opisuje i dostarcza dostęp do wszystkich widoków w każdym
* row_itemie.
*
*
* ViewHolder to taki wzorzec, w ktorym mamy obiekt który zawiera View i Dane do zrenderowania na tym View. Definiujemy
* ja zazwyczaj jako klasy prywatne wewnatrz adaptera.
*
*
* Pare uwag:
* - Nie wykonywac animacji na view wewnatrz viewholdera (np. itemView.animate(). ItemAnimator jest jedynym komponentem
* ktory moze animowac viewsy.
* - Nie uzywac notifyItemRangeChanged w ten sposob: notifyItemRangeChanged(0, getItemsCount())
* - Do zarządzania updejtami adaptera uzywac DiffUtil - obsłuży on wsyzstkie kalkulacje zmian i rozdzieli je do adaptera
* - Nigdy nie ustawiac View.OnCliCklistener wewnątrz onBindViewHodler! Zrobic osobno clicklistenra i ustawic go w konstruktorze
* viewholdera (najlepiej ustawic i odwolac sie do listenera, ale mozemy tez tam po prostu go zrobic)
* - Uzywac setHasStableIds(true) z getItemId(int position) a RecyclerView automatycznie obsłuży wszystkie animacje na prostym wywołaniu
* notifyDataSetChanged().
* Jeżeli chcemy smoothscrolling, nie możemy o tym zapomnieć:
* - mamy tylko 16ms do wykonania calej pracy/per framme
* - item layout powinien być prosty
* - unikać deep layout hierarchii
* - unikać overdraw issue,
* - nie ustawiac zbyt długich textów w TextView, bo text line wrap są ciężkimi kalkulacjami. Usatwić max lines z text i ellipsis
* - używać LayoutManager.setItemPrefetchEnabled() dla zagnieżdżonych RecyclerViews dla lepszego performancu renderingu
*
*
* LayoutManager - dołącza, mierzy/oblicza wszystkie child views RecyclerView w czasie rzeczywistym. Jak user scrolluje widok,
* to LayoutManager określa kiedy nowy child view zostanie dodany i kiedy starty child view zostanie odłączony (detached) i usunięty.
* Możemy stworzyć customowy LayoutManager rozrzeszając RecyclerView.LayoutManager lub np. inne implementacje LayoutManagera:
* LinearyLayoutManager, GridLayoutManager, StaggeredGridLayoutManager.
*
*
*
*
* RecyclerView.ItemAnimator - klasa która określa wykonywane na itemach animacje i będzie animować zmiany ViewGropud jak np.
* dodawanie, usuwanie, zaznaczenie wykonywane/inforowane na adapterze. DefaultItemAnimator jest bazową animacją dostępną
* domyślnie w RecyclerView. Żeby skustomizować DefaultItemAnimator wystarczy dodać item animator do RecyclerView:
* RecyclerView.ItemAnimator itemAnimator = new DefaultItemAnimator();
* itemAnimator.setAddDuration(1000);
* itemAnimator.setRemoveDuration(1000);
* recyclerView.setItemAnimator(itemAnimator);
* Przyklad pokazany w klasie MainActivity
* INNYM SPOSOBEM ANIMOWANIA RECYCLERVIEW ITEMOW jest wykorzystanie Androidowych Interpolatorów. Interpolator definiuje
* częśtość zmiany aniumacji. Przykład xmlowy reprezentujący dwie animacje z wykorzystaniem interpolatorów. Dodaje się je
* do res/anim/:
*
* overshoot.xml
* <?xml version="1.0" encoding="utf-8"?>
* <set xmlns:android="http://schemas.android.com/apk/res/android"
* android:interpolator="@android:anim/anticipate_overshoot_interpolator">
* <translate
* android:fromYDelta="-50%p"
* android:toYDelta="0"
* android:duration="2000"
* />
* </set>
*
* bounce.xml
*
*<set xmlns:android="http://schemas.android.com/apk/res/android"
* android:interpolator="@android:anim/bounce_interpolator">
* <translate
* android:duration="1500"
* android:fromYDelta="-150%p"
* android:toYDelta="0"
* />
* </set>
*
* A w Adapterze RecyclerView trezba dodac funkcje:
*
* public void animate(RecyclerView.ViewHolder viewHolder) {
* final Animation animAnticipateOvershoot = AnimationUtils.loadAnimation(context, R.anim.bounce_interpolator);
* viewHolder.itemView.setAnimation(animAnticipateOvershoot);
* }
*
* Te animacje co prawda męczą oczy. Metode te wywolujemy wewnatrz onBindViewHolder, bo tam powinno się to odbywać. To
* jako taka dodatkowa informacja
*
*
*
*/
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private static String TAG = "RecyclerViewAdapter";
private static String TAG_VH = "RecyclerViewAdapterVH";
List<Model> dataList;
public RecyclerViewAdapter(List<Model> dataList) {
Log.d(TAG, "constructor call");
this.dataList = dataList;
}
/***
* Inflatuje item layout i tworzy holder
*
* Wywolywane tyle razy ile mamy itemow jako pierwsza metoda, jeszcze przed wywołaniem konstruktora ViewHoldera,
* czyli przed utworzeniem takiego obiektu. Jest to jasne, bo przeciez tworzymy go wewnatrz tej metody. Wywoływane
* jest tylko wtedy, kiedy naprawdę musimy utworzyć nowy view.
*
* Inflatuje row layout i inicjalizuje ViewHolder. Jak już ViewHolder jest zainicjalizowany to zarządza ten viewholder finViewById do
* bindowania widoków i recyclowania ich by uiknąć potwarzanych wywołań
*/
@NonNull
@Override
public RecyclerViewAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
Log.d(TAG, "onCreateviewHolder call, where parent is: " + parent.getClass().getName().toString());
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view_item, parent, false);
MyViewHolder viewHolder = new MyViewHolder(view);
return viewHolder;
}
// //do selekcji itema
// int selectedPostion = RecyclerView.NO_POSITION;
/***
* Ustawia view attributes w oparciu o dane (data)
*
* Wywolywane tyle razy ile mamy itemow. Wywolywane juz po onCreateViewHolder i utworzeniu ViewHoldera, czyli także
* wywołaniu konstruktora tego ViewHodldera. Metoda wywolywana jest dla kazdego itemu.
* Wykorzystuje ViewHolder skonstruowany w onCreateViewHolder do wypełnienia danego rowa RecyclerView danymi
*/
@Override
public void onBindViewHolder(@NonNull RecyclerViewAdapter.MyViewHolder holder, int position) {
Log.d(TAG, "onBindViewHolder call for position: " + position);
Model model = dataList.get(position);
holder.titleTextView.setText(model.getTitle());
holder.descriptionTextView.setText(model.getDescription());
/***
* Możemy np. ustawić taga na dany item żeby dostać go w np. onClick listenerze, dodałem jako przykład.
* Ustawiamy to na itemView holdera, czyli dla danego row itema.
*/
holder.itemView.setTag(model);
//Do zaznaczenia wybranego itema
// holder.itemView.setSelected(selectedPostion == position);
}
/***
*
* Określa liczbę itemów
*/
@Override
public int getItemCount() {
//Log.d(TAG, "getItemCount call");
return dataList.size();
}
/***
* Customowy listener w celu dodania listenra w activity wyzej np czy fragmencie.
*/
private RecyclerViewOnItemClickListener listener;
public interface RecyclerViewOnItemClickListener {
void onItemClick(View itemView, int position);
}
public void setOnItemClickListener(RecyclerViewOnItemClickListener listener){
this.listener = listener;
}
/***
* Przyklad uzycia klasy diffUtil
*/
public void diffUtilTest(List<Model> modelList){
RecyclerViewDiffUtilCallback callback = new RecyclerViewDiffUtilCallback(this.dataList, modelList);
DiffUtil.DiffResult result = DiffUtil.calculateDiff(callback);
this.dataList.clear();
this.dataList.addAll(modelList);
result.dispatchUpdatesTo(this);
}
/***
* Przyklad uzycia klasy diffUtil do sortowania
*/
public void updateSortedList(List<Model> newList){
DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new RecyclerViewDiffUtilCallback(this.dataList, newList));
this.dataList.clear();
this.dataList.addAll(newList);
diffResult.dispatchUpdatesTo(this);
}
/***
*
*/
public void updateSortedListWithAsyncDiff(List<Model> newList){
//Kaklukacje powinny się odbywać w backgroundtHreadize i do teog wykorzystuje się
//AsyncListDIffer: https://developer.android.com/reference/android/support/v7/recyclerview/extensions/AsyncListDiffer
}
/***
* Zapewnia bezpośrednią referencje do każdego z views w itemie. Używane do cachowania widoków wewnątrz layoutu
* itema dla szybkiego dostępu.
* RecyclerView wykorzystuje ViewHolder do przechowywania referencji do odpowiednich widoków dla każdego entry w RecyclerView.
* Pozwala to uniknąć wywołań wszystkich finViewById metod w adapterze do wyszukania widoków do wypełnienia danymi.
*/
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView titleTextView;
TextView descriptionTextView;
/***
* Konstruktor akceptuje cały item row i wykonuje wyszukiwanie widoku by znalexć każdy subview
*/
public MyViewHolder(final View itemView) {
/***
* Przechowuje itemView w publicznej finalnej zmiennej która może być używana do uzyskania dostępu do kontekstu
* z dowolnegj instancji ViewHoldera
*/
super(itemView);
Log.d(TAG_VH, "constructor call");
titleTextView = (TextView) itemView.findViewById(R.id.recyclerview_item_title);
descriptionTextView = (TextView) itemView.findViewById(R.id.recyclerview_item_description);
/***
* W przeciwienstwie do ListView, recyclerView nie ma specjlanych przepisów dotyczących dołączania click handlerów
* do itemów, jak np. w ListView metoda setOnItemClickListener. Aby jednak osiągnąć podobny efekt możemy dołączyć
* click event wewnątrz ViewHoldera w adapterze. Tak to się powinno robić. Jest jeszcze przypadek że np. chcielibyśmy
* stworzyć takiego click handlera dla danego itema ale w np. activity lub w fragmncie w którym zawarty jest ten recycler view.
* W takim wypadku musimy stworzyć customowego listenera (interefjs) w adapterze i wystrzeliwać eventy do implementacji
* tego listenera (interfejsu) w danym activity / fragmencie. Jest to tu pokazane
*
* Ciekawe podejście do zrobienia właśnego itemClickListenera podobnego do tego w listview: https://www.sitepoint.com/mastering-complex-lists-with-the-android-recyclerview/
*/
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
/***
* I teraz mamy 2 sposoby na uzyskanie obiektu, albo przez pobranie pozycji itema z listy,
* albo tak jak wyżej dodałem przez taga:
*/
// Model model = dataList.get(position);
// Model model = (Model) itemView.getTag();
//Moze byc view, bo przxeciez danym view jest rownie dobrze itemview holdera - bo to ten sam row item.
Model model = (Model) view.getTag();
Toast.makeText(view.getContext(), model.getTitle() + " clicked", Toast.LENGTH_SHORT).show();
//poinformowanie customowego listenera o evencie do odebrania w MainActivity
listener.onItemClick(itemView, position);
//do zaznaczenia kliknietego itema
//najpierw informujemy o zmianie stary item, a nastepnie nowy
// notifyItemChanged(selectedPostion);
// selectedPostion = position;
// notifyItemChanged(selectedPostion);
}
}
});
}
}
}
/*
Logi z listy z 4 elementami po wystartowaniu:
D/RecyclerViewAdapter: constructor call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: onCreateviewHolder call, where parent is: android.support.v7.widget.RecyclerView
D/RecyclerViewAdapterVH: constructor call
D/RecyclerViewAdapter: onBindViewHolder call for position: 0
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: onCreateviewHolder call, where parent is: android.support.v7.widget.RecyclerView
D/RecyclerViewAdapterVH: constructor call
D/RecyclerViewAdapter: onBindViewHolder call for position: 1
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: onCreateviewHolder call, where parent is: android.support.v7.widget.RecyclerView
D/RecyclerViewAdapterVH: constructor call
D/RecyclerViewAdapter: onBindViewHolder call for position: 2
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: onCreateviewHolder call, where parent is: android.support.v7.widget.RecyclerView
D/RecyclerViewAdapterVH: constructor call
D/RecyclerViewAdapter: onBindViewHolder call for position: 3
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
Pozniej przy np. 10 itemach i przewijaniu w dol w gore wywoluje OnBindViewHodler tylko dla pozycji 0 i 10.
*/
| /***
* RecyclerView jest to ViewGroup zastpęujący ListView i GridView dostępny w support-v7. Powinniśmy używać go kiedy tylko
* posiadamy kolekcje danych ktorej elementy mogą się zmieniać podczas runtimeu na podstawie akcji użytkownika lub eventów
* sieciowych.
*
* Zeby używać RecyclverView musimy poznać pracę z:
* - RecyclerView.Adapter - do obsługi kolekcji danych i powiązaniach ich do widoku (view).
* - LayoutManager - Pomaga pozycjonować itemy (np. horyzontalnie)
* - ItemAnimator - Pomaga z animacją itemów dla powszechnych operacji jak np. dodawanie czy odejmowanie.
*
* Przeciwnie do ListView tutaj ViewHolder jest wymagany w Adapterach. W listView adapterach nie były one wymagane, chociaż
* zwiększają perforemance. W RecyclerView są one wymagane i używamy do tego RecyclerView.Adapter.
* Co jeszcze warte uwagi, ListView mają adaptery dla rożnych źródeł danych (np. ArrayAdapter czy CursorAdapter). RecyclerView
* natomiast wymaga customowej implementacji żeby wspierać takie dane w adapterze.
*
*
* RecyclerViewAdapter
* Służy do populacji danych do RecyclerView. Jego rolą jest po prostu konwertowanie obiektu na danej pozycji do wstawienia
* w row_item. W RecyclerView adapter wymaga obiektu ViewHoldera, który opisuje i dostarcza dostęp do wszystkich widoków w każdym
* row_itemie.
*
*
* ViewHolder to taki wzorzec, w ktorym mamy obiekt który zawiera View i Dane do zrenderowania na tym View. Definiujemy
* ja zazwyczaj jako klasy prywatne wewnatrz adaptera.
*
*
* Pare uwag:
* - Nie wykonywac animacji na view wewnatrz viewholdera (np. itemView.animate(). ItemAnimator jest jedynym komponentem
* ktory moze animowac viewsy.
* - Nie uzywac notifyItemRangeChanged w ten sposob: notifyItemRangeChanged(0, getItemsCount())
* - Do zarządzania updejtami adaptera uzywac DiffUtil - obsłuży on wsyzstkie kalkulacje zmian i rozdzieli je do adaptera
* - Nigdy nie ustawiac View.OnCliCklistener wewnątrz onBindViewHodler! Zrobic osobno clicklistenra i ustawic go w konstruktorze
* viewholdera (najlepiej ustawic i odwolac sie do listenera, ale mozemy tez tam po prostu go zrobic)
* - Uzywac setHasStableIds(true) z getItemId(int position) a RecyclerView automatycznie obsłuży wszystkie animacje na prostym wywołaniu
* notifyDataSetChanged().
* Jeżeli chcemy smoothscrolling, nie możemy o tym zapomnieć:
* - mamy tylko 16ms do wykonania calej pracy/per framme
* - item layout powinien być prosty
* - unikać deep layout hierarchii
* - unikać overdraw issue,
* - nie ustawiac zbyt długich textów w TextView, bo text line wrap są ciężkimi kalkulacjami. Usatwić max lines z text i ellipsis
* - używać LayoutManager.setItemPrefetchEnabled() dla zagnieżdżonych RecyclerViews dla lepszego performancu renderingu
*
*
* LayoutManager - dołącza, mierzy/oblicza wszystkie child views RecyclerView w czasie rzeczywistym. Jak user scrolluje widok,
* to LayoutManager określa kiedy nowy child view zostanie dodany i kiedy starty child view zostanie odłączony (detached) i usunięty.
* Możemy stworzyć customowy LayoutManager rozrzeszając RecyclerView.LayoutManager lub np. inne implementacje LayoutManagera:
* LinearyLayoutManager, GridLayoutManager, StaggeredGridLayoutManager.
*
*
*
*
* RecyclerView.ItemAnimator - klasa która określa wykonywane na itemach animacje i będzie animować zmiany ViewGropud jak np.
* dodawanie, usuwanie, zaznaczenie wykonywane/inforowane na adapterze. DefaultItemAnimator jest bazową animacją dostępną
* domyślnie w RecyclerView. Żeby skustomizować DefaultItemAnimator wystarczy dodać item animator do RecyclerView:
* RecyclerView.ItemAnimator itemAnimator = new DefaultItemAnimator();
* itemAnimator.setAddDuration(1000);
* itemAnimator.setRemoveDuration(1000);
* recyclerView.setItemAnimator(itemAnimator);
* Przyklad pokazany w klasie MainActivity
* INNYM SPOSOBEM ANIMOWANIA RECYCLERVIEW ITEMOW jest wykorzystanie Androidowych Interpolatorów. Interpolator definiuje
* częśtość zmiany aniumacji. Przykład xmlowy reprezentujący dwie animacje z wykorzystaniem interpolatorów. Dodaje się je
* do res/anim/:
*
* overshoot.xml
* <?xml version="1.0" encoding="utf-8"?>
* <set xmlns:android="http://schemas.android.com/apk/res/android"
* android:interpolator="@android:anim/anticipate_overshoot_interpolator">
* <translate
* android:fromYDelta="-50%p"
* android:toYDelta="0"
* android:duration="2000"
* />
* </set>
*
* bounce.xml
*
*<set xmlns:android="http://schemas.android.com/apk/res/android"
* android:interpolator="@android:anim/bounce_interpolator">
* <translate
* android:duration="1500"
* android:fromYDelta="-150%p"
* android:toYDelta="0"
* />
* </set>
*
* A w Adapterze RecyclerView trezba dodac funkcje:
*
* public void animate(RecyclerView.ViewHolder viewHolder) {
* final Animation animAnticipateOvershoot = AnimationUtils.loadAnimation(context, R.anim.bounce_interpolator);
* viewHolder.itemView.setAnimation(animAnticipateOvershoot);
* }
*
* Te animacje co prawda męczą oczy. Metode te wywolujemy wewnatrz onBindViewHolder, bo tam powinno się to odbywać. To
* jako taka dodatkowa informacja
*
*
*
*/ | package com.example.mwojcik.recyclerviewone;
import android.support.annotation.NonNull;
import android.support.v7.recyclerview.extensions.AsyncListDiffer;
import android.support.v7.util.DiffUtil;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
/***
* RecyclerView jest to <SUF>*/
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private static String TAG = "RecyclerViewAdapter";
private static String TAG_VH = "RecyclerViewAdapterVH";
List<Model> dataList;
public RecyclerViewAdapter(List<Model> dataList) {
Log.d(TAG, "constructor call");
this.dataList = dataList;
}
/***
* Inflatuje item layout i tworzy holder
*
* Wywolywane tyle razy ile mamy itemow jako pierwsza metoda, jeszcze przed wywołaniem konstruktora ViewHoldera,
* czyli przed utworzeniem takiego obiektu. Jest to jasne, bo przeciez tworzymy go wewnatrz tej metody. Wywoływane
* jest tylko wtedy, kiedy naprawdę musimy utworzyć nowy view.
*
* Inflatuje row layout i inicjalizuje ViewHolder. Jak już ViewHolder jest zainicjalizowany to zarządza ten viewholder finViewById do
* bindowania widoków i recyclowania ich by uiknąć potwarzanych wywołań
*/
@NonNull
@Override
public RecyclerViewAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
Log.d(TAG, "onCreateviewHolder call, where parent is: " + parent.getClass().getName().toString());
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view_item, parent, false);
MyViewHolder viewHolder = new MyViewHolder(view);
return viewHolder;
}
// //do selekcji itema
// int selectedPostion = RecyclerView.NO_POSITION;
/***
* Ustawia view attributes w oparciu o dane (data)
*
* Wywolywane tyle razy ile mamy itemow. Wywolywane juz po onCreateViewHolder i utworzeniu ViewHoldera, czyli także
* wywołaniu konstruktora tego ViewHodldera. Metoda wywolywana jest dla kazdego itemu.
* Wykorzystuje ViewHolder skonstruowany w onCreateViewHolder do wypełnienia danego rowa RecyclerView danymi
*/
@Override
public void onBindViewHolder(@NonNull RecyclerViewAdapter.MyViewHolder holder, int position) {
Log.d(TAG, "onBindViewHolder call for position: " + position);
Model model = dataList.get(position);
holder.titleTextView.setText(model.getTitle());
holder.descriptionTextView.setText(model.getDescription());
/***
* Możemy np. ustawić taga na dany item żeby dostać go w np. onClick listenerze, dodałem jako przykład.
* Ustawiamy to na itemView holdera, czyli dla danego row itema.
*/
holder.itemView.setTag(model);
//Do zaznaczenia wybranego itema
// holder.itemView.setSelected(selectedPostion == position);
}
/***
*
* Określa liczbę itemów
*/
@Override
public int getItemCount() {
//Log.d(TAG, "getItemCount call");
return dataList.size();
}
/***
* Customowy listener w celu dodania listenra w activity wyzej np czy fragmencie.
*/
private RecyclerViewOnItemClickListener listener;
public interface RecyclerViewOnItemClickListener {
void onItemClick(View itemView, int position);
}
public void setOnItemClickListener(RecyclerViewOnItemClickListener listener){
this.listener = listener;
}
/***
* Przyklad uzycia klasy diffUtil
*/
public void diffUtilTest(List<Model> modelList){
RecyclerViewDiffUtilCallback callback = new RecyclerViewDiffUtilCallback(this.dataList, modelList);
DiffUtil.DiffResult result = DiffUtil.calculateDiff(callback);
this.dataList.clear();
this.dataList.addAll(modelList);
result.dispatchUpdatesTo(this);
}
/***
* Przyklad uzycia klasy diffUtil do sortowania
*/
public void updateSortedList(List<Model> newList){
DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new RecyclerViewDiffUtilCallback(this.dataList, newList));
this.dataList.clear();
this.dataList.addAll(newList);
diffResult.dispatchUpdatesTo(this);
}
/***
*
*/
public void updateSortedListWithAsyncDiff(List<Model> newList){
//Kaklukacje powinny się odbywać w backgroundtHreadize i do teog wykorzystuje się
//AsyncListDIffer: https://developer.android.com/reference/android/support/v7/recyclerview/extensions/AsyncListDiffer
}
/***
* Zapewnia bezpośrednią referencje do każdego z views w itemie. Używane do cachowania widoków wewnątrz layoutu
* itema dla szybkiego dostępu.
* RecyclerView wykorzystuje ViewHolder do przechowywania referencji do odpowiednich widoków dla każdego entry w RecyclerView.
* Pozwala to uniknąć wywołań wszystkich finViewById metod w adapterze do wyszukania widoków do wypełnienia danymi.
*/
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView titleTextView;
TextView descriptionTextView;
/***
* Konstruktor akceptuje cały item row i wykonuje wyszukiwanie widoku by znalexć każdy subview
*/
public MyViewHolder(final View itemView) {
/***
* Przechowuje itemView w publicznej finalnej zmiennej która może być używana do uzyskania dostępu do kontekstu
* z dowolnegj instancji ViewHoldera
*/
super(itemView);
Log.d(TAG_VH, "constructor call");
titleTextView = (TextView) itemView.findViewById(R.id.recyclerview_item_title);
descriptionTextView = (TextView) itemView.findViewById(R.id.recyclerview_item_description);
/***
* W przeciwienstwie do ListView, recyclerView nie ma specjlanych przepisów dotyczących dołączania click handlerów
* do itemów, jak np. w ListView metoda setOnItemClickListener. Aby jednak osiągnąć podobny efekt możemy dołączyć
* click event wewnątrz ViewHoldera w adapterze. Tak to się powinno robić. Jest jeszcze przypadek że np. chcielibyśmy
* stworzyć takiego click handlera dla danego itema ale w np. activity lub w fragmncie w którym zawarty jest ten recycler view.
* W takim wypadku musimy stworzyć customowego listenera (interefjs) w adapterze i wystrzeliwać eventy do implementacji
* tego listenera (interfejsu) w danym activity / fragmencie. Jest to tu pokazane
*
* Ciekawe podejście do zrobienia właśnego itemClickListenera podobnego do tego w listview: https://www.sitepoint.com/mastering-complex-lists-with-the-android-recyclerview/
*/
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
/***
* I teraz mamy 2 sposoby na uzyskanie obiektu, albo przez pobranie pozycji itema z listy,
* albo tak jak wyżej dodałem przez taga:
*/
// Model model = dataList.get(position);
// Model model = (Model) itemView.getTag();
//Moze byc view, bo przxeciez danym view jest rownie dobrze itemview holdera - bo to ten sam row item.
Model model = (Model) view.getTag();
Toast.makeText(view.getContext(), model.getTitle() + " clicked", Toast.LENGTH_SHORT).show();
//poinformowanie customowego listenera o evencie do odebrania w MainActivity
listener.onItemClick(itemView, position);
//do zaznaczenia kliknietego itema
//najpierw informujemy o zmianie stary item, a nastepnie nowy
// notifyItemChanged(selectedPostion);
// selectedPostion = position;
// notifyItemChanged(selectedPostion);
}
}
});
}
}
}
/*
Logi z listy z 4 elementami po wystartowaniu:
D/RecyclerViewAdapter: constructor call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: onCreateviewHolder call, where parent is: android.support.v7.widget.RecyclerView
D/RecyclerViewAdapterVH: constructor call
D/RecyclerViewAdapter: onBindViewHolder call for position: 0
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: onCreateviewHolder call, where parent is: android.support.v7.widget.RecyclerView
D/RecyclerViewAdapterVH: constructor call
D/RecyclerViewAdapter: onBindViewHolder call for position: 1
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: onCreateviewHolder call, where parent is: android.support.v7.widget.RecyclerView
D/RecyclerViewAdapterVH: constructor call
D/RecyclerViewAdapter: onBindViewHolder call for position: 2
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: onCreateviewHolder call, where parent is: android.support.v7.widget.RecyclerView
D/RecyclerViewAdapterVH: constructor call
D/RecyclerViewAdapter: onBindViewHolder call for position: 3
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
D/RecyclerViewAdapter: getItemCount call
Pozniej przy np. 10 itemach i przewijaniu w dol w gore wywoluje OnBindViewHodler tylko dla pozycji 0 i 10.
*/
| null |
6900_0 | Malgosia-web/Malgorzata_Stolarczyk-kodilla_tester | 200 | kodilla-collections-advanced/src/main/java/com/kodilla/collections/adv/maps/homework/School.java | package com.kodilla.collections.adv.maps.homework;
import java.util.ArrayList;
import java.util.List;
public class School {
private List<Integer> school = new ArrayList<>(); // nie wiem dlaczego to nie działa
private int number;
public School(List<Integer> school, int number) {
this.school = school;
this.number = number;
}
public int totalKids(){
int sum = 0;
for (int group : school)
sum += group;
return sum;
}
public int getNumber() {
return number;
}
@Override
public String toString() {
return "School{" +
"school=" + school +
'}';
}
}
| // nie wiem dlaczego to nie działa | package com.kodilla.collections.adv.maps.homework;
import java.util.ArrayList;
import java.util.List;
public class School {
private List<Integer> school = new ArrayList<>(); // nie wiem <SUF>
private int number;
public School(List<Integer> school, int number) {
this.school = school;
this.number = number;
}
public int totalKids(){
int sum = 0;
for (int group : school)
sum += group;
return sum;
}
public int getNumber() {
return number;
}
@Override
public String toString() {
return "School{" +
"school=" + school +
'}';
}
}
| null |
4060_0 | Marchuck/Louis | 749 | app/src/main/java/pl/kitowcy/louis/proposition/PropositionItemsProvider.java | package pl.kitowcy.louis.proposition;
import java.util.ArrayList;
import java.util.List;
import pl.kitowcy.louis.R;
/**
* Created by Patryk Mieczkowski on 29.10.2016
*/
public class PropositionItemsProvider {
public static List<PropItem> getItems() {
List<PropItem> propItemList = new ArrayList<>();
propItemList.add(getBeksinski());
propItemList.add(getJazzFestiwal());
propItemList.add(getRolki());
propItemList.add(getMovie());
propItemList.add(getBeksinski());
propItemList.add(getJazzFestiwal());
propItemList.add(getRolki());
propItemList.add(getMovie());
propItemList.add(getBeksinski());
propItemList.add(getJazzFestiwal());
propItemList.add(getRolki());
propItemList.add(getMovie());
return propItemList;
}
private static PropItem getBeksinski() {
return new PropItem("Zdzisław Beksiński Gallery",
"Obrazy, rysunki i fotografie - łącznie 250 prac z prywatnej kolekcji. " +
"Beksiński należy do wąskiego grona polskich artystów, których twórczość jest " +
"tak dobrze rozpoznawalna zarówno w Polsce, jak i w Europie. Rodzące wiele emocji i kontrowersji " +
"dzieła Artysty nikogo nie pozostawiają obojętnym.",
"10.00 - 22.00",
"NCK\nal. Jana Pawła II 232",
R.drawable.beksinski);
}
private static PropItem getJazzFestiwal() {
return new PropItem("11th Krakow Jazz Autumn",
"Jazz concert features France’s duo of double bassist Joelle Leandre and trumpeter Jean-Luc Cappozzo.",
"20.00",
"Alchemia\nul. Estery 5",
R.drawable.jazz);
}
private static PropItem getMovie() {
return new PropItem("Cinema City - Doctor Strange",
" A former neurosurgeon embarks on a journey of healing only to be drawn into the world of the mystic arts.",
"21.15",
"Cinema City Bonarka",
R.drawable.doctorstrange);
}
private static PropItem getRolki() {
return new PropItem("Night rollerblading",
"Best way to spend active night at beautiful city",
"",
"",
R.drawable.krakownoca);
}
}
| /**
* Created by Patryk Mieczkowski on 29.10.2016
*/ | package pl.kitowcy.louis.proposition;
import java.util.ArrayList;
import java.util.List;
import pl.kitowcy.louis.R;
/**
* Created by Patryk <SUF>*/
public class PropositionItemsProvider {
public static List<PropItem> getItems() {
List<PropItem> propItemList = new ArrayList<>();
propItemList.add(getBeksinski());
propItemList.add(getJazzFestiwal());
propItemList.add(getRolki());
propItemList.add(getMovie());
propItemList.add(getBeksinski());
propItemList.add(getJazzFestiwal());
propItemList.add(getRolki());
propItemList.add(getMovie());
propItemList.add(getBeksinski());
propItemList.add(getJazzFestiwal());
propItemList.add(getRolki());
propItemList.add(getMovie());
return propItemList;
}
private static PropItem getBeksinski() {
return new PropItem("Zdzisław Beksiński Gallery",
"Obrazy, rysunki i fotografie - łącznie 250 prac z prywatnej kolekcji. " +
"Beksiński należy do wąskiego grona polskich artystów, których twórczość jest " +
"tak dobrze rozpoznawalna zarówno w Polsce, jak i w Europie. Rodzące wiele emocji i kontrowersji " +
"dzieła Artysty nikogo nie pozostawiają obojętnym.",
"10.00 - 22.00",
"NCK\nal. Jana Pawła II 232",
R.drawable.beksinski);
}
private static PropItem getJazzFestiwal() {
return new PropItem("11th Krakow Jazz Autumn",
"Jazz concert features France’s duo of double bassist Joelle Leandre and trumpeter Jean-Luc Cappozzo.",
"20.00",
"Alchemia\nul. Estery 5",
R.drawable.jazz);
}
private static PropItem getMovie() {
return new PropItem("Cinema City - Doctor Strange",
" A former neurosurgeon embarks on a journey of healing only to be drawn into the world of the mystic arts.",
"21.15",
"Cinema City Bonarka",
R.drawable.doctorstrange);
}
private static PropItem getRolki() {
return new PropItem("Night rollerblading",
"Best way to spend active night at beautiful city",
"",
"",
R.drawable.krakownoca);
}
}
| null |
9120_0 | MartaWu87/ArraysOfProducts | 653 | src/main/java/io/_10a/MigrationBean.java | package io._10a;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.sql.DataSource;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.MigrationInfo;
import org.flywaydb.core.api.configuration.FluentConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
@Startup
@TransactionManagement(TransactionManagementType.BEAN)
public class MigrationBean {
protected Logger log = LoggerFactory.getLogger(getClass());
@PersistenceContext
private EntityManager entityManager;
@PostConstruct
public void init() {
long timestamp = System.nanoTime();
log.info("Flyway migration is started: {}", timestamp);
Map<String, Object> properties = entityManager.getEntityManagerFactory().getProperties();
Object datasourceObject = properties.get("hibernate.connection.datasource");
if (!(datasourceObject instanceof DataSource)) {
log.error("Cannot get datasource, {}", datasourceObject);
return;
}
DataSource dataSource = (DataSource) datasourceObject;
Flyway flyway = new Flyway(
new FluentConfiguration()
.table("_FLYWAY")
.outOfOrder(true)
.ignoreMissingMigrations(true)
.dataSource(dataSource)
.locations("classpath:db.Migration") //Pamiętaj, że pliki w locations muszę mieć dwa _ _ (podkreślniki)
// .outOfOrder(true)
// .ignoreMissingMigrations(true)
);
MigrationInfo migrationInfo = flyway.info().current();
if (migrationInfo == null) {
log.info("There is no existing database at actual datasource.");
} else {
log.info("Found the database with the version: {}", migrationInfo.getVersion() + " : "
+ migrationInfo.getDescription());
}
flyway.migrate();
log.info("Successfully migrated to the database version: {}", flyway.info().current().getVersion());
log.info("Migration finished in: {} us", (System.nanoTime() - timestamp) / 1000);
}
}
| //Pamiętaj, że pliki w locations muszę mieć dwa _ _ (podkreślniki) | package io._10a;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.sql.DataSource;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.MigrationInfo;
import org.flywaydb.core.api.configuration.FluentConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
@Startup
@TransactionManagement(TransactionManagementType.BEAN)
public class MigrationBean {
protected Logger log = LoggerFactory.getLogger(getClass());
@PersistenceContext
private EntityManager entityManager;
@PostConstruct
public void init() {
long timestamp = System.nanoTime();
log.info("Flyway migration is started: {}", timestamp);
Map<String, Object> properties = entityManager.getEntityManagerFactory().getProperties();
Object datasourceObject = properties.get("hibernate.connection.datasource");
if (!(datasourceObject instanceof DataSource)) {
log.error("Cannot get datasource, {}", datasourceObject);
return;
}
DataSource dataSource = (DataSource) datasourceObject;
Flyway flyway = new Flyway(
new FluentConfiguration()
.table("_FLYWAY")
.outOfOrder(true)
.ignoreMissingMigrations(true)
.dataSource(dataSource)
.locations("classpath:db.Migration") //Pamiętaj, że <SUF>
// .outOfOrder(true)
// .ignoreMissingMigrations(true)
);
MigrationInfo migrationInfo = flyway.info().current();
if (migrationInfo == null) {
log.info("There is no existing database at actual datasource.");
} else {
log.info("Found the database with the version: {}", migrationInfo.getVersion() + " : "
+ migrationInfo.getDescription());
}
flyway.migrate();
log.info("Successfully migrated to the database version: {}", flyway.info().current().getVersion());
log.info("Migration finished in: {} us", (System.nanoTime() - timestamp) / 1000);
}
}
| null |
3783_1 | MatPiw/TAS-Serwis-aukcyjny | 235 | JavaAPI/src/main/java/pl/edu/amu/rest/database/CommentDatabase.java | package pl.edu.amu.rest.database;
import pl.edu.amu.rest.model.Comment;
import java.util.Collection;
/**
* Created by Altenfrost on 2015-12-31.
*/
public interface CommentDatabase {
Comment getComment(String commentId);
Collection<Comment> getCommentsByUser(String userId);
Collection<Comment> getCommentsWithFilters(String giverId, String receiverId, String offerId);
Comment updateComment(String commentId, Comment comment);
Comment saveComment(Comment comment);
Boolean deleteComment(String commentId);
Boolean deleteCommentsFromAuction(String offerId);
Boolean deleteCommentsFromUser(String userId);//nie wiem, czy potrzebne. On jest od usuwania komentarzy tego usera, zarówno tych przez niego otrzymanych jak i danych
}
| //nie wiem, czy potrzebne. On jest od usuwania komentarzy tego usera, zarówno tych przez niego otrzymanych jak i danych | package pl.edu.amu.rest.database;
import pl.edu.amu.rest.model.Comment;
import java.util.Collection;
/**
* Created by Altenfrost on 2015-12-31.
*/
public interface CommentDatabase {
Comment getComment(String commentId);
Collection<Comment> getCommentsByUser(String userId);
Collection<Comment> getCommentsWithFilters(String giverId, String receiverId, String offerId);
Comment updateComment(String commentId, Comment comment);
Comment saveComment(Comment comment);
Boolean deleteComment(String commentId);
Boolean deleteCommentsFromAuction(String offerId);
Boolean deleteCommentsFromUser(String userId);//nie wiem, <SUF>
}
| null |
3724_1 | MatWich/TechnikiAgentowe | 315 | lab3/src/main/java/Klasa7.java | import jade.core.behaviours.Behaviour;
public class Klasa7 extends Klasa4 {
// Tak wiem dało sie ładniej to zrobić ale nie chciało mi się
// Klasa dodaje Beha po czym ten Beh jedno krokowy dodaje kolejnego Beha po czym kończy sie zabawa
@Override
protected void setup() {
super.setup();
addBehaviour(new Behaviour() {
private int step = 0;
@Override
public void action() {
if (step == 0) {
System.out.println("Pierwsze");
step++;
myAgent.addBehaviour(new Behaviour() {
private int step = 0;
@Override
public void action() {
if (step == 0) {
step++;
System.out.println("Drugie");
}
}
@Override
public boolean done() {
return step == 1;
}
});
}
}
@Override
public boolean done() {
return step == 1;
}
});
}
}
| // Klasa dodaje Beha po czym ten Beh jedno krokowy dodaje kolejnego Beha po czym kończy sie zabawa | import jade.core.behaviours.Behaviour;
public class Klasa7 extends Klasa4 {
// Tak wiem dało sie ładniej to zrobić ale nie chciało mi się
// Klasa dodaje <SUF>
@Override
protected void setup() {
super.setup();
addBehaviour(new Behaviour() {
private int step = 0;
@Override
public void action() {
if (step == 0) {
System.out.println("Pierwsze");
step++;
myAgent.addBehaviour(new Behaviour() {
private int step = 0;
@Override
public void action() {
if (step == 0) {
step++;
System.out.println("Drugie");
}
}
@Override
public boolean done() {
return step == 1;
}
});
}
}
@Override
public boolean done() {
return step == 1;
}
});
}
}
| null |
6873_4 | MateuszBrzozowski/DiscordBot | 5,506 | src/main/java/pl/mbrzozowski/ranger/response/EmbedInfo.java | package pl.mbrzozowski.ranger.response;
import lombok.extern.slf4j.Slf4j;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel;
import net.dv8tion.jda.api.entities.emoji.Emoji;
import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.exceptions.ErrorHandler;
import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.buttons.Button;
import net.dv8tion.jda.api.requests.ErrorResponse;
import org.jetbrains.annotations.NotNull;
import pl.mbrzozowski.ranger.DiscordBot;
import pl.mbrzozowski.ranger.event.Event;
import pl.mbrzozowski.ranger.event.EventChanges;
import pl.mbrzozowski.ranger.guild.ComponentId;
import pl.mbrzozowski.ranger.guild.RangersGuild;
import pl.mbrzozowski.ranger.helpers.RoleID;
import pl.mbrzozowski.ranger.helpers.Users;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
@Slf4j
public class EmbedInfo extends EmbedCreator {
public static void recruiter(@NotNull MessageReceivedEvent event) {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.DEFAULT);
builder.setDescription("# Podanie\n" +
"Chcemy nasze wieloletnie doświadczenie przekazać kolejnym Rangersom. Nasza gra opiera się na wzajemnej komunikacji i skoordynowanym działaniu. " +
"Jako grupa, pielęgnujemy dobrą atmosferę i przyjazne, dojrzałe relacje między członkami naszego klanu, a także polską społecznością.");
builder.addField("Złóż podanie do klanu klikając przycisk PONIŻEJ", "", false);
builder.addField("Wymagamy", """
- podstawowa znajomość zasad rozgrywki w Squad
- gra zespołowa (używamy TeamSpeak 3)
- kultura osobista
- duża ilość wolnego czasu
- brak VAC bana w ciągu 2 ostatnich lat""", false);
event.getChannel().sendMessageEmbeds(builder.build())
.setComponents(ActionRow.of(Button.success(ComponentId.NEW_RECRUIT, "Podanie")))
.queue();
}
/**
* Sends information about closed channel
*
* @param signature user who closing channel
* @param channel channel which is closing
*/
public static void closeServerServiceChannel(String signature, @NotNull MessageChannel channel) {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.INF_CONFIRM);
builder.setTitle("Kanał zamknięty");
builder.setDescription("Kanał zamknięty przez " + signature + ".");
channel.sendMessageEmbeds(builder.build())
.setComponents(ActionRow.of(getButtons(signature)))
.queue();
}
@NotNull
private static List<Button> getButtons(@NotNull String signature) {
List<Button> buttons = new ArrayList<>();
buttons.add(Button.danger(ComponentId.REMOVE_SERVER_SERVICE_CHANNEL, "Usuń kanał"));
if (signature.equalsIgnoreCase("Ranger - brak aktywności")) {
buttons.add(Button.success(ComponentId.SERVER_SERVICE_OPEN_NO_CLOSE, "Otwórz i nie zamykaj automatycznie"));
}
return buttons;
}
public static void confirmCloseChannel(@NotNull ButtonInteractionEvent event) {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.QUESTION);
builder.setTitle("Do you want close the ticket?");
event.reply("")
.setEmbeds(builder.build())
.setActionRow(Button.success(ComponentId.CLOSE_YES, "Yes"),
Button.danger(ComponentId.CLOSE_NO, "No"))
.queue();
}
public static void confirmRemoveChannel(@NotNull TextChannel channel) {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.QUESTION);
builder.setTitle("Potwierdź czy chcesz usunąć kanał?");
channel.sendMessageEmbeds(builder.build())
.setActionRow(Button.success(ComponentId.REMOVE_YES, "Tak"),
Button.danger(ComponentId.REMOVE_NO, "Nie"))
.queue();
}
/**
* Wyświetla informację że kanał został usunięty i że za chwilę zniknie.
*
* @param event Button interaction
*/
public static void removedChannel(@NotNull ButtonInteractionEvent event) {
event.reply("Kanał wkrótce zostanie usunięty.").setEphemeral(true).queue();
}
public static void endNegative(String drillId, String recruitId, @NotNull TextChannel channel) {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.INF_RED);
builder.setTitle(EmbedSettings.RESULT + "NEGATYWNY");
builder.setDescription("Rekrutacja zostaje zakończona z wynikiem NEGATYWNYM!");
builder.setThumbnail(EmbedSettings.THUMBNAIL);
builder.setFooter("Podpis: " + Users.getUserNicknameFromID(drillId));
channel.sendMessage("<@" + recruitId + ">").setEmbeds(builder.build()).queue();
JDA jda = DiscordBot.getJda();
jda.openPrivateChannelById(recruitId).queue(privateChannel -> {
builder.setDescription("Rekrutacja do klanu Rangers Polska zostaje zakończona z wynikiem NEGATYWNYM!");
privateChannel.sendMessageEmbeds(builder.build()).queue((s) -> log.info("Private message send"),
new ErrorHandler().handle(ErrorResponse.CANNOT_SEND_TO_USER,
(ex) -> log.info("Cannot send messages to this user in private channel")));
});
}
public static void endPositive(String drillId, String recruitId, @NotNull TextChannel channel) {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.INF_CONFIRM);
builder.setTitle(EmbedSettings.RESULT + "POZYTYWNY");
builder.setDescription("Rekrutacja zostaje zakończona z wynikiem POZYTYWNYM!");
builder.setThumbnail(EmbedSettings.THUMBNAIL);
builder.setFooter("Podpis: " + Users.getUserNicknameFromID(drillId));
channel.sendMessage("Gratulacje <@" + recruitId + ">").setEmbeds(builder.build()).queue();
}
/**
* Jeżeli użytkownik nie jest botem usuwa wiadomość i wysyła informację że kanał służy do logowania i tam nie piszemy.
*
* @param event Wydarzenie napisania wiadomości na kanale tekstowym.
*/
public static void noWriteOnLoggerChannel(@NotNull MessageReceivedEvent event) {
if (!event.getAuthor().isBot()) {
event.getMessage().delete().submit();
User userById = DiscordBot.getJda().getUserById(event.getAuthor().getId());
if (userById != null) {
userById.openPrivateChannel().queue(privateChannel -> {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.WARNING);
builder.setTitle("Zachowajmy porządek!");
builder.setDescription("Panie administratorze! Zachowajmy czystość na kanale do loggowania. Proszę nie wtrącać się w moje wypociny.");
builder.setFooter(getFooter());
privateChannel.sendMessageEmbeds(builder.build()).queue();
});
}
}
}
/**
* Wysyła informację że pomyślnie wyłączono przypomnienia dla eventów.
*
* @param userID ID użytkownika
*/
public static void reminderOff(String userID) {
User userById = DiscordBot.getJda().getUserById(userID);
if (userById != null) {
userById.openPrivateChannel().queue(privateChannel -> {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.INF_CONFIRM);
builder.setTitle("Przypomnienia wyłączone.");
builder.setDescription("Aby włączyć ponownie przypomnienia użyj komendy **!reminder On**");
privateChannel.sendMessageEmbeds(builder.build()).queue();
});
}
}
/**
* Wysyła informację że pomyślnie włączono przypomnienia dla eventów.
*
* @param userID ID użytkownika
*/
public static void reminderOn(String userID) {
User userById = DiscordBot.getJda().getUserById(userID);
if (userById != null) {
userById.openPrivateChannel().queue(privateChannel -> {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.INF_CONFIRM);
builder.setTitle("Przypomnienia włączone.");
builder.setFooter("Więcej informacji i ustawień powiadomień pod komendą !help Reminder");
privateChannel.sendMessageEmbeds(builder.build()).queue();
});
}
}
/**
* Wysyła do użytkownika o ID userID wiadomość o zmianach w evencie.
*
* @param userID ID użytkownika
* @param whatChange jaka zmiana zostala wykonana
* @param dateTime data i czas
*/
public static void sendInfoChanges(String userID, Event event, @NotNull EventChanges whatChange, String dateTime) {
String description = "";
if (whatChange.equals(EventChanges.CHANGES)) {
description = "Zmieniona data lub czas wydarzenia na które się zapisałeś.";
} else if (whatChange.equals(EventChanges.REMOVE)) {
description = "Wydarzenie zostaje odwołane.";
}
String link = "[" + event.getName() + "](" + RangersGuild.getLinkToMessage(event.getChannelId(), event.getMsgId()) + ")";
User userById = DiscordBot.getJda().getUserById(userID);
String finalDescription = description + " Sprawdź szczegóły!";
if (userById != null) {
userById.openPrivateChannel().queue(privateChannel -> {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.INF_RED);
builder.setThumbnail(EmbedSettings.THUMBNAIL);
builder.setTitle("**UWAGA:** Zmiany w wydarzeniu.");
builder.setDescription(finalDescription);
builder.addField("Szczegóły eventu", link + "\n:date: " + dateTime, false);
privateChannel.sendMessageEmbeds(builder.build()).queue();
log.info("USER: {} - wysłałem powiadomienie", userID);
});
}
}
public static void seedersRoleJoining(@NotNull TextChannel channel) {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.INF_CONFIRM);
builder.setTitle("SQUAD SERVER SEEDER");
builder.addField("", "Jeśli chcesz pomóc nam w rozkręcaniu naszego serwera. Możesz przypisać sobię rolę klikając w poniższy przycisk by otrzymywać ping.", false);
builder.addField("", "If you would like to help us seed our server you can add role below to receive a ping.", false);
builder.setThumbnail(EmbedSettings.THUMBNAIL);
channel.sendMessageEmbeds(builder.build()).setActionRow(Button.success(ComponentId.SEED_ROLE, "Add/Remove Seed Role ").withEmoji(Emoji.fromUnicode("\uD83C\uDF31"))).queue();
}
/**
* Formatka z opisem jak stworzyć ticket.
*
* @param channel Kanał na którym wstawiana jest formatka.
*/
public static void serverService(@NotNull MessageChannel channel) {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.DEFAULT);
builder.setTitle("Rangers Polska Servers - Create Ticket :ticket:");
builder.addField("", "Jeśli potrzebujesz pomocy admina naszych serwerów, " +
"kliknij w odpowiedni przycisk poniżej.", false);
builder.addField("--------------------", "If you need help of Rangers Polska Servers Admins, " +
"please react with the correct button below.", false);
channel.sendMessageEmbeds(builder.build()).setActionRow(
Button.primary(ComponentId.SERVER_SERVICE_REPORT, "Report Player").withEmoji(Emoji.fromUnicode(EmbedSettings.BOOK_RED)),
Button.primary(ComponentId.SERVER_SERVICE_UNBAN, "Unban appeal").withEmoji(Emoji.fromUnicode(EmbedSettings.BOOK_BLUE)),
Button.primary(ComponentId.SERVER_SERVICE_CONTACT, "Contact With Admin").withEmoji(Emoji.fromUnicode(EmbedSettings.BOOK_GREEN))).queue();
}
/**
* Wysyła powitalną formatkę z opisem do czego dany kanał służy i co należy zrobić.
*
* @param userID pinguje usera z tym ID
* @param channel Kanał na którym wysyłana jest wiadomość
*/
public static void sendEmbedReport(String userID, @NotNull TextChannel channel) {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.WARNING);
builder.setTitle("Report player");
builder.addField("", """
Zgłoś gracza według poniższego formularza.
1. Podaj nick.
2. Opisz sytuację i podaj powód dlaczego zgłaszasz gracza.
3. Podaj nazwę serwera.
4. Dodaj dowody. Screenshot lub podaj link do wideo (np. Youtube).""", false);
builder.addField("--------------------", """
Report player according to the form below.
1. Player nick.
2. Describe of bad behaviour.
3. Server name.
4. Add evidence. Screenshot or video link (e.g. Youtube).""", false);
channel.sendMessage("<@" + userID + ">, " + "<@&" + RoleID.SERVER_ADMIN + ">")
.setEmbeds(builder.build())
.setActionRow(Button.primary(ComponentId.CLOSE, "Close ticket").withEmoji(Emoji.fromUnicode(EmbedSettings.LOCK)))
.queue(message -> message.pin().queue());
}
/**
* Wysyła powitalną formatkę z opisem do czego dany kanał służy i co należy zrobić.
*
* @param userID pinguje usera z tym ID
* @param channel Kanał na którym wysyłana jest wiadomość
*/
public static void sendEmbedUnban(String userID, @NotNull TextChannel channel) {
EmbedBuilder builder = getEmbedBuilder(Color.BLUE, ThumbnailType.DEFAULT);
builder.setTitle("Unban player");
builder.addField("", """
Napisz tutaj jeżeli chcesz odowłać swój ban.
1. Podaj swój nick i/lub steamid.
2. Podaj nazwę serwera.""", false);
builder.addField("--------------------", """
Write here if you want to revoke your ban.
1. Provide your ingame nick and/or steamid.
2. Server name.""", false);
channel.sendMessage("<@" + userID + ">, " + "<@&" + RoleID.SERVER_ADMIN + ">")
.setEmbeds(builder.build())
.setActionRow(Button.primary(ComponentId.CLOSE, "Close ticket").withEmoji(Emoji.fromUnicode(EmbedSettings.LOCK)))
.queue(message -> message.pin().queue());
}
/**
* Wysyła powitalną formatkę z opisem do czego dany kanał służy i co należy zrobić.
*
* @param userID pinguje usera z tym ID
* @param channel Kanał na którym wysyłana jest wiadomość
*/
public static void sendEmbedContact(String userID, @NotNull TextChannel channel) {
EmbedBuilder builder = getEmbedBuilder(Color.GREEN, ThumbnailType.DEFAULT);
builder.setTitle("Contact with Admin");
builder.addField("", "Napisz tutaj jeżeli masz jakiś problem z którymś z naszych serwerów, dodaj screenshoty, nazwę serwera. " +
"Twój nick w grze lub/i steamId64.", false);
builder.addField("--------------------", "Please describe your problem with more details, " +
"screenshots, servername the issue occured on and related steamId64", false);
channel.sendMessage("<@" + userID + ">, " + "<@&" + RoleID.SERVER_ADMIN + ">")
.setEmbeds(builder.build())
.setActionRow(Button.primary(ComponentId.CLOSE, "Close ticket").withEmoji(Emoji.fromUnicode(EmbedSettings.LOCK)))
.queue(message -> message.pin().queue());
}
public static void recruitAnonymousComplaintsFormOpening(@NotNull TextChannel textChannel) {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.INF_CONFIRM);
builder.setTitle("Anonimowe zgłoszenia");
builder.addField("Zgłoś anonimowo sytuację używając przycisku poniżej", "", false);
textChannel
.sendMessageEmbeds(builder.build())
.setActionRow(Button.primary(ComponentId.OPEN_FORM_ANONYMOUS_COMPLAINTS, "Formularz"))
.queue();
}
public static void recruitAccepted(String userName, @NotNull TextChannel textChannel) {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.INF_BLUE);
builder.setTitle("Rozpoczęto rekrutację");
builder.setDescription("Od tego momentu rozpoczyna się Twój okres rekrutacyjny pod okiem wszystkich członków klanu.");
builder.setFooter("Podpis: " + userName);
textChannel.sendMessageEmbeds(builder.build()).queue();
}
public static void recruitNotAccepted(String userName, @NotNull TextChannel textChannel) {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.INF_RED);
builder.setTitle("Podanie odrzucone");
builder.setFooter("Podpis: " + userName);
textChannel.sendMessageEmbeds(builder.build()).queue();
}
public static void warningMaxRecruits() {
TextChannel textChannel = RangersGuild.getTextChannel(RangersGuild.ChannelsId.DRILL_INSTRUCTOR_HQ);
if (textChannel != null) {
textChannel.sendMessage("**Brak wolnych miejsc. Rekrutacja zamknięta.**\nOsiągnięto maksymalną ilość kanałów w kategorii.").queue();
}
}
public static void warningFewSlots() {
TextChannel textChannel = RangersGuild.getTextChannel(RangersGuild.ChannelsId.DRILL_INSTRUCTOR_HQ);
if (textChannel != null) {
textChannel.sendMessage("**Pozostały 2 lub mniej miejsc dla rekrutów.**").queue();
}
}
}
| /**
* Wysyła informację że pomyślnie włączono przypomnienia dla eventów.
*
* @param userID ID użytkownika
*/ | package pl.mbrzozowski.ranger.response;
import lombok.extern.slf4j.Slf4j;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel;
import net.dv8tion.jda.api.entities.emoji.Emoji;
import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.exceptions.ErrorHandler;
import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.buttons.Button;
import net.dv8tion.jda.api.requests.ErrorResponse;
import org.jetbrains.annotations.NotNull;
import pl.mbrzozowski.ranger.DiscordBot;
import pl.mbrzozowski.ranger.event.Event;
import pl.mbrzozowski.ranger.event.EventChanges;
import pl.mbrzozowski.ranger.guild.ComponentId;
import pl.mbrzozowski.ranger.guild.RangersGuild;
import pl.mbrzozowski.ranger.helpers.RoleID;
import pl.mbrzozowski.ranger.helpers.Users;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
@Slf4j
public class EmbedInfo extends EmbedCreator {
public static void recruiter(@NotNull MessageReceivedEvent event) {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.DEFAULT);
builder.setDescription("# Podanie\n" +
"Chcemy nasze wieloletnie doświadczenie przekazać kolejnym Rangersom. Nasza gra opiera się na wzajemnej komunikacji i skoordynowanym działaniu. " +
"Jako grupa, pielęgnujemy dobrą atmosferę i przyjazne, dojrzałe relacje między członkami naszego klanu, a także polską społecznością.");
builder.addField("Złóż podanie do klanu klikając przycisk PONIŻEJ", "", false);
builder.addField("Wymagamy", """
- podstawowa znajomość zasad rozgrywki w Squad
- gra zespołowa (używamy TeamSpeak 3)
- kultura osobista
- duża ilość wolnego czasu
- brak VAC bana w ciągu 2 ostatnich lat""", false);
event.getChannel().sendMessageEmbeds(builder.build())
.setComponents(ActionRow.of(Button.success(ComponentId.NEW_RECRUIT, "Podanie")))
.queue();
}
/**
* Sends information about closed channel
*
* @param signature user who closing channel
* @param channel channel which is closing
*/
public static void closeServerServiceChannel(String signature, @NotNull MessageChannel channel) {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.INF_CONFIRM);
builder.setTitle("Kanał zamknięty");
builder.setDescription("Kanał zamknięty przez " + signature + ".");
channel.sendMessageEmbeds(builder.build())
.setComponents(ActionRow.of(getButtons(signature)))
.queue();
}
@NotNull
private static List<Button> getButtons(@NotNull String signature) {
List<Button> buttons = new ArrayList<>();
buttons.add(Button.danger(ComponentId.REMOVE_SERVER_SERVICE_CHANNEL, "Usuń kanał"));
if (signature.equalsIgnoreCase("Ranger - brak aktywności")) {
buttons.add(Button.success(ComponentId.SERVER_SERVICE_OPEN_NO_CLOSE, "Otwórz i nie zamykaj automatycznie"));
}
return buttons;
}
public static void confirmCloseChannel(@NotNull ButtonInteractionEvent event) {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.QUESTION);
builder.setTitle("Do you want close the ticket?");
event.reply("")
.setEmbeds(builder.build())
.setActionRow(Button.success(ComponentId.CLOSE_YES, "Yes"),
Button.danger(ComponentId.CLOSE_NO, "No"))
.queue();
}
public static void confirmRemoveChannel(@NotNull TextChannel channel) {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.QUESTION);
builder.setTitle("Potwierdź czy chcesz usunąć kanał?");
channel.sendMessageEmbeds(builder.build())
.setActionRow(Button.success(ComponentId.REMOVE_YES, "Tak"),
Button.danger(ComponentId.REMOVE_NO, "Nie"))
.queue();
}
/**
* Wyświetla informację że kanał został usunięty i że za chwilę zniknie.
*
* @param event Button interaction
*/
public static void removedChannel(@NotNull ButtonInteractionEvent event) {
event.reply("Kanał wkrótce zostanie usunięty.").setEphemeral(true).queue();
}
public static void endNegative(String drillId, String recruitId, @NotNull TextChannel channel) {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.INF_RED);
builder.setTitle(EmbedSettings.RESULT + "NEGATYWNY");
builder.setDescription("Rekrutacja zostaje zakończona z wynikiem NEGATYWNYM!");
builder.setThumbnail(EmbedSettings.THUMBNAIL);
builder.setFooter("Podpis: " + Users.getUserNicknameFromID(drillId));
channel.sendMessage("<@" + recruitId + ">").setEmbeds(builder.build()).queue();
JDA jda = DiscordBot.getJda();
jda.openPrivateChannelById(recruitId).queue(privateChannel -> {
builder.setDescription("Rekrutacja do klanu Rangers Polska zostaje zakończona z wynikiem NEGATYWNYM!");
privateChannel.sendMessageEmbeds(builder.build()).queue((s) -> log.info("Private message send"),
new ErrorHandler().handle(ErrorResponse.CANNOT_SEND_TO_USER,
(ex) -> log.info("Cannot send messages to this user in private channel")));
});
}
public static void endPositive(String drillId, String recruitId, @NotNull TextChannel channel) {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.INF_CONFIRM);
builder.setTitle(EmbedSettings.RESULT + "POZYTYWNY");
builder.setDescription("Rekrutacja zostaje zakończona z wynikiem POZYTYWNYM!");
builder.setThumbnail(EmbedSettings.THUMBNAIL);
builder.setFooter("Podpis: " + Users.getUserNicknameFromID(drillId));
channel.sendMessage("Gratulacje <@" + recruitId + ">").setEmbeds(builder.build()).queue();
}
/**
* Jeżeli użytkownik nie jest botem usuwa wiadomość i wysyła informację że kanał służy do logowania i tam nie piszemy.
*
* @param event Wydarzenie napisania wiadomości na kanale tekstowym.
*/
public static void noWriteOnLoggerChannel(@NotNull MessageReceivedEvent event) {
if (!event.getAuthor().isBot()) {
event.getMessage().delete().submit();
User userById = DiscordBot.getJda().getUserById(event.getAuthor().getId());
if (userById != null) {
userById.openPrivateChannel().queue(privateChannel -> {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.WARNING);
builder.setTitle("Zachowajmy porządek!");
builder.setDescription("Panie administratorze! Zachowajmy czystość na kanale do loggowania. Proszę nie wtrącać się w moje wypociny.");
builder.setFooter(getFooter());
privateChannel.sendMessageEmbeds(builder.build()).queue();
});
}
}
}
/**
* Wysyła informację że pomyślnie wyłączono przypomnienia dla eventów.
*
* @param userID ID użytkownika
*/
public static void reminderOff(String userID) {
User userById = DiscordBot.getJda().getUserById(userID);
if (userById != null) {
userById.openPrivateChannel().queue(privateChannel -> {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.INF_CONFIRM);
builder.setTitle("Przypomnienia wyłączone.");
builder.setDescription("Aby włączyć ponownie przypomnienia użyj komendy **!reminder On**");
privateChannel.sendMessageEmbeds(builder.build()).queue();
});
}
}
/**
* Wysyła informację że <SUF>*/
public static void reminderOn(String userID) {
User userById = DiscordBot.getJda().getUserById(userID);
if (userById != null) {
userById.openPrivateChannel().queue(privateChannel -> {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.INF_CONFIRM);
builder.setTitle("Przypomnienia włączone.");
builder.setFooter("Więcej informacji i ustawień powiadomień pod komendą !help Reminder");
privateChannel.sendMessageEmbeds(builder.build()).queue();
});
}
}
/**
* Wysyła do użytkownika o ID userID wiadomość o zmianach w evencie.
*
* @param userID ID użytkownika
* @param whatChange jaka zmiana zostala wykonana
* @param dateTime data i czas
*/
public static void sendInfoChanges(String userID, Event event, @NotNull EventChanges whatChange, String dateTime) {
String description = "";
if (whatChange.equals(EventChanges.CHANGES)) {
description = "Zmieniona data lub czas wydarzenia na które się zapisałeś.";
} else if (whatChange.equals(EventChanges.REMOVE)) {
description = "Wydarzenie zostaje odwołane.";
}
String link = "[" + event.getName() + "](" + RangersGuild.getLinkToMessage(event.getChannelId(), event.getMsgId()) + ")";
User userById = DiscordBot.getJda().getUserById(userID);
String finalDescription = description + " Sprawdź szczegóły!";
if (userById != null) {
userById.openPrivateChannel().queue(privateChannel -> {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.INF_RED);
builder.setThumbnail(EmbedSettings.THUMBNAIL);
builder.setTitle("**UWAGA:** Zmiany w wydarzeniu.");
builder.setDescription(finalDescription);
builder.addField("Szczegóły eventu", link + "\n:date: " + dateTime, false);
privateChannel.sendMessageEmbeds(builder.build()).queue();
log.info("USER: {} - wysłałem powiadomienie", userID);
});
}
}
public static void seedersRoleJoining(@NotNull TextChannel channel) {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.INF_CONFIRM);
builder.setTitle("SQUAD SERVER SEEDER");
builder.addField("", "Jeśli chcesz pomóc nam w rozkręcaniu naszego serwera. Możesz przypisać sobię rolę klikając w poniższy przycisk by otrzymywać ping.", false);
builder.addField("", "If you would like to help us seed our server you can add role below to receive a ping.", false);
builder.setThumbnail(EmbedSettings.THUMBNAIL);
channel.sendMessageEmbeds(builder.build()).setActionRow(Button.success(ComponentId.SEED_ROLE, "Add/Remove Seed Role ").withEmoji(Emoji.fromUnicode("\uD83C\uDF31"))).queue();
}
/**
* Formatka z opisem jak stworzyć ticket.
*
* @param channel Kanał na którym wstawiana jest formatka.
*/
public static void serverService(@NotNull MessageChannel channel) {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.DEFAULT);
builder.setTitle("Rangers Polska Servers - Create Ticket :ticket:");
builder.addField("", "Jeśli potrzebujesz pomocy admina naszych serwerów, " +
"kliknij w odpowiedni przycisk poniżej.", false);
builder.addField("--------------------", "If you need help of Rangers Polska Servers Admins, " +
"please react with the correct button below.", false);
channel.sendMessageEmbeds(builder.build()).setActionRow(
Button.primary(ComponentId.SERVER_SERVICE_REPORT, "Report Player").withEmoji(Emoji.fromUnicode(EmbedSettings.BOOK_RED)),
Button.primary(ComponentId.SERVER_SERVICE_UNBAN, "Unban appeal").withEmoji(Emoji.fromUnicode(EmbedSettings.BOOK_BLUE)),
Button.primary(ComponentId.SERVER_SERVICE_CONTACT, "Contact With Admin").withEmoji(Emoji.fromUnicode(EmbedSettings.BOOK_GREEN))).queue();
}
/**
* Wysyła powitalną formatkę z opisem do czego dany kanał służy i co należy zrobić.
*
* @param userID pinguje usera z tym ID
* @param channel Kanał na którym wysyłana jest wiadomość
*/
public static void sendEmbedReport(String userID, @NotNull TextChannel channel) {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.WARNING);
builder.setTitle("Report player");
builder.addField("", """
Zgłoś gracza według poniższego formularza.
1. Podaj nick.
2. Opisz sytuację i podaj powód dlaczego zgłaszasz gracza.
3. Podaj nazwę serwera.
4. Dodaj dowody. Screenshot lub podaj link do wideo (np. Youtube).""", false);
builder.addField("--------------------", """
Report player according to the form below.
1. Player nick.
2. Describe of bad behaviour.
3. Server name.
4. Add evidence. Screenshot or video link (e.g. Youtube).""", false);
channel.sendMessage("<@" + userID + ">, " + "<@&" + RoleID.SERVER_ADMIN + ">")
.setEmbeds(builder.build())
.setActionRow(Button.primary(ComponentId.CLOSE, "Close ticket").withEmoji(Emoji.fromUnicode(EmbedSettings.LOCK)))
.queue(message -> message.pin().queue());
}
/**
* Wysyła powitalną formatkę z opisem do czego dany kanał służy i co należy zrobić.
*
* @param userID pinguje usera z tym ID
* @param channel Kanał na którym wysyłana jest wiadomość
*/
public static void sendEmbedUnban(String userID, @NotNull TextChannel channel) {
EmbedBuilder builder = getEmbedBuilder(Color.BLUE, ThumbnailType.DEFAULT);
builder.setTitle("Unban player");
builder.addField("", """
Napisz tutaj jeżeli chcesz odowłać swój ban.
1. Podaj swój nick i/lub steamid.
2. Podaj nazwę serwera.""", false);
builder.addField("--------------------", """
Write here if you want to revoke your ban.
1. Provide your ingame nick and/or steamid.
2. Server name.""", false);
channel.sendMessage("<@" + userID + ">, " + "<@&" + RoleID.SERVER_ADMIN + ">")
.setEmbeds(builder.build())
.setActionRow(Button.primary(ComponentId.CLOSE, "Close ticket").withEmoji(Emoji.fromUnicode(EmbedSettings.LOCK)))
.queue(message -> message.pin().queue());
}
/**
* Wysyła powitalną formatkę z opisem do czego dany kanał służy i co należy zrobić.
*
* @param userID pinguje usera z tym ID
* @param channel Kanał na którym wysyłana jest wiadomość
*/
public static void sendEmbedContact(String userID, @NotNull TextChannel channel) {
EmbedBuilder builder = getEmbedBuilder(Color.GREEN, ThumbnailType.DEFAULT);
builder.setTitle("Contact with Admin");
builder.addField("", "Napisz tutaj jeżeli masz jakiś problem z którymś z naszych serwerów, dodaj screenshoty, nazwę serwera. " +
"Twój nick w grze lub/i steamId64.", false);
builder.addField("--------------------", "Please describe your problem with more details, " +
"screenshots, servername the issue occured on and related steamId64", false);
channel.sendMessage("<@" + userID + ">, " + "<@&" + RoleID.SERVER_ADMIN + ">")
.setEmbeds(builder.build())
.setActionRow(Button.primary(ComponentId.CLOSE, "Close ticket").withEmoji(Emoji.fromUnicode(EmbedSettings.LOCK)))
.queue(message -> message.pin().queue());
}
public static void recruitAnonymousComplaintsFormOpening(@NotNull TextChannel textChannel) {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.INF_CONFIRM);
builder.setTitle("Anonimowe zgłoszenia");
builder.addField("Zgłoś anonimowo sytuację używając przycisku poniżej", "", false);
textChannel
.sendMessageEmbeds(builder.build())
.setActionRow(Button.primary(ComponentId.OPEN_FORM_ANONYMOUS_COMPLAINTS, "Formularz"))
.queue();
}
public static void recruitAccepted(String userName, @NotNull TextChannel textChannel) {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.INF_BLUE);
builder.setTitle("Rozpoczęto rekrutację");
builder.setDescription("Od tego momentu rozpoczyna się Twój okres rekrutacyjny pod okiem wszystkich członków klanu.");
builder.setFooter("Podpis: " + userName);
textChannel.sendMessageEmbeds(builder.build()).queue();
}
public static void recruitNotAccepted(String userName, @NotNull TextChannel textChannel) {
EmbedBuilder builder = getEmbedBuilder(EmbedStyle.INF_RED);
builder.setTitle("Podanie odrzucone");
builder.setFooter("Podpis: " + userName);
textChannel.sendMessageEmbeds(builder.build()).queue();
}
public static void warningMaxRecruits() {
TextChannel textChannel = RangersGuild.getTextChannel(RangersGuild.ChannelsId.DRILL_INSTRUCTOR_HQ);
if (textChannel != null) {
textChannel.sendMessage("**Brak wolnych miejsc. Rekrutacja zamknięta.**\nOsiągnięto maksymalną ilość kanałów w kategorii.").queue();
}
}
public static void warningFewSlots() {
TextChannel textChannel = RangersGuild.getTextChannel(RangersGuild.ChannelsId.DRILL_INSTRUCTOR_HQ);
if (textChannel != null) {
textChannel.sendMessage("**Pozostały 2 lub mniej miejsc dla rekrutów.**").queue();
}
}
}
| null |
6872_0 | MateuszJagienski/AISMarineTracker | 1,001 | src/main/java/pl/ais/aismarinetracker/decoder/reports/BaseStationReport.java | package pl.ais.aismarinetracker.decoder.reports;
import pl.ais.aismarinetracker.decoder.Decoders;
import pl.ais.aismarinetracker.decoder.enums.EPFD;
import pl.ais.aismarinetracker.decoder.enums.SyncState;
import lombok.Getter;
@Getter
public class BaseStationReport extends AisMessage implements IPositionReport {
private int year;
private int month;
private int day;
private int hour;
private int minute;
private int second;
private boolean fixQuality;
private float longitude;
private float latitude;
private EPFD typeOfEPFD;
private boolean raimFlag;
private ICommunicationState SOTDMAState;
public BaseStationReport(String messagePayload) {
super(messagePayload);
decode();
}
private void decode() {
this.raimFlag = decodeRaimFlag();
this.fixQuality = decodeFixQuality();
this.longitude = decodeLongitude();
this.latitude = decodeLatitude();
this.typeOfEPFD = decodeTypeOfEPFD();
this.year = decodeYear();
this.month = decodeMonth();
this.day = decodeDay();
this.hour = decodeHour();
this.minute = decodeMinute();
this.second = decodeSecond();
this.SOTDMAState = decodeSOTDMAState();
}
private int decodeYear() {
return Decoders.toUnsignedInteger(getBinaryMessagePayload().substring(38, 52)); // todo dlaczego tak duzo bitow?
}
private int decodeMonth() {
return Decoders.toUnsignedInteger(getBinaryMessagePayload().substring(52, 56));
}
private int decodeDay() {
return Decoders.toUnsignedInteger(getBinaryMessagePayload().substring(56, 61));
}
private int decodeHour() {
return Decoders.toUnsignedInteger(getBinaryMessagePayload().substring(61, 66));
}
private int decodeMinute() {
return Decoders.toUnsignedInteger(getBinaryMessagePayload().substring(66, 72));
}
private int decodeSecond() {
return Decoders.toUnsignedInteger(getBinaryMessagePayload().substring(72, 78));
}
private boolean decodeFixQuality() {
return Decoders.toBoolean(getBinaryMessagePayload().substring(78, 79));
}
private float decodeLongitude() {
var longitude = Decoders.toFloat(getBinaryMessagePayload().substring(79, 107));
return longitude / 600000f;
}
private float decodeLatitude() {
var latitude = Decoders.toFloat(getBinaryMessagePayload().substring(107, 134));
return latitude / 600000f;
}
private EPFD decodeTypeOfEPFD() {
return EPFD.from(Decoders.toInteger(getBinaryMessagePayload().substring(134, 138)));
}
private boolean decodeRaimFlag() {
return Decoders.toBoolean(getBinaryMessagePayload().substring(148, 149));
}
private ICommunicationState decodeSOTDMAState() {
SyncState syncState = SyncState.from(Decoders.toUnsignedInteger(getBinaryMessagePayload().substring(149, 151)));
return new SOTDMACommunicationState(syncState, Decoders.toUnsignedInteger(getBinaryMessagePayload().substring(151, 154)),
getBinaryMessagePayload().substring(154, 168));
}
}
| // todo dlaczego tak duzo bitow? | package pl.ais.aismarinetracker.decoder.reports;
import pl.ais.aismarinetracker.decoder.Decoders;
import pl.ais.aismarinetracker.decoder.enums.EPFD;
import pl.ais.aismarinetracker.decoder.enums.SyncState;
import lombok.Getter;
@Getter
public class BaseStationReport extends AisMessage implements IPositionReport {
private int year;
private int month;
private int day;
private int hour;
private int minute;
private int second;
private boolean fixQuality;
private float longitude;
private float latitude;
private EPFD typeOfEPFD;
private boolean raimFlag;
private ICommunicationState SOTDMAState;
public BaseStationReport(String messagePayload) {
super(messagePayload);
decode();
}
private void decode() {
this.raimFlag = decodeRaimFlag();
this.fixQuality = decodeFixQuality();
this.longitude = decodeLongitude();
this.latitude = decodeLatitude();
this.typeOfEPFD = decodeTypeOfEPFD();
this.year = decodeYear();
this.month = decodeMonth();
this.day = decodeDay();
this.hour = decodeHour();
this.minute = decodeMinute();
this.second = decodeSecond();
this.SOTDMAState = decodeSOTDMAState();
}
private int decodeYear() {
return Decoders.toUnsignedInteger(getBinaryMessagePayload().substring(38, 52)); // todo dlaczego <SUF>
}
private int decodeMonth() {
return Decoders.toUnsignedInteger(getBinaryMessagePayload().substring(52, 56));
}
private int decodeDay() {
return Decoders.toUnsignedInteger(getBinaryMessagePayload().substring(56, 61));
}
private int decodeHour() {
return Decoders.toUnsignedInteger(getBinaryMessagePayload().substring(61, 66));
}
private int decodeMinute() {
return Decoders.toUnsignedInteger(getBinaryMessagePayload().substring(66, 72));
}
private int decodeSecond() {
return Decoders.toUnsignedInteger(getBinaryMessagePayload().substring(72, 78));
}
private boolean decodeFixQuality() {
return Decoders.toBoolean(getBinaryMessagePayload().substring(78, 79));
}
private float decodeLongitude() {
var longitude = Decoders.toFloat(getBinaryMessagePayload().substring(79, 107));
return longitude / 600000f;
}
private float decodeLatitude() {
var latitude = Decoders.toFloat(getBinaryMessagePayload().substring(107, 134));
return latitude / 600000f;
}
private EPFD decodeTypeOfEPFD() {
return EPFD.from(Decoders.toInteger(getBinaryMessagePayload().substring(134, 138)));
}
private boolean decodeRaimFlag() {
return Decoders.toBoolean(getBinaryMessagePayload().substring(148, 149));
}
private ICommunicationState decodeSOTDMAState() {
SyncState syncState = SyncState.from(Decoders.toUnsignedInteger(getBinaryMessagePayload().substring(149, 151)));
return new SOTDMACommunicationState(syncState, Decoders.toUnsignedInteger(getBinaryMessagePayload().substring(151, 154)),
getBinaryMessagePayload().substring(154, 168));
}
}
| null |
3189_1 | MathMatowicki/Algorithms-and-Datastructure | 1,774 | PS3/Exercise4.java | /*
Zaimplementuj algorytm wspomagający proces decyzyjny w fabryce papieru odnośnie cięcia
dużych arkuszy papieru na mniejsze. Wiadomo, że celem zachowania kątów prostych, cięcia
wykonywane są przez maszynę jedynie po liniach poziomych lub pionowych. Odrzut papieru z
dużego arkusza jest wyrażony w postaci kosztów linii cięcia. Należy zminimalizować koszt
pocięcia dużego arkusza na mniejsze . Koszty cięć wzdłuż pionowych linii
oznaczone są jako x1, x2, ..., xm-1, zaś wzdłuż poziomych linii jako y1, y2, ..., yn-1. Całkowity koszt
pocięcia arkusza to suma kosztów wybranych linii cięcia.
Dla przykładowego arkusza koszt jego pocięcia wzdłuż przerywanych linii jest równy:
y1 + y2 + y3 + 4(x1 + x2 + x3 + x4 + x5)
*/
import java.io.*;
import java.util.*;
public class Exercise4 {
public static void displayMenu() {
System.out.println("************* MENU ************");
System.out.println("*************1-Wczytaj dane z pliku ************");
System.out.println("*************2-Oblicz ************");
System.out.println("*************3-Testuj ************");
System.out.println("*************4-Zakoncz program ************");
}
public static int[][] wczytaj() throws FileNotFoundException {
String nazwaPliku = "c:/Users/matow/Dev/Algorithms-and-Datastructure/PS3/in4.txt";
int[][] tab = null;
int liczba;
BufferedReader br = new BufferedReader(new FileReader(nazwaPliku));
String linia;
String[] podzielonaLinia = null;
try {
for (int i = 0; (linia = br.readLine()) != null; i++) {
podzielonaLinia = linia.split(" ");
for (int j = 0; j < podzielonaLinia.length; j++) {
liczba = Integer.parseInt(podzielonaLinia[j].trim());
if (i == 0) {
tab = new int[liczba][5];
tab[i][j] = liczba;
}
if (i == 1) {
tab[i - 1][j] = liczba;
}
if (i >= 2) {
tab[i - 1][j] = liczba;
}
}
}
} catch (IOException | NumberFormatException e) {
System.err.println("Wystapil blad przy wczytywaniu danych");
}
return tab;
}
public static void main(String[] args) throws IOException {
int[][] tab = null;
int x, l1 = 0;
Scanner s = new Scanner(System.in);
// System.out.println(Arrays.deepToString(tab));
while (true) {
displayMenu();
x = s.nextInt();
switch (x) {
case 1:
tab = wczytaj();
System.out.println(Arrays.deepToString(tab));
break;
case 2:
l1 = algorytm1(tab);
break;
case 3:
System.out.println("licznik operacji w algorytmie 1 = " + l1);
break;
case 4:
return;
}
}
}
private static int algorytm1(int[][] tab) throws FileNotFoundException {
int counter = 0, sum, cieciex, cieciey;
PrintWriter zapis = new PrintWriter("c:/Users/matow/Dev/Algorithms-and-Datastructure/PS3/out4.txt");
List<Integer> xList = new ArrayList<>(tab[0].length);
List<Integer> yList = new ArrayList<>(tab[1].length - 2);
//Zmiana tablicy na typ ArrayList w celu łatwiejszego znajdywania maxa
for (int i : tab[0]) {
xList.add(i);
}
for (int i : tab[1]) {
yList.add(i);
}
Integer ele = 0;
while (yList.contains(ele)) {
yList.remove(ele);
}
int n = yList.size(), m = xList.size();
cieciex = 1;
cieciey = 1;
sum = 0;
for (int i = 0; i < n + m; i++) {
counter++;
if (!xList.isEmpty() && !yList.isEmpty()) {
counter++;
if (Collections.max(xList) >= Collections.max(yList)) {
sum = sum + Collections.max(xList) * cieciex;
// System.out.println("Suma:" + sum + "cieciex " + cieciex);
cieciey++;
xList.remove(Collections.max(xList));
} else {
sum = sum + Collections.max(yList) * cieciey;
// System.out.println("Suma:" + sum + "cieciey " + cieciey);
cieciex++;
yList.remove(Collections.max(yList));
}
counter++;
} else if (xList.isEmpty()) {
while (!yList.isEmpty()) {
sum = sum + Collections.max(yList) * cieciey;
// System.out.println("Suma:" + sum + "cieciey " + cieciey);
cieciey++;
yList.remove(Collections.max(yList));
}
counter++;
} else {
while (!xList.isEmpty()) {
sum = sum + Collections.max(xList) * cieciex;
// System.out.println("Suma:" + sum + "cieciex " + cieciex);
cieciex++;
xList.remove(Collections.max(xList));
}
}
}
zapis.println("Suma to : " + sum);
zapis.close();
System.out.println("Suma to : " + sum);
return counter;
}
} | //Zmiana tablicy na typ ArrayList w celu łatwiejszego znajdywania maxa | /*
Zaimplementuj algorytm wspomagający proces decyzyjny w fabryce papieru odnośnie cięcia
dużych arkuszy papieru na mniejsze. Wiadomo, że celem zachowania kątów prostych, cięcia
wykonywane są przez maszynę jedynie po liniach poziomych lub pionowych. Odrzut papieru z
dużego arkusza jest wyrażony w postaci kosztów linii cięcia. Należy zminimalizować koszt
pocięcia dużego arkusza na mniejsze . Koszty cięć wzdłuż pionowych linii
oznaczone są jako x1, x2, ..., xm-1, zaś wzdłuż poziomych linii jako y1, y2, ..., yn-1. Całkowity koszt
pocięcia arkusza to suma kosztów wybranych linii cięcia.
Dla przykładowego arkusza koszt jego pocięcia wzdłuż przerywanych linii jest równy:
y1 + y2 + y3 + 4(x1 + x2 + x3 + x4 + x5)
*/
import java.io.*;
import java.util.*;
public class Exercise4 {
public static void displayMenu() {
System.out.println("************* MENU ************");
System.out.println("*************1-Wczytaj dane z pliku ************");
System.out.println("*************2-Oblicz ************");
System.out.println("*************3-Testuj ************");
System.out.println("*************4-Zakoncz program ************");
}
public static int[][] wczytaj() throws FileNotFoundException {
String nazwaPliku = "c:/Users/matow/Dev/Algorithms-and-Datastructure/PS3/in4.txt";
int[][] tab = null;
int liczba;
BufferedReader br = new BufferedReader(new FileReader(nazwaPliku));
String linia;
String[] podzielonaLinia = null;
try {
for (int i = 0; (linia = br.readLine()) != null; i++) {
podzielonaLinia = linia.split(" ");
for (int j = 0; j < podzielonaLinia.length; j++) {
liczba = Integer.parseInt(podzielonaLinia[j].trim());
if (i == 0) {
tab = new int[liczba][5];
tab[i][j] = liczba;
}
if (i == 1) {
tab[i - 1][j] = liczba;
}
if (i >= 2) {
tab[i - 1][j] = liczba;
}
}
}
} catch (IOException | NumberFormatException e) {
System.err.println("Wystapil blad przy wczytywaniu danych");
}
return tab;
}
public static void main(String[] args) throws IOException {
int[][] tab = null;
int x, l1 = 0;
Scanner s = new Scanner(System.in);
// System.out.println(Arrays.deepToString(tab));
while (true) {
displayMenu();
x = s.nextInt();
switch (x) {
case 1:
tab = wczytaj();
System.out.println(Arrays.deepToString(tab));
break;
case 2:
l1 = algorytm1(tab);
break;
case 3:
System.out.println("licznik operacji w algorytmie 1 = " + l1);
break;
case 4:
return;
}
}
}
private static int algorytm1(int[][] tab) throws FileNotFoundException {
int counter = 0, sum, cieciex, cieciey;
PrintWriter zapis = new PrintWriter("c:/Users/matow/Dev/Algorithms-and-Datastructure/PS3/out4.txt");
List<Integer> xList = new ArrayList<>(tab[0].length);
List<Integer> yList = new ArrayList<>(tab[1].length - 2);
//Zmiana tablicy <SUF>
for (int i : tab[0]) {
xList.add(i);
}
for (int i : tab[1]) {
yList.add(i);
}
Integer ele = 0;
while (yList.contains(ele)) {
yList.remove(ele);
}
int n = yList.size(), m = xList.size();
cieciex = 1;
cieciey = 1;
sum = 0;
for (int i = 0; i < n + m; i++) {
counter++;
if (!xList.isEmpty() && !yList.isEmpty()) {
counter++;
if (Collections.max(xList) >= Collections.max(yList)) {
sum = sum + Collections.max(xList) * cieciex;
// System.out.println("Suma:" + sum + "cieciex " + cieciex);
cieciey++;
xList.remove(Collections.max(xList));
} else {
sum = sum + Collections.max(yList) * cieciey;
// System.out.println("Suma:" + sum + "cieciey " + cieciey);
cieciex++;
yList.remove(Collections.max(yList));
}
counter++;
} else if (xList.isEmpty()) {
while (!yList.isEmpty()) {
sum = sum + Collections.max(yList) * cieciey;
// System.out.println("Suma:" + sum + "cieciey " + cieciey);
cieciey++;
yList.remove(Collections.max(yList));
}
counter++;
} else {
while (!xList.isEmpty()) {
sum = sum + Collections.max(xList) * cieciex;
// System.out.println("Suma:" + sum + "cieciex " + cieciex);
cieciex++;
xList.remove(Collections.max(xList));
}
}
}
zapis.println("Suma to : " + sum);
zapis.close();
System.out.println("Suma to : " + sum);
return counter;
}
} | null |
6093_0 | MatiPl01/concurrency-theory | 410 | lab2/producer-consumer/App.java | /**
* Przygotuj się na ocenę na nast. zajęcia z wyjasnienia, w jaki
* sposób dochodzi do zakleszczenia
*
* np. mamy 2 producentów, 1 konsumenta i 1-elementowy bufor,
* - pierwszy do monitora zostaje wpuszczony wątek konsumenta i zawiesza się na pustym buforze,
* - kolejny do monitora wchodzi producent i zapełnia bufor,
* - zamiast zwolnić wątek konsumenta, kóry został wyrzucony z monitora,
* po wykonaniu notify i czeka razem z drugim producentem na wejście,
* do monitora wchodzi wątek producenta, który wiesza się na pełnym buforze,
* - mamy 2 zawieszonych producentów i żaden z nich nie wywoła już notify, bo
* obaj producenci czekają na pełnym buforze, dlatego konsument nie zostaje
* wpuszczony do monitora (bo nie dostał notify)
*/
public class App {
public static void main(String[] args) {
int producerCount = 2;
int consumerCount = 1;
Counter counter = new Counter();
for (int i = 0; i < producerCount; i++) {
new Thread(new Producer(counter)).start();
}
for (int i = 0; i < consumerCount; i++) {
new Thread(new Consumer(counter)).start();
}
}
}
| /**
* Przygotuj się na ocenę na nast. zajęcia z wyjasnienia, w jaki
* sposób dochodzi do zakleszczenia
*
* np. mamy 2 producentów, 1 konsumenta i 1-elementowy bufor,
* - pierwszy do monitora zostaje wpuszczony wątek konsumenta i zawiesza się na pustym buforze,
* - kolejny do monitora wchodzi producent i zapełnia bufor,
* - zamiast zwolnić wątek konsumenta, kóry został wyrzucony z monitora,
* po wykonaniu notify i czeka razem z drugim producentem na wejście,
* do monitora wchodzi wątek producenta, który wiesza się na pełnym buforze,
* - mamy 2 zawieszonych producentów i żaden z nich nie wywoła już notify, bo
* obaj producenci czekają na pełnym buforze, dlatego konsument nie zostaje
* wpuszczony do monitora (bo nie dostał notify)
*/ | /**
* Przygotuj się na <SUF>*/
public class App {
public static void main(String[] args) {
int producerCount = 2;
int consumerCount = 1;
Counter counter = new Counter();
for (int i = 0; i < producerCount; i++) {
new Thread(new Producer(counter)).start();
}
for (int i = 0; i < consumerCount; i++) {
new Thread(new Consumer(counter)).start();
}
}
}
| null |
3136_0 | MattWroclaw/ZadanieQuizowe | 1,259 | src/main/java/Quiz.java | import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Quiz {
public static void main(String[] args) throws FileNotFoundException {
File kategoriaPytan = zakresPytan();
System.out.println("Wybrałeś tematykę: "+kategoriaPytan.getName());
List<ZadaniaQuizowe> zadaniaQuizowes = wczytajPlik(kategoriaPytan);
graj(zadaniaQuizowes);
}
private static void graj(List<ZadaniaQuizowe> zadania){
int punkty =0;
Collections.shuffle(zadania);
for (int i =0; i<10 ;i++){
ZadaniaQuizowe zadanie = zadania.get(i);
System.out.println("Zadanie "+i+":"+zadanie.pytanie);
// przed mixowaniem odpowiedzi, trzeba zapamietac, ta ktora jest poprawna
List<String> odpowiedzi = zadanie.odpowiedzi; //tutaj
String poprawnaOdpowiedz = odpowiedzi.get(0);
Collections.shuffle(odpowiedzi);
for (int j=0; j<odpowiedzi.size(); j++){
System.out.println(j+") "+odpowiedzi.get(j));
}
Scanner scanner = new Scanner(System.in);
int nrWybranejOdpowiedzi = scanner.nextInt();
String odpowiedzWybranaPrzezGracza = odpowiedzi.get(nrWybranejOdpowiedzi);
if (odpowiedzWybranaPrzezGracza.equals(poprawnaOdpowiedz)){
System.out.println("Poprawna odpowiedź");
punkty++;
} else {
System.out.println("Błąd");
System.out.println("Poprawna odpowiedź to:"+poprawnaOdpowiedz);
}
System.out.println("Zdobyłeś "+punkty+" punktów");
}
}
// zad 1
public static File zakresPytan(){
File folder = new File("src/main/resources");
File [] kategorie = folder.listFiles();
int ileKategrii = kategorie.length;
for (int i = 1 ; i< ileKategrii; i++){
String plik = kategorie[i].getName();
System.out.println(i+" - "+plik);
}
System.out.println("Wybierz tematykę (numer), która Cię interesuje");
Scanner scanner = new Scanner(System.in);
int nrTematyki = scanner.nextInt();
File wybranaKategoria = kategorie[nrTematyki];
return wybranaKategoria;
}
// do mieszania odpowiedzi służy Collections.shuffle(jakaś lista)
// Zad.2 w tej metodzie przekazujemy już pojedynczy plik z pytaniami z wybranej wczesniej
// tematyki
private static List<ZadaniaQuizowe> wczytajPlik(File plik) throws FileNotFoundException {
Scanner scanner = new Scanner(plik);
List<ZadaniaQuizowe> zadania = new ArrayList<ZadaniaQuizowe>();
while (scanner.hasNextLine()) {
ZadaniaQuizowe zadanie = new ZadaniaQuizowe();
zadanie.pytanie = scanner.nextLine();
// String pytanie = scanner.nextLine();
// System.out.println("Pytanie:" + zadanie.pytanie);
// trzeba parsować, bo jak się zrobi nextInt to może być cośtam ze
// znakiem końca linii i ogólnie kupa
String ileOdpowiedzi = scanner.nextLine();
int ileOdp = Integer.parseInt(ileOdpowiedzi);
List<String> mozliweOdpowiedzi = new ArrayList<String>(ileOdp);
for (int i = 0; i < ileOdp; i++) {
String odpowiedz = scanner.nextLine();
// System.out.println("Odpowiedz: " + odpowiedz);
mozliweOdpowiedzi.add(odpowiedz);
}
zadanie.odpowiedzi = mozliweOdpowiedzi;
zadania.add(zadanie);
}
return zadania;
}
}
| // przed mixowaniem odpowiedzi, trzeba zapamietac, ta ktora jest poprawna | import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Quiz {
public static void main(String[] args) throws FileNotFoundException {
File kategoriaPytan = zakresPytan();
System.out.println("Wybrałeś tematykę: "+kategoriaPytan.getName());
List<ZadaniaQuizowe> zadaniaQuizowes = wczytajPlik(kategoriaPytan);
graj(zadaniaQuizowes);
}
private static void graj(List<ZadaniaQuizowe> zadania){
int punkty =0;
Collections.shuffle(zadania);
for (int i =0; i<10 ;i++){
ZadaniaQuizowe zadanie = zadania.get(i);
System.out.println("Zadanie "+i+":"+zadanie.pytanie);
// przed mixowaniem <SUF>
List<String> odpowiedzi = zadanie.odpowiedzi; //tutaj
String poprawnaOdpowiedz = odpowiedzi.get(0);
Collections.shuffle(odpowiedzi);
for (int j=0; j<odpowiedzi.size(); j++){
System.out.println(j+") "+odpowiedzi.get(j));
}
Scanner scanner = new Scanner(System.in);
int nrWybranejOdpowiedzi = scanner.nextInt();
String odpowiedzWybranaPrzezGracza = odpowiedzi.get(nrWybranejOdpowiedzi);
if (odpowiedzWybranaPrzezGracza.equals(poprawnaOdpowiedz)){
System.out.println("Poprawna odpowiedź");
punkty++;
} else {
System.out.println("Błąd");
System.out.println("Poprawna odpowiedź to:"+poprawnaOdpowiedz);
}
System.out.println("Zdobyłeś "+punkty+" punktów");
}
}
// zad 1
public static File zakresPytan(){
File folder = new File("src/main/resources");
File [] kategorie = folder.listFiles();
int ileKategrii = kategorie.length;
for (int i = 1 ; i< ileKategrii; i++){
String plik = kategorie[i].getName();
System.out.println(i+" - "+plik);
}
System.out.println("Wybierz tematykę (numer), która Cię interesuje");
Scanner scanner = new Scanner(System.in);
int nrTematyki = scanner.nextInt();
File wybranaKategoria = kategorie[nrTematyki];
return wybranaKategoria;
}
// do mieszania odpowiedzi służy Collections.shuffle(jakaś lista)
// Zad.2 w tej metodzie przekazujemy już pojedynczy plik z pytaniami z wybranej wczesniej
// tematyki
private static List<ZadaniaQuizowe> wczytajPlik(File plik) throws FileNotFoundException {
Scanner scanner = new Scanner(plik);
List<ZadaniaQuizowe> zadania = new ArrayList<ZadaniaQuizowe>();
while (scanner.hasNextLine()) {
ZadaniaQuizowe zadanie = new ZadaniaQuizowe();
zadanie.pytanie = scanner.nextLine();
// String pytanie = scanner.nextLine();
// System.out.println("Pytanie:" + zadanie.pytanie);
// trzeba parsować, bo jak się zrobi nextInt to może być cośtam ze
// znakiem końca linii i ogólnie kupa
String ileOdpowiedzi = scanner.nextLine();
int ileOdp = Integer.parseInt(ileOdpowiedzi);
List<String> mozliweOdpowiedzi = new ArrayList<String>(ileOdp);
for (int i = 0; i < ileOdp; i++) {
String odpowiedz = scanner.nextLine();
// System.out.println("Odpowiedz: " + odpowiedz);
mozliweOdpowiedzi.add(odpowiedz);
}
zadanie.odpowiedzi = mozliweOdpowiedzi;
zadania.add(zadanie);
}
return zadania;
}
}
| null |
8202_1 | MattWroclaw/jdbc_expls | 489 | src/main/java/sda/jdbc/przyklad1.java | /*
* przyklad1
* Przyklad pokazuje jak podlaczyc sie do bazy danych, wykonac zapytanie SELECT
* wykozystujac interface Statement i wyswietla wynik na konsoli.
* */
package sda.jdbc;
import java.sql.*;
public class przyklad1 {
public static void main(String arg[]) {
Connection connection = null;
Statement stmt = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver"); //od wersji 4 nie trzeba tego wskazywać
String url = "jdbc:mysql://localhost:3306/ksiegarnia"; // albo nazwa bazy danych albo nazwa schematu
String user = "sdatest";
String password = "Start123!";
connection = DriverManager.getConnection(url, user, password);
stmt = connection.createStatement();
ResultSet resultSet = stmt.executeQuery("SELECT imie, nazwisko FROM uzytkownik;");
while (resultSet.next()) {
String imie = resultSet.getString("imie"); // można też zrobic (columnIndex: 1) w SQL liczymy od 1 nie od 0
String nazwisko = resultSet.getString("nazwisko");
System.out.println("pobrano uzytkownika: " + imie + " " + nazwisko);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
stmt.close(); // kolejność zamykania jest w dowrotnej kolejności jak kolejność otwierania
} catch (SQLException e) {
e.printStackTrace();
}
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
| //od wersji 4 nie trzeba tego wskazywać | /*
* przyklad1
* Przyklad pokazuje jak podlaczyc sie do bazy danych, wykonac zapytanie SELECT
* wykozystujac interface Statement i wyswietla wynik na konsoli.
* */
package sda.jdbc;
import java.sql.*;
public class przyklad1 {
public static void main(String arg[]) {
Connection connection = null;
Statement stmt = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver"); //od wersji <SUF>
String url = "jdbc:mysql://localhost:3306/ksiegarnia"; // albo nazwa bazy danych albo nazwa schematu
String user = "sdatest";
String password = "Start123!";
connection = DriverManager.getConnection(url, user, password);
stmt = connection.createStatement();
ResultSet resultSet = stmt.executeQuery("SELECT imie, nazwisko FROM uzytkownik;");
while (resultSet.next()) {
String imie = resultSet.getString("imie"); // można też zrobic (columnIndex: 1) w SQL liczymy od 1 nie od 0
String nazwisko = resultSet.getString("nazwisko");
System.out.println("pobrano uzytkownika: " + imie + " " + nazwisko);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
stmt.close(); // kolejność zamykania jest w dowrotnej kolejności jak kolejność otwierania
} catch (SQLException e) {
e.printStackTrace();
}
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
| null |
8007_2 | Meridiano1984/gui_swing_anim | 750 | src/figury/AnimatorApp.java | package figury;
import java.awt.EventQueue;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.JButton;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class AnimatorApp extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
final AnimatorApp frame = new AnimatorApp();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* @param delay
*/
public AnimatorApp() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int ww = 450, wh = 300;
setBounds((screen.width-ww)/2, (screen.height-wh)/2, ww, wh);
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(null);
AnimPanel kanwa = new AnimPanel();
kanwa.setBounds(10, 11, 422, 219);
contentPane.add(kanwa);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
kanwa.initialize();
}
});
JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
kanwa.addFig();
}
});
btnAdd.setBounds(10, 239, 80, 23);
contentPane.add(btnAdd);
JButton btnAnimate = new JButton("Animate");
btnAnimate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
kanwa.animate();
}
});
btnAnimate.setBounds(100, 239, 80, 23);
contentPane.add(btnAnimate);
//Tutaj dodaje przykładowy komentarz
}
}
| //Tutaj dodaje przykładowy komentarz | package figury;
import java.awt.EventQueue;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.JButton;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class AnimatorApp extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
final AnimatorApp frame = new AnimatorApp();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* @param delay
*/
public AnimatorApp() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int ww = 450, wh = 300;
setBounds((screen.width-ww)/2, (screen.height-wh)/2, ww, wh);
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(null);
AnimPanel kanwa = new AnimPanel();
kanwa.setBounds(10, 11, 422, 219);
contentPane.add(kanwa);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
kanwa.initialize();
}
});
JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
kanwa.addFig();
}
});
btnAdd.setBounds(10, 239, 80, 23);
contentPane.add(btnAdd);
JButton btnAnimate = new JButton("Animate");
btnAnimate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
kanwa.animate();
}
});
btnAnimate.setBounds(100, 239, 80, 23);
contentPane.add(btnAnimate);
//Tutaj dodaje <SUF>
}
}
| null |
10085_5 | Michal-Koter/Advanced-JAVA | 3,154 | lab-03-Michal-Koter/schedulers/src/main/java/org/example/Main.java | package org.example;
import org.example.Chron.Chron;
import org.example.Chron.abstractions.IProvideNextExecutionTime;
import org.example.scheduler.SchedulerThread;
import org.example.scheduler.abstractions.ICatchException;
import org.example.scheduler.abstractions.IRunNotSafeAction;
import org.example.scheduler.Scheduler;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Random;
public class Main {
public static void main(String[] args) {
/**
* Zanim zaczniesz pisać kod,
* zajrzyj do kodu poniższej metody
* i spróbuj zrozumieć o co w niej chodzi.
* Jest tam przykład prostej implementacji
* wzorca zwanego "metodą wytwórczą",
* czasem zwaną "fabrykującą",
* oraz prostej implementacji wzorca projektowego "budowniczego".
*
* zrozumienie implementacji tej metody
* pomoże Tobie w rozwiązaniu następnych zadań.
*/
checkThisOut();
/**
* Utwórz nowy interfejs
* z zadeklarowaną metodą "provideTime".
* Jego implementacje później będą wykorzystywane
* do określania, kiedy mają być wywoływane
* konkretne operacje
*/
IProvideNextExecutionTime nextExecutionTimeProvider;
/**
* dodaj adnotację @FunctionalInterface
* nad nowoutworzonym interfejsem
* aby zaznaczyć, że będzie on używany
* z operatorem lambda.
*
* poniżej masz dwie przykładowe implementacje
* tego interfejsu w postaci wyrażeń (metod) lambda
*/
nextExecutionTimeProvider = LocalDateTime::now;
nextExecutionTimeProvider = () -> LocalDateTime.now();
/**
* Twoim pierwszym zadaniem jest napisanie
* klasy o nazwie "Chron",
* która jest przykładem prostej implementacji
* wzorca projektowego "budowniczego".
* Budowniczy w tym przykładzie zwraca metodę
* wytwórczą, która ma być implementacją wcześniej utworzonego interfejsu.
*
* Chodzi o taką implemntację tych wzorców,
* gdzie można ustawić:
* -> setStartTime: godzinę startu (domyślnie teraz)
* -> setEndTime: godzinę końca (domyślnie nigdy),
* -> setMaxExecutionTimes: ilość powtórzeń wykonania
* (czyli ile kolejnych godzin\czasów ma zwrócić - domyślnie ma wykonywać w nieskończoność),
* -> setIntervalDuration: odstęp czasowy między kolejnymi godzinami/ czasami (domyślnie 1 sekunda)
*
* Metoda buildNextTimeExecutionProvider ma zwracać lambdę,
* która generuje kolejną godzinę według wcześniej podanych parametrów
* UAWAGA !
* Najlepiej zrobić tak, aby klasa Chron implementowała "buildera" (budowniczego) - w sensie nie robić buildera jako odrębnej klasy
*/
IProvideNextExecutionTime<Chron> startsNowFor5SecondsMax5TimesWithDurationOf500Millis = Chron.builder()
.setStartTime(LocalDateTime.now())
.setEndDate(LocalDateTime.now().plusSeconds(5))
.setMaxExecutionTimes(5)
.setIntervalDuration(Duration.ofMillis(500))
.buildNextExecutionTimeProvider();
/**
* Super udało się - jestem pod wielkim wrażeniem ;-]
* W dalszej części programu bedziemy potrzebowali
* kolejnego interfejsu, który będzie wykorzystywany
* jako lambda, która może rzucić wyjątkiem (błędem)
*/
IRunNotSafeAction throwAnError = ()->{ throw new Exception(); };
try {
throwAnError.executeNotSafeAction();
System.out.println("tutaj powinien wystąpić błąd, a nie wystąpił :(");
return;
}catch (Exception ex){
}
/**
* wykorzystajmy metodę,
* która co jakiś czas rzuca błedem
* jako implementacja powyższego interfejsu
*/
// IRunNotSafeAction randomlyThrowsAnError = () -> randomlyThrowException();
/* albo inaczej: */
IRunNotSafeAction randomlyThrowsAnErrorMethodReference = Main::randomlyThrowException;
/**
* Jeśli myslałeś, że poprzednie zadanie było łatwe,
* to ciekawe co powiesz o tym...
*
* Teraz mamy zdefiniowene dwa interfejsy:
* 1. IProvideNextExecutionTime - implementacja zwraca kolejną godzinę,
* według ustawień podanych w builderze
* 2. IRunNotSafeAction - implementacje tego interfejsu będą definiować zadanie,
* które będzie wykonywane przez harmonogram
*
* Czas na zaimplementowanie klasy Scheduler,
* która to właśnie będzie odpowiadać za wykonywanie zadań,
* o konkretnych porach.
*
* Ta klasa będzie mixem 2 wzorców projektowych:
* 1. singletonu - chcemy, aby był tylko jeden harmonogram,
* w którym będą przechowywane informacje o wszystkich zadaniach jakie mają być wykonane (Implementacje IRunNotSafeAction),
* oraz o metodzie lambda która zwraca kolejne czasy wykonania danego zadania (implementacja IProvideNextExecutionTime)
* 2. budowniczego:
* -> forAction: metoda do definiowania zadania do wykonania
* -> onError: metoda która przyjmuje lambdę, która to z kolei jako parametr ma przyjąć wyjątek, i jakoś go obsłużyć
* -> onSingleActionCompleted: przyjmuje lambdę, która definiuje co ma się stać po wykonaniu pojednyczego zadania
* -> onCompleted: przyjmuje lambdę, która definiuje co ma się stać gdy wszystkie zadania danego typu się zakończą
* -> schedule: zapisuje wszystkie powyższe dane do pewnej kolekcji
*
* UWAGA!
* W tym zadaniu pewnie będziesz musiał napisac kilka własnych klas/ inetrfejsów pomocniczych,
* których nie spotkasz w tym miejscu (tzn. w ciele funkcji main, w której aktualnie się znajdujemy)
*/
ICatchException iCatchException = (ex)->{
System.out.println(ex.getMessage());
};
Scheduler scheduler = Scheduler.getInstance();
scheduler.build()
.forAction(randomlyThrowsAnErrorMethodReference)
.useExecutionTimeProvider(startsNowFor5SecondsMax5TimesWithDurationOf500Millis)
.onError(iCatchException)
.onSingleActionCompleted(()->System.out.println("wykonano akcje z powodzeniem"))
.onCompleted(()->System.out.println("Zakończyłem pracę"))
.schedule();
/**
* Jeżeli już tutaj się znalazłeś i samemu rozwiązałeeś powyższe zadania,
* to wiedz, że drzemie w Tobie duży potencjał - tak trzymać !
*
* No to mamy już możliwość tworzenia harmonogramów zadań
* teraz przyda się nam jakiś wątek, który będzie mógł uruchamiać te zadania,
* w tle działania aplikacji
* Utwórz klasę SchedulerThread,
* która implementuje interfejs Runnable (ten interfejs jest utworzony w frameworku JAVY),
* w taki sposób, że bierze zadania z singletonu Schedule'ra i odpala je o konkretnych porach.
*
* Np. co sekunde z kolekcji zadań sprawdza czas wykonania zadania
* i jeśli czas na te zadanie właśnie mija/minał,
* a zadanie się jeszcze nie wykonało,
* to je wykonuje.
*/
Runnable schedulerThread = new SchedulerThread();
new Thread(schedulerThread).start();
/**
* na zakończenie sprawdźmy co się stanie,
* jeśli 'zbuduję' jeszcze jedno zadanie
* i dodam je do Schedulera
*/
scheduler.build().forAction(()->System.out.println("chyba zaczynam to rozumieć"))
.useExecutionTimeProvider(Chron.builder().setMaxExecutionTimes(1).buildNextExecutionTimeProvider())
.onCompleted(()->System.out.println("Nie wierzę... działa!"))
.schedule();
new Thread(schedulerThread).start();
/**
* to jest tylko po to aby main sam nie kończyl się wykonywać.
*/
runForever();
}
private static void handleException(Throwable ex) {
System.out.println("Wystąpił błąd :(");
}
static void randomlyThrowException() throws Exception {
int nextInt = new Random().nextInt(10);
if(nextInt<2){
// System.out.println("O nie... coś się popsuło");
throw new Exception("O nie... coś się popsuło :(");
}
System.out.println("Działam sobie normalnie :)");
Thread.sleep(nextInt*100);
}
static void runForever(){
new Thread(()->{
while (true){
try {
Thread.currentThread().join();
//Thread.sleep(1000);
}catch (Exception ignored){}
}
}).start();
}
static void checkThisOut(){
IProvide<Person> janKowalskiProvider = Person.builder()
.setName("Jan")
.setSurname("Kowalski")
.buildPersonProvider();
Person janKowalski = janKowalskiProvider.provide();
}
}
class Person{
private String name;
private String surname;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public static PersonBuilder builder(){
return new PersonBuilder();
}
}
interface IProvide<T>{
T provide();
}
class PersonBuilder{
String name, surname;
public PersonBuilder setName(String name){
this.name = name;
return this;
}
public PersonBuilder setSurname(String surname){
this.surname = surname;
return this;
}
public IProvide<Person> buildPersonProvider()
{
return ()->{
Person p = new Person();
p.setName(name);
p.setSurname(surname);
return p;
};
}
}
| /**
* wykorzystajmy metodę,
* która co jakiś czas rzuca błedem
* jako implementacja powyższego interfejsu
*/ | package org.example;
import org.example.Chron.Chron;
import org.example.Chron.abstractions.IProvideNextExecutionTime;
import org.example.scheduler.SchedulerThread;
import org.example.scheduler.abstractions.ICatchException;
import org.example.scheduler.abstractions.IRunNotSafeAction;
import org.example.scheduler.Scheduler;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Random;
public class Main {
public static void main(String[] args) {
/**
* Zanim zaczniesz pisać kod,
* zajrzyj do kodu poniższej metody
* i spróbuj zrozumieć o co w niej chodzi.
* Jest tam przykład prostej implementacji
* wzorca zwanego "metodą wytwórczą",
* czasem zwaną "fabrykującą",
* oraz prostej implementacji wzorca projektowego "budowniczego".
*
* zrozumienie implementacji tej metody
* pomoże Tobie w rozwiązaniu następnych zadań.
*/
checkThisOut();
/**
* Utwórz nowy interfejs
* z zadeklarowaną metodą "provideTime".
* Jego implementacje później będą wykorzystywane
* do określania, kiedy mają być wywoływane
* konkretne operacje
*/
IProvideNextExecutionTime nextExecutionTimeProvider;
/**
* dodaj adnotację @FunctionalInterface
* nad nowoutworzonym interfejsem
* aby zaznaczyć, że będzie on używany
* z operatorem lambda.
*
* poniżej masz dwie przykładowe implementacje
* tego interfejsu w postaci wyrażeń (metod) lambda
*/
nextExecutionTimeProvider = LocalDateTime::now;
nextExecutionTimeProvider = () -> LocalDateTime.now();
/**
* Twoim pierwszym zadaniem jest napisanie
* klasy o nazwie "Chron",
* która jest przykładem prostej implementacji
* wzorca projektowego "budowniczego".
* Budowniczy w tym przykładzie zwraca metodę
* wytwórczą, która ma być implementacją wcześniej utworzonego interfejsu.
*
* Chodzi o taką implemntację tych wzorców,
* gdzie można ustawić:
* -> setStartTime: godzinę startu (domyślnie teraz)
* -> setEndTime: godzinę końca (domyślnie nigdy),
* -> setMaxExecutionTimes: ilość powtórzeń wykonania
* (czyli ile kolejnych godzin\czasów ma zwrócić - domyślnie ma wykonywać w nieskończoność),
* -> setIntervalDuration: odstęp czasowy między kolejnymi godzinami/ czasami (domyślnie 1 sekunda)
*
* Metoda buildNextTimeExecutionProvider ma zwracać lambdę,
* która generuje kolejną godzinę według wcześniej podanych parametrów
* UAWAGA !
* Najlepiej zrobić tak, aby klasa Chron implementowała "buildera" (budowniczego) - w sensie nie robić buildera jako odrębnej klasy
*/
IProvideNextExecutionTime<Chron> startsNowFor5SecondsMax5TimesWithDurationOf500Millis = Chron.builder()
.setStartTime(LocalDateTime.now())
.setEndDate(LocalDateTime.now().plusSeconds(5))
.setMaxExecutionTimes(5)
.setIntervalDuration(Duration.ofMillis(500))
.buildNextExecutionTimeProvider();
/**
* Super udało się - jestem pod wielkim wrażeniem ;-]
* W dalszej części programu bedziemy potrzebowali
* kolejnego interfejsu, który będzie wykorzystywany
* jako lambda, która może rzucić wyjątkiem (błędem)
*/
IRunNotSafeAction throwAnError = ()->{ throw new Exception(); };
try {
throwAnError.executeNotSafeAction();
System.out.println("tutaj powinien wystąpić błąd, a nie wystąpił :(");
return;
}catch (Exception ex){
}
/**
* wykorzystajmy metodę,
<SUF>*/
// IRunNotSafeAction randomlyThrowsAnError = () -> randomlyThrowException();
/* albo inaczej: */
IRunNotSafeAction randomlyThrowsAnErrorMethodReference = Main::randomlyThrowException;
/**
* Jeśli myslałeś, że poprzednie zadanie było łatwe,
* to ciekawe co powiesz o tym...
*
* Teraz mamy zdefiniowene dwa interfejsy:
* 1. IProvideNextExecutionTime - implementacja zwraca kolejną godzinę,
* według ustawień podanych w builderze
* 2. IRunNotSafeAction - implementacje tego interfejsu będą definiować zadanie,
* które będzie wykonywane przez harmonogram
*
* Czas na zaimplementowanie klasy Scheduler,
* która to właśnie będzie odpowiadać za wykonywanie zadań,
* o konkretnych porach.
*
* Ta klasa będzie mixem 2 wzorców projektowych:
* 1. singletonu - chcemy, aby był tylko jeden harmonogram,
* w którym będą przechowywane informacje o wszystkich zadaniach jakie mają być wykonane (Implementacje IRunNotSafeAction),
* oraz o metodzie lambda która zwraca kolejne czasy wykonania danego zadania (implementacja IProvideNextExecutionTime)
* 2. budowniczego:
* -> forAction: metoda do definiowania zadania do wykonania
* -> onError: metoda która przyjmuje lambdę, która to z kolei jako parametr ma przyjąć wyjątek, i jakoś go obsłużyć
* -> onSingleActionCompleted: przyjmuje lambdę, która definiuje co ma się stać po wykonaniu pojednyczego zadania
* -> onCompleted: przyjmuje lambdę, która definiuje co ma się stać gdy wszystkie zadania danego typu się zakończą
* -> schedule: zapisuje wszystkie powyższe dane do pewnej kolekcji
*
* UWAGA!
* W tym zadaniu pewnie będziesz musiał napisac kilka własnych klas/ inetrfejsów pomocniczych,
* których nie spotkasz w tym miejscu (tzn. w ciele funkcji main, w której aktualnie się znajdujemy)
*/
ICatchException iCatchException = (ex)->{
System.out.println(ex.getMessage());
};
Scheduler scheduler = Scheduler.getInstance();
scheduler.build()
.forAction(randomlyThrowsAnErrorMethodReference)
.useExecutionTimeProvider(startsNowFor5SecondsMax5TimesWithDurationOf500Millis)
.onError(iCatchException)
.onSingleActionCompleted(()->System.out.println("wykonano akcje z powodzeniem"))
.onCompleted(()->System.out.println("Zakończyłem pracę"))
.schedule();
/**
* Jeżeli już tutaj się znalazłeś i samemu rozwiązałeeś powyższe zadania,
* to wiedz, że drzemie w Tobie duży potencjał - tak trzymać !
*
* No to mamy już możliwość tworzenia harmonogramów zadań
* teraz przyda się nam jakiś wątek, który będzie mógł uruchamiać te zadania,
* w tle działania aplikacji
* Utwórz klasę SchedulerThread,
* która implementuje interfejs Runnable (ten interfejs jest utworzony w frameworku JAVY),
* w taki sposób, że bierze zadania z singletonu Schedule'ra i odpala je o konkretnych porach.
*
* Np. co sekunde z kolekcji zadań sprawdza czas wykonania zadania
* i jeśli czas na te zadanie właśnie mija/minał,
* a zadanie się jeszcze nie wykonało,
* to je wykonuje.
*/
Runnable schedulerThread = new SchedulerThread();
new Thread(schedulerThread).start();
/**
* na zakończenie sprawdźmy co się stanie,
* jeśli 'zbuduję' jeszcze jedno zadanie
* i dodam je do Schedulera
*/
scheduler.build().forAction(()->System.out.println("chyba zaczynam to rozumieć"))
.useExecutionTimeProvider(Chron.builder().setMaxExecutionTimes(1).buildNextExecutionTimeProvider())
.onCompleted(()->System.out.println("Nie wierzę... działa!"))
.schedule();
new Thread(schedulerThread).start();
/**
* to jest tylko po to aby main sam nie kończyl się wykonywać.
*/
runForever();
}
private static void handleException(Throwable ex) {
System.out.println("Wystąpił błąd :(");
}
static void randomlyThrowException() throws Exception {
int nextInt = new Random().nextInt(10);
if(nextInt<2){
// System.out.println("O nie... coś się popsuło");
throw new Exception("O nie... coś się popsuło :(");
}
System.out.println("Działam sobie normalnie :)");
Thread.sleep(nextInt*100);
}
static void runForever(){
new Thread(()->{
while (true){
try {
Thread.currentThread().join();
//Thread.sleep(1000);
}catch (Exception ignored){}
}
}).start();
}
static void checkThisOut(){
IProvide<Person> janKowalskiProvider = Person.builder()
.setName("Jan")
.setSurname("Kowalski")
.buildPersonProvider();
Person janKowalski = janKowalskiProvider.provide();
}
}
class Person{
private String name;
private String surname;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public static PersonBuilder builder(){
return new PersonBuilder();
}
}
interface IProvide<T>{
T provide();
}
class PersonBuilder{
String name, surname;
public PersonBuilder setName(String name){
this.name = name;
return this;
}
public PersonBuilder setSurname(String surname){
this.surname = surname;
return this;
}
public IProvide<Person> buildPersonProvider()
{
return ()->{
Person p = new Person();
p.setName(name);
p.setSurname(surname);
return p;
};
}
}
| null |
9532_1 | Michalas-Jomi/mimiRPG | 5,661 | Pierwszy/src/me/jomi/mimiRPG/PojedynczeKomendy/Targ.java | package me.jomi.mimiRPG.PojedynczeKomendy;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import com.google.common.collect.Lists;
import me.jomi.mimiRPG.Main;
import me.jomi.mimiRPG.Moduły.Moduł;
import me.jomi.mimiRPG.util.Config;
import me.jomi.mimiRPG.util.Func;
import me.jomi.mimiRPG.util.Komenda;
import me.jomi.mimiRPG.util.Krotka;
import me.jomi.mimiRPG.util.Przeładowalny;
import net.milkbowl.vault.economy.EconomyResponse;
@Moduł
public class Targ extends Komenda implements Listener, Przeładowalny {
private static ItemStack itemBrak = Func.stwórzItem(Material.BLACK_STAINED_GLASS_PANE, 1, "§6§2 ", null);
private static ItemStack itemBrakTowaru = Func.stwórzItem(Material.LIGHT_GRAY_STAINED_GLASS_PANE, 1, "§6§2 ", null);
private static ItemStack itemOdśwież = Func.dajGłówkę("§6Odśwież", "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZTg4N2NjMzg4YzhkY2ZjZjFiYThhYTVjM2MxMDJkY2U5Y2Y3YjFiNjNlNzg2YjM0ZDRmMWMzNzk2ZDNlOWQ2MSJ9fX0=");
private static ItemStack itemTowary = Func.dajGłówkę("§6Pokaż tylko własne towary", "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMThlZmE1YWM4NmVkYjdhYWQyNzFmYjE4YjRmNzg3ODVkMGY0OWFhOGZjNzMzM2FlMmRiY2JmY2E4NGIwOWI5ZiJ9fX0=");
private static ItemStack itemPoprzedniaStrona = Func.stwórzItem(Material.WRITABLE_BOOK, 1, "§6Poprzednia strona", null);
private static ItemStack itemNastępnaStrona = Func.stwórzItem(Material.WRITABLE_BOOK, 1, "§6Następna strona", null);
public static Config config = new Config("configi/targ");
private static List<ItemStack> Itemy = Lists.newArrayList();
private static HashMap<String, List<ItemStack>> menu = new HashMap<>();
private static HashMap<String, Integer> strony = new HashMap<>();
public static String prefix = Func.prefix("Targ");
private static List<String> gracze;
public static int maxCena = 10_000_000;
public Targ() {
super("wystaw", prefix + "/wystaw <cena> [ilość]");
ustawKomende("targ", null, null);
przeładuj();
}
@Override
@SuppressWarnings("unchecked")
public void przeładuj() {
config.przeładuj();
// wczytywanie graczy z pliku
gracze = (List<String>) config.wczytaj("gracze");
if (gracze == null)
gracze = Lists.newArrayList();
// wczytywanie itemów z pliku
Itemy = Lists.newArrayList();
for (String nick : gracze)
Itemy.addAll((List<ItemStack>) config.wczytaj(nick));
}
@Override
public Krotka<String, Object> raport() {
return Func.r("Itemy Targu", Itemy.size());
}
private static ItemStack przetwórzItem(ItemStack item, double cena, String gracz) {
ItemMeta meta = item.getItemMeta();
List<String> lore = Func.getLore(meta);
if (lore == null)
lore = Lists.newArrayList();
lore.add("");
lore.add("§6Cena: §e" + cena + "$");
lore.add("§6Sprzedawca: §e" + gracz);
Func.setLore(meta, lore);
item.setItemMeta(meta);
return item;
}
private static ItemStack odtwórzItem(ItemStack item) {
if (item == null) return null;
ItemMeta meta = item.getItemMeta();
List<String> lore = Func.getLore(meta);
int len = lore.size();
lore = lore.subList(0, len-3);
Func.setLore(meta, lore);
item.setItemMeta(meta);
return item;
}
private static boolean dajMenu(Player p) {
if (!Main.ekonomia) {
p.sendMessage(prefix + "Ta komenda nie działa poprawnie! wpisz §e/raport §6aby dowiedzieć się więcej");
return true;
}
Inventory inv = Func.createInventory(p, 6*9,"§6§lTarg");
List<ItemStack> lista = Lists.newArrayList();
lista.addAll(Itemy);
lista = Lists.reverse(lista);
menu.put(p.getName(), lista);
inv.setItem(49, itemOdśwież);
inv.setItem(46, itemTowary);
inv.setItem(45, itemPoprzedniaStrona);
inv.setItem(53, itemNastępnaStrona);
for (int i=47; i<9*6-1; i++)
if (inv.getItem(i) == null)
inv.setItem(i, itemBrak);
p.openInventory(inv);
zmieńStrone(p, 0, true);
return true;
}
private static void zmieńStrone(Player p, int strona, boolean pierwsze) {
if (strona < 0) return;
List<ItemStack> lista = menu.get(p.getName());
int max = lista.size();
if (!pierwsze)
if (strona*45 > max) return;
Inventory inv = p.getOpenInventory().getInventory(0);
strony.put(p.getName(), strona);
for (int i=0; i<5*9; i++)
inv.setItem(i, itemBrakTowaru);
for (int i=strona*45; i<(strona+1)*45; i++) {
if (i >= max)
break;
inv.setItem(i % 45, lista.get(i));
}
}
@SuppressWarnings({ "deprecation", "unchecked" })
private void kup(Player p, ItemStack item) {
if (!Itemy.contains(item)) {
p.sendMessage(prefix + "Tego przedmiotu nie ma już na targu");
return;
}
List<String> lore = item.getItemMeta().getLore();
int len = lore.size();
String sprzedawca = lore.get(len-1).split(" ")[1].substring(2);
if (sprzedawca.equals(p.getName())) {
Main.panelTakNie(p, "§4§lCzy napewno chcesz wycofać ofertę na §c" + Func.nazwaItemku(item), "§aTak", "§cNie", () -> wycofajItem(p, item), () -> {});
return;
}
String s = lore.get(len-2).split(" ")[1];
s = s.substring(2, s.length()-1);
double cena = Func.Double(s, -1);
if (cena > Main.econ.getBalance(p)) {
p.sendMessage(prefix + "Nie stać cię na to");
return;
}
if (p.getInventory().firstEmpty() == -1) {
p.sendMessage(prefix + "Nie masz wolnego miejsca w ekwipunku");
return;
}
Main.panelTakNie(p, "§4§lCzy napewno chcesz kupić §c" + Func.nazwaItemku(item), "§aTak§6, zapłacę " + cena + "$", "§cNie§6, dziękuję", () -> {
if (!Itemy.contains(item)) {
p.sendMessage(prefix + "Tego przedmiotu nie ma już na targu");
return;
}
EconomyResponse r = Main.econ.withdrawPlayer(p, cena);
Main.econ.depositPlayer(sprzedawca, cena);
if(r.transactionSuccess()) {
p.sendMessage(String.format(prefix + "Kupiłeś przedmiot od gracza §e%s§6 za §e%s$§6 zostało ci §e%s$", sprzedawca, Func.DoubleToString(r.amount), Func.DoubleToString(r.balance)));
Player sp = Bukkit.getPlayer(sprzedawca);
if (sp != null && sp.isOnline())
sp.sendMessage(String.format(prefix + "Gracz §e%s§6 kupił od ciebie przedmiot za §e%s$", p.getName(), Func.DoubleToString(r.amount)));
} else {
p.sendMessage(String.format(prefix + "Wystąpił problem: §c%s", r.errorMessage));
return;
}
Itemy.remove(item);
List<ItemStack> of = (List<ItemStack>) config.wczytaj(sprzedawca);
of.remove(item);
if (of.size() == 0) {
gracze.remove(sprzedawca);
config.ustaw("gracze", gracze);
config.ustaw_zapisz(sprzedawca, null);
} else
config.ustaw_zapisz(sprzedawca, of);
p.getInventory().addItem(odtwórzItem(item));
odświeżOferte(p);
}, () -> {});
}
@SuppressWarnings({ "deprecation", "unchecked" })
private static void wystawItem(Player p, double cena) {
ItemStack item = p.getItemInHand();
String nick = p.getName();
if (item == null || item.getType().equals(Material.AIR))
{p.sendMessage(prefix + "Musisz trzymać coś w ręce aby tego użyć"); return;}
if (cena < 1)
{p.sendMessage(prefix + "Nie możesz sprzedać nic za mniej niż §e1$"); return;}
if (cena > maxCena)
{p.sendMessage(prefix + "Nie możesz sprzedać nic za więcej niż §e" + maxCena + "$"); return;}
List<ItemStack> oferty = (List<ItemStack>) config.wczytaj(nick);
if (oferty == null)
oferty = Lists.newArrayList();
if (oferty.size() >= limitOfert(p))
{p.sendMessage(prefix + "Osiągnięto już limit ofert"); return;}
if (!gracze.contains(nick)) {
gracze.add(nick);
config.ustaw_zapisz("gracze", gracze);
}
item = przetwórzItem(item, cena, nick);
Itemy.add(item);
oferty.add(item);
config.ustaw_zapisz(nick, oferty);
p.setItemInHand(new ItemStack(Material.AIR));
p.sendMessage(prefix + "Wystawiono item za §e" + Func.DoubleToString(cena) + "$");
}
private static final Pattern limitOfertPattern = Pattern.compile("mimirpg\\.targ\\.limit\\.(\\d+)");
public static int limitOfert(Player p) {
AtomicInteger ai = new AtomicInteger(0);
p.getEffectivePermissions().forEach(perm -> {
if (perm.getValue()) {
Matcher matcher = limitOfertPattern.matcher(perm.getPermission());
if (matcher.matches())
ai.set(Math.max(ai.get(), Func.Int(matcher.group(1))));
}
});
return ai.get();
}
@SuppressWarnings("unchecked")
private void wycofajItem(Player p, ItemStack item) {
if (p.getInventory().firstEmpty() == -1)
{p.sendMessage(prefix + "Twój ekwipunek jest pełny"); return;}
String nick = p.getName();
List<ItemStack> oferty = (List<ItemStack>) config.wczytaj(nick);
if (!oferty.remove(item))
{p.sendMessage(prefix + "Tej oferty nie ma już na rynku"); return;};
if (oferty.size() == 0) {
gracze.remove(nick);
config.ustaw("gracze", gracze);
config.ustaw_zapisz(nick, null);
} else
config.ustaw_zapisz(nick, oferty);
Itemy.remove(item);
p.sendMessage(prefix + "Wycofano item");
p.getInventory().addItem(odtwórzItem(item));
if (Func.getTitle(p.getOpenInventory()).equals("§6§lTwoje oferty"))
pokażSwojeOferty(p);
else
odświeżOferte(p);
}
private void odświeżOferte(Player p) {
dajMenu(p);
}
@SuppressWarnings("unchecked")
private void pokażSwojeOferty(Player p) {
Inventory inv = Func.createInventory(p, 18, "§6§lTwoje oferty");
ItemStack nic = Func.stwórzItem(Material.LIGHT_GRAY_STAINED_GLASS_PANE, 1, "§aKliknij item aby go wycofać", null);
for (int i=0; i<17; i++)
inv.setItem(i, nic);
int i = 0;
List<ItemStack> lista = (List<ItemStack>) config.wczytaj(p.getName());
if (lista != null) {
for (ItemStack item : lista) {
inv.setItem(i, item);
i++;
}
}
inv.setItem(17, Func.dajGłówkę("§6Powrót do targu", "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvODY1MmUyYjkzNmNhODAyNmJkMjg2NTFkN2M5ZjI4MTlkMmU5MjM2OTc3MzRkMThkZmRiMTM1NTBmOGZkYWQ1ZiJ9fX0="));
p.openInventory(inv);
}
@EventHandler
public void kliknięcie(InventoryClickEvent ev) {
Player p = (Player) ev.getWhoClicked();
ItemStack item = ev.getCurrentItem();
int slot = ev.getRawSlot();
switch (Func.getTitle(ev.getView())) {
case "§6§lTarg":
if (slot >= 6*9 || slot < 0) return;
ev.setCancelled(true);
String nazwa = Func.nazwaItemku(item);
if (item.isSimilar(itemBrakTowaru)) return;
if (slot < 5*9) {kup(p, item); return;}
switch(nazwa) {
case "§6Poprzednia strona":
zmieńStrone(p, strony.get(p.getName())-1, false);
break;
case "§6Następna strona":
zmieńStrone(p, strony.get(p.getName())+1, false);
break;
case "§6Odśwież":
odświeżOferte(p);
break;
case "§6Pokaż tylko własne towary":
pokażSwojeOferty(p);
break;
}
return;
case "§6§lTwoje oferty":
if (slot >= 18 || slot < 0) return;
ev.setCancelled(true);
if (slot == 17)
dajMenu(p);
else if (!Func.nazwaItemku(item).equals("§aKliknij item aby go wycofać"))
wycofajItem(p, item);
return;
}
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] args) {
return Lists.newArrayList();
}
@Override
public boolean wykonajKomende(CommandSender sender, Command cmd, String label, String[] args) {
if (!(sender instanceof Player))
return Func.powiadom(sender, prefix + "Targ to nie miejsce dla ciebie");
Player p = (Player) sender;
if (cmd.getName().equalsIgnoreCase("targ"))
return dajMenu(p);
if (args.length < 1) return false;
String cena = args[0];
if (!Main.ekonomia) {
p.sendMessage(prefix + "Ta komenda nie działa poprawnie! wpisz §e/raport §6aby dowiedzieć się więcej");
return true;
}
double koszt = Func.Double(cena, -1);
if (koszt == -1) {
p.sendMessage(prefix + "Niepoprawna liczba: " + cena);
return true;
}
wystawItem(p, koszt);
return true;
}
}
| // wczytywanie itemów z pliku
| package me.jomi.mimiRPG.PojedynczeKomendy;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import com.google.common.collect.Lists;
import me.jomi.mimiRPG.Main;
import me.jomi.mimiRPG.Moduły.Moduł;
import me.jomi.mimiRPG.util.Config;
import me.jomi.mimiRPG.util.Func;
import me.jomi.mimiRPG.util.Komenda;
import me.jomi.mimiRPG.util.Krotka;
import me.jomi.mimiRPG.util.Przeładowalny;
import net.milkbowl.vault.economy.EconomyResponse;
@Moduł
public class Targ extends Komenda implements Listener, Przeładowalny {
private static ItemStack itemBrak = Func.stwórzItem(Material.BLACK_STAINED_GLASS_PANE, 1, "§6§2 ", null);
private static ItemStack itemBrakTowaru = Func.stwórzItem(Material.LIGHT_GRAY_STAINED_GLASS_PANE, 1, "§6§2 ", null);
private static ItemStack itemOdśwież = Func.dajGłówkę("§6Odśwież", "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZTg4N2NjMzg4YzhkY2ZjZjFiYThhYTVjM2MxMDJkY2U5Y2Y3YjFiNjNlNzg2YjM0ZDRmMWMzNzk2ZDNlOWQ2MSJ9fX0=");
private static ItemStack itemTowary = Func.dajGłówkę("§6Pokaż tylko własne towary", "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMThlZmE1YWM4NmVkYjdhYWQyNzFmYjE4YjRmNzg3ODVkMGY0OWFhOGZjNzMzM2FlMmRiY2JmY2E4NGIwOWI5ZiJ9fX0=");
private static ItemStack itemPoprzedniaStrona = Func.stwórzItem(Material.WRITABLE_BOOK, 1, "§6Poprzednia strona", null);
private static ItemStack itemNastępnaStrona = Func.stwórzItem(Material.WRITABLE_BOOK, 1, "§6Następna strona", null);
public static Config config = new Config("configi/targ");
private static List<ItemStack> Itemy = Lists.newArrayList();
private static HashMap<String, List<ItemStack>> menu = new HashMap<>();
private static HashMap<String, Integer> strony = new HashMap<>();
public static String prefix = Func.prefix("Targ");
private static List<String> gracze;
public static int maxCena = 10_000_000;
public Targ() {
super("wystaw", prefix + "/wystaw <cena> [ilość]");
ustawKomende("targ", null, null);
przeładuj();
}
@Override
@SuppressWarnings("unchecked")
public void przeładuj() {
config.przeładuj();
// wczytywanie graczy z pliku
gracze = (List<String>) config.wczytaj("gracze");
if (gracze == null)
gracze = Lists.newArrayList();
// wczytywanie itemów <SUF>
Itemy = Lists.newArrayList();
for (String nick : gracze)
Itemy.addAll((List<ItemStack>) config.wczytaj(nick));
}
@Override
public Krotka<String, Object> raport() {
return Func.r("Itemy Targu", Itemy.size());
}
private static ItemStack przetwórzItem(ItemStack item, double cena, String gracz) {
ItemMeta meta = item.getItemMeta();
List<String> lore = Func.getLore(meta);
if (lore == null)
lore = Lists.newArrayList();
lore.add("");
lore.add("§6Cena: §e" + cena + "$");
lore.add("§6Sprzedawca: §e" + gracz);
Func.setLore(meta, lore);
item.setItemMeta(meta);
return item;
}
private static ItemStack odtwórzItem(ItemStack item) {
if (item == null) return null;
ItemMeta meta = item.getItemMeta();
List<String> lore = Func.getLore(meta);
int len = lore.size();
lore = lore.subList(0, len-3);
Func.setLore(meta, lore);
item.setItemMeta(meta);
return item;
}
private static boolean dajMenu(Player p) {
if (!Main.ekonomia) {
p.sendMessage(prefix + "Ta komenda nie działa poprawnie! wpisz §e/raport §6aby dowiedzieć się więcej");
return true;
}
Inventory inv = Func.createInventory(p, 6*9,"§6§lTarg");
List<ItemStack> lista = Lists.newArrayList();
lista.addAll(Itemy);
lista = Lists.reverse(lista);
menu.put(p.getName(), lista);
inv.setItem(49, itemOdśwież);
inv.setItem(46, itemTowary);
inv.setItem(45, itemPoprzedniaStrona);
inv.setItem(53, itemNastępnaStrona);
for (int i=47; i<9*6-1; i++)
if (inv.getItem(i) == null)
inv.setItem(i, itemBrak);
p.openInventory(inv);
zmieńStrone(p, 0, true);
return true;
}
private static void zmieńStrone(Player p, int strona, boolean pierwsze) {
if (strona < 0) return;
List<ItemStack> lista = menu.get(p.getName());
int max = lista.size();
if (!pierwsze)
if (strona*45 > max) return;
Inventory inv = p.getOpenInventory().getInventory(0);
strony.put(p.getName(), strona);
for (int i=0; i<5*9; i++)
inv.setItem(i, itemBrakTowaru);
for (int i=strona*45; i<(strona+1)*45; i++) {
if (i >= max)
break;
inv.setItem(i % 45, lista.get(i));
}
}
@SuppressWarnings({ "deprecation", "unchecked" })
private void kup(Player p, ItemStack item) {
if (!Itemy.contains(item)) {
p.sendMessage(prefix + "Tego przedmiotu nie ma już na targu");
return;
}
List<String> lore = item.getItemMeta().getLore();
int len = lore.size();
String sprzedawca = lore.get(len-1).split(" ")[1].substring(2);
if (sprzedawca.equals(p.getName())) {
Main.panelTakNie(p, "§4§lCzy napewno chcesz wycofać ofertę na §c" + Func.nazwaItemku(item), "§aTak", "§cNie", () -> wycofajItem(p, item), () -> {});
return;
}
String s = lore.get(len-2).split(" ")[1];
s = s.substring(2, s.length()-1);
double cena = Func.Double(s, -1);
if (cena > Main.econ.getBalance(p)) {
p.sendMessage(prefix + "Nie stać cię na to");
return;
}
if (p.getInventory().firstEmpty() == -1) {
p.sendMessage(prefix + "Nie masz wolnego miejsca w ekwipunku");
return;
}
Main.panelTakNie(p, "§4§lCzy napewno chcesz kupić §c" + Func.nazwaItemku(item), "§aTak§6, zapłacę " + cena + "$", "§cNie§6, dziękuję", () -> {
if (!Itemy.contains(item)) {
p.sendMessage(prefix + "Tego przedmiotu nie ma już na targu");
return;
}
EconomyResponse r = Main.econ.withdrawPlayer(p, cena);
Main.econ.depositPlayer(sprzedawca, cena);
if(r.transactionSuccess()) {
p.sendMessage(String.format(prefix + "Kupiłeś przedmiot od gracza §e%s§6 za §e%s$§6 zostało ci §e%s$", sprzedawca, Func.DoubleToString(r.amount), Func.DoubleToString(r.balance)));
Player sp = Bukkit.getPlayer(sprzedawca);
if (sp != null && sp.isOnline())
sp.sendMessage(String.format(prefix + "Gracz §e%s§6 kupił od ciebie przedmiot za §e%s$", p.getName(), Func.DoubleToString(r.amount)));
} else {
p.sendMessage(String.format(prefix + "Wystąpił problem: §c%s", r.errorMessage));
return;
}
Itemy.remove(item);
List<ItemStack> of = (List<ItemStack>) config.wczytaj(sprzedawca);
of.remove(item);
if (of.size() == 0) {
gracze.remove(sprzedawca);
config.ustaw("gracze", gracze);
config.ustaw_zapisz(sprzedawca, null);
} else
config.ustaw_zapisz(sprzedawca, of);
p.getInventory().addItem(odtwórzItem(item));
odświeżOferte(p);
}, () -> {});
}
@SuppressWarnings({ "deprecation", "unchecked" })
private static void wystawItem(Player p, double cena) {
ItemStack item = p.getItemInHand();
String nick = p.getName();
if (item == null || item.getType().equals(Material.AIR))
{p.sendMessage(prefix + "Musisz trzymać coś w ręce aby tego użyć"); return;}
if (cena < 1)
{p.sendMessage(prefix + "Nie możesz sprzedać nic za mniej niż §e1$"); return;}
if (cena > maxCena)
{p.sendMessage(prefix + "Nie możesz sprzedać nic za więcej niż §e" + maxCena + "$"); return;}
List<ItemStack> oferty = (List<ItemStack>) config.wczytaj(nick);
if (oferty == null)
oferty = Lists.newArrayList();
if (oferty.size() >= limitOfert(p))
{p.sendMessage(prefix + "Osiągnięto już limit ofert"); return;}
if (!gracze.contains(nick)) {
gracze.add(nick);
config.ustaw_zapisz("gracze", gracze);
}
item = przetwórzItem(item, cena, nick);
Itemy.add(item);
oferty.add(item);
config.ustaw_zapisz(nick, oferty);
p.setItemInHand(new ItemStack(Material.AIR));
p.sendMessage(prefix + "Wystawiono item za §e" + Func.DoubleToString(cena) + "$");
}
private static final Pattern limitOfertPattern = Pattern.compile("mimirpg\\.targ\\.limit\\.(\\d+)");
public static int limitOfert(Player p) {
AtomicInteger ai = new AtomicInteger(0);
p.getEffectivePermissions().forEach(perm -> {
if (perm.getValue()) {
Matcher matcher = limitOfertPattern.matcher(perm.getPermission());
if (matcher.matches())
ai.set(Math.max(ai.get(), Func.Int(matcher.group(1))));
}
});
return ai.get();
}
@SuppressWarnings("unchecked")
private void wycofajItem(Player p, ItemStack item) {
if (p.getInventory().firstEmpty() == -1)
{p.sendMessage(prefix + "Twój ekwipunek jest pełny"); return;}
String nick = p.getName();
List<ItemStack> oferty = (List<ItemStack>) config.wczytaj(nick);
if (!oferty.remove(item))
{p.sendMessage(prefix + "Tej oferty nie ma już na rynku"); return;};
if (oferty.size() == 0) {
gracze.remove(nick);
config.ustaw("gracze", gracze);
config.ustaw_zapisz(nick, null);
} else
config.ustaw_zapisz(nick, oferty);
Itemy.remove(item);
p.sendMessage(prefix + "Wycofano item");
p.getInventory().addItem(odtwórzItem(item));
if (Func.getTitle(p.getOpenInventory()).equals("§6§lTwoje oferty"))
pokażSwojeOferty(p);
else
odświeżOferte(p);
}
private void odświeżOferte(Player p) {
dajMenu(p);
}
@SuppressWarnings("unchecked")
private void pokażSwojeOferty(Player p) {
Inventory inv = Func.createInventory(p, 18, "§6§lTwoje oferty");
ItemStack nic = Func.stwórzItem(Material.LIGHT_GRAY_STAINED_GLASS_PANE, 1, "§aKliknij item aby go wycofać", null);
for (int i=0; i<17; i++)
inv.setItem(i, nic);
int i = 0;
List<ItemStack> lista = (List<ItemStack>) config.wczytaj(p.getName());
if (lista != null) {
for (ItemStack item : lista) {
inv.setItem(i, item);
i++;
}
}
inv.setItem(17, Func.dajGłówkę("§6Powrót do targu", "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvODY1MmUyYjkzNmNhODAyNmJkMjg2NTFkN2M5ZjI4MTlkMmU5MjM2OTc3MzRkMThkZmRiMTM1NTBmOGZkYWQ1ZiJ9fX0="));
p.openInventory(inv);
}
@EventHandler
public void kliknięcie(InventoryClickEvent ev) {
Player p = (Player) ev.getWhoClicked();
ItemStack item = ev.getCurrentItem();
int slot = ev.getRawSlot();
switch (Func.getTitle(ev.getView())) {
case "§6§lTarg":
if (slot >= 6*9 || slot < 0) return;
ev.setCancelled(true);
String nazwa = Func.nazwaItemku(item);
if (item.isSimilar(itemBrakTowaru)) return;
if (slot < 5*9) {kup(p, item); return;}
switch(nazwa) {
case "§6Poprzednia strona":
zmieńStrone(p, strony.get(p.getName())-1, false);
break;
case "§6Następna strona":
zmieńStrone(p, strony.get(p.getName())+1, false);
break;
case "§6Odśwież":
odświeżOferte(p);
break;
case "§6Pokaż tylko własne towary":
pokażSwojeOferty(p);
break;
}
return;
case "§6§lTwoje oferty":
if (slot >= 18 || slot < 0) return;
ev.setCancelled(true);
if (slot == 17)
dajMenu(p);
else if (!Func.nazwaItemku(item).equals("§aKliknij item aby go wycofać"))
wycofajItem(p, item);
return;
}
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] args) {
return Lists.newArrayList();
}
@Override
public boolean wykonajKomende(CommandSender sender, Command cmd, String label, String[] args) {
if (!(sender instanceof Player))
return Func.powiadom(sender, prefix + "Targ to nie miejsce dla ciebie");
Player p = (Player) sender;
if (cmd.getName().equalsIgnoreCase("targ"))
return dajMenu(p);
if (args.length < 1) return false;
String cena = args[0];
if (!Main.ekonomia) {
p.sendMessage(prefix + "Ta komenda nie działa poprawnie! wpisz §e/raport §6aby dowiedzieć się więcej");
return true;
}
double koszt = Func.Double(cena, -1);
if (koszt == -1) {
p.sendMessage(prefix + "Niepoprawna liczba: " + cena);
return true;
}
wystawItem(p, koszt);
return true;
}
}
| null |
5082_2 | MikeCbl/Klub | 1,782 | Klub_Strzelecki/src/main/java/Klub/Guns.java | package Klub;
import Klub.DbConnection.DbConn;
import io.github.palexdev.materialfx.controls.MFXButton;
import io.github.palexdev.materialfx.controls.MFXFilterComboBox;
import io.github.palexdev.materialfx.controls.MFXTextField;
import io.github.palexdev.materialfx.validation.Constraint;
import io.github.palexdev.materialfx.validation.Severity;
import javafx.beans.binding.Bindings;
import javafx.css.PseudoClass;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Window;
import java.net.URL;
import java.sql.SQLException;
import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.atomic.AtomicBoolean;
import static io.github.palexdev.materialfx.utils.StringUtils.containsAll;
import static io.github.palexdev.materialfx.utils.StringUtils.containsAny;
public class Guns implements Initializable {
@FXML
private MFXTextField brand_gun;
@FXML
private MFXTextField caliber_gun;
@FXML
private MFXTextField kind_gun;
@FXML
private MFXTextField number_gun;
@FXML
private MFXTextField productionDate_gun;
@FXML
private MFXFilterComboBox<String> type_gun_combo;
@FXML
private MFXButton gun_insertion;
@FXML
private Label validationLabelKind;
@FXML
private Label validationLabelBrand;
@FXML
private Label validationLabelNumber;
@FXML
private Label validationLabelYear;
@FXML
private Label validationLabelCal;
//Editable
private Boolean IsEditable = Boolean.FALSE;
DbConn connect;
//lista typów broni
String[] typeList = {"","Sportowa", "Półautomatyczna", "Samopowtarzalna", "Gładkolufowa", "Czarnoprochowa"};
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
connect = DbConn.getInstance();
type_gun_combo.getItems().addAll(typeList);
runValidation();
}
public void runValidation(){
ValidationUtil.addValidation(kind_gun, validationLabelKind, "textField");
ValidationUtil.addValidation(brand_gun, validationLabelBrand, "textField");
ValidationUtil.addValidation(number_gun, validationLabelNumber, "nr_fab");
ValidationUtil.addValidation(productionDate_gun, validationLabelYear, "year");
ValidationUtil.addValidation(caliber_gun, validationLabelCal, "empty");
}
public void GunInserted(ActionEvent actionEvent) throws SQLException {
Window owner = gun_insertion.getScene().getWindow();
// runValidation();
if (!kind_gun.isValid()) {
showAlert(Alert.AlertType.ERROR, owner, "Form Error!",
"Proszę poprawić błędy");
return;
}
if (!brand_gun.isValid()) {
showAlert(Alert.AlertType.ERROR, owner, "Form Error!",
"Proszę poprawić błędy");
return;
}if(!number_gun.isValid()) {
showAlert(Alert.AlertType.ERROR, owner, "Form Error!",
"Proszę poprawić numer fabryczny");
return;
}if(!productionDate_gun.isValid()) {
showAlert(Alert.AlertType.ERROR, owner, "Form Error!",
"Proszę poprawić rok produkcji");
return;
}if(!caliber_gun.isValid()) {
showAlert(Alert.AlertType.ERROR, owner, "Form Error!",
"Proszę poprawić kaliber");
return;
}
// if(kind_gun.getText().isEmpty()) {
// showAlert(Alert.AlertType.ERROR, owner, "Form Error!",
// "Proszę podać Rodzaj");
// return;
// }
//Edit check
if(IsEditable){
handleEditMethod();
return;
}
String kind = kind_gun.getText();
String type = type_gun_combo.getValue();
String brand = brand_gun.getText();
String caliber = caliber_gun.getText();
String number = number_gun.getText();
String productionDate = productionDate_gun.getText();
int flag = connect.insert_Guns_query_Executer(kind,type,brand,caliber,number,productionDate);
if(flag == 1){
infoBox("Dodano broń!", null, "Ok");
}
else{
infoBox("nie powiodło się", null, "Błąd");
}
}
public void UpdateInformation(GunsCollection.Guns gun){
kind_gun.setText(gun.getKind());
type_gun_combo.setText(gun.getType());
brand_gun.setText(gun.getBrand());
caliber_gun.setText(gun.getCaliber());
number_gun.setText(gun.getNumber());
productionDate_gun.setText(gun.getProductionDate());
number_gun.setEditable(false);
number_gun.setDisable(true);
IsEditable = Boolean.TRUE;
}
public String timestamp(){
return "";
}
//update query for edit
private void handleEditMethod() {
GunsCollection.Guns gun = new GunsCollection.Guns(kind_gun.getText(),type_gun_combo.getText(),brand_gun.getText(),caliber_gun.getText(),number_gun.getText(),productionDate_gun.getText(),timestamp(),true);
if(connect.updateGun(gun)){
AlertMaker.showAlert("Ok!!","Broń edytowana");
System.out.println(timestamp());
}else{
AlertMaker.showError("Błąd!","Edycja nie powiodła się!");
}
}
private static void showAlert(Alert.AlertType alertType, Window owner, String title, String message) {
Alert alert = new Alert(alertType);
alert.setTitle(title);
alert.setHeaderText(null);
alert.setContentText(message);
alert.initOwner(owner);
alert.show();
}
private static void infoBox(String infoMessage, String headerText, String title){
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setContentText(infoMessage);
alert.setTitle(title);
alert.setHeaderText(headerText);
alert.showAndWait();
}
}
| // "Proszę podać Rodzaj"); | package Klub;
import Klub.DbConnection.DbConn;
import io.github.palexdev.materialfx.controls.MFXButton;
import io.github.palexdev.materialfx.controls.MFXFilterComboBox;
import io.github.palexdev.materialfx.controls.MFXTextField;
import io.github.palexdev.materialfx.validation.Constraint;
import io.github.palexdev.materialfx.validation.Severity;
import javafx.beans.binding.Bindings;
import javafx.css.PseudoClass;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Window;
import java.net.URL;
import java.sql.SQLException;
import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.atomic.AtomicBoolean;
import static io.github.palexdev.materialfx.utils.StringUtils.containsAll;
import static io.github.palexdev.materialfx.utils.StringUtils.containsAny;
public class Guns implements Initializable {
@FXML
private MFXTextField brand_gun;
@FXML
private MFXTextField caliber_gun;
@FXML
private MFXTextField kind_gun;
@FXML
private MFXTextField number_gun;
@FXML
private MFXTextField productionDate_gun;
@FXML
private MFXFilterComboBox<String> type_gun_combo;
@FXML
private MFXButton gun_insertion;
@FXML
private Label validationLabelKind;
@FXML
private Label validationLabelBrand;
@FXML
private Label validationLabelNumber;
@FXML
private Label validationLabelYear;
@FXML
private Label validationLabelCal;
//Editable
private Boolean IsEditable = Boolean.FALSE;
DbConn connect;
//lista typów broni
String[] typeList = {"","Sportowa", "Półautomatyczna", "Samopowtarzalna", "Gładkolufowa", "Czarnoprochowa"};
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
connect = DbConn.getInstance();
type_gun_combo.getItems().addAll(typeList);
runValidation();
}
public void runValidation(){
ValidationUtil.addValidation(kind_gun, validationLabelKind, "textField");
ValidationUtil.addValidation(brand_gun, validationLabelBrand, "textField");
ValidationUtil.addValidation(number_gun, validationLabelNumber, "nr_fab");
ValidationUtil.addValidation(productionDate_gun, validationLabelYear, "year");
ValidationUtil.addValidation(caliber_gun, validationLabelCal, "empty");
}
public void GunInserted(ActionEvent actionEvent) throws SQLException {
Window owner = gun_insertion.getScene().getWindow();
// runValidation();
if (!kind_gun.isValid()) {
showAlert(Alert.AlertType.ERROR, owner, "Form Error!",
"Proszę poprawić błędy");
return;
}
if (!brand_gun.isValid()) {
showAlert(Alert.AlertType.ERROR, owner, "Form Error!",
"Proszę poprawić błędy");
return;
}if(!number_gun.isValid()) {
showAlert(Alert.AlertType.ERROR, owner, "Form Error!",
"Proszę poprawić numer fabryczny");
return;
}if(!productionDate_gun.isValid()) {
showAlert(Alert.AlertType.ERROR, owner, "Form Error!",
"Proszę poprawić rok produkcji");
return;
}if(!caliber_gun.isValid()) {
showAlert(Alert.AlertType.ERROR, owner, "Form Error!",
"Proszę poprawić kaliber");
return;
}
// if(kind_gun.getText().isEmpty()) {
// showAlert(Alert.AlertType.ERROR, owner, "Form Error!",
// "Proszę podać <SUF>
// return;
// }
//Edit check
if(IsEditable){
handleEditMethod();
return;
}
String kind = kind_gun.getText();
String type = type_gun_combo.getValue();
String brand = brand_gun.getText();
String caliber = caliber_gun.getText();
String number = number_gun.getText();
String productionDate = productionDate_gun.getText();
int flag = connect.insert_Guns_query_Executer(kind,type,brand,caliber,number,productionDate);
if(flag == 1){
infoBox("Dodano broń!", null, "Ok");
}
else{
infoBox("nie powiodło się", null, "Błąd");
}
}
public void UpdateInformation(GunsCollection.Guns gun){
kind_gun.setText(gun.getKind());
type_gun_combo.setText(gun.getType());
brand_gun.setText(gun.getBrand());
caliber_gun.setText(gun.getCaliber());
number_gun.setText(gun.getNumber());
productionDate_gun.setText(gun.getProductionDate());
number_gun.setEditable(false);
number_gun.setDisable(true);
IsEditable = Boolean.TRUE;
}
public String timestamp(){
return "";
}
//update query for edit
private void handleEditMethod() {
GunsCollection.Guns gun = new GunsCollection.Guns(kind_gun.getText(),type_gun_combo.getText(),brand_gun.getText(),caliber_gun.getText(),number_gun.getText(),productionDate_gun.getText(),timestamp(),true);
if(connect.updateGun(gun)){
AlertMaker.showAlert("Ok!!","Broń edytowana");
System.out.println(timestamp());
}else{
AlertMaker.showError("Błąd!","Edycja nie powiodła się!");
}
}
private static void showAlert(Alert.AlertType alertType, Window owner, String title, String message) {
Alert alert = new Alert(alertType);
alert.setTitle(title);
alert.setHeaderText(null);
alert.setContentText(message);
alert.initOwner(owner);
alert.show();
}
private static void infoBox(String infoMessage, String headerText, String title){
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setContentText(infoMessage);
alert.setTitle(title);
alert.setHeaderText(headerText);
alert.showAndWait();
}
}
| null |
4463_0 | MiloszBuchacz/Battle-Ship | 551 | ComputerBattle.java | import java.util.concurrent.TimeUnit;
//Tutaj nie pojawiaja sie w ogole strzaly i wszystko leci za szybko
public class ComputerBattle {
private Ship[] shipsObj = {new Ship(4, "B"), new Ship(3, "C"), new Ship(3, "S"), new Ship(2, "D"), new Ship(5, "Y")};
private Ship[] shipsObj2 = {new Ship(4, "B"), new Ship(3, "C"), new Ship(3, "S"), new Ship(2, "D"), new Ship(5, "Y")};
public void computerBattle() {
Ocean ocean = new Ocean(15, 15);
Ocean oceanEnemy = new Ocean(15, 15);
ocean.fillOcean();
for (int i =0; i < shipsObj.length; i++) {
ocean.placeShip(shipsObj[i]);
}
oceanEnemy.fillOcean();
for (int i =0; i < shipsObj2.length; i++) {
oceanEnemy.placeShip(shipsObj2[i]);
}
System.out.println("Computer 1 board:");
while (true){
System.out.println("Score: " + ocean.score);
ocean.printOcean();
ocean.placeRandomShoot();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Score enemy: " + oceanEnemy.score);
oceanEnemy.printOcean();
oceanEnemy.placeRandomShoot();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (ocean.score > 1 ) {
System.out.println("Computer 1 won!!!");
break;
}
if (oceanEnemy.score > 1) {
System.out.println("Computer 2 won!!!");
break;
}
}
}
} | //Tutaj nie pojawiaja sie w ogole strzaly i wszystko leci za szybko | import java.util.concurrent.TimeUnit;
//Tutaj nie <SUF>
public class ComputerBattle {
private Ship[] shipsObj = {new Ship(4, "B"), new Ship(3, "C"), new Ship(3, "S"), new Ship(2, "D"), new Ship(5, "Y")};
private Ship[] shipsObj2 = {new Ship(4, "B"), new Ship(3, "C"), new Ship(3, "S"), new Ship(2, "D"), new Ship(5, "Y")};
public void computerBattle() {
Ocean ocean = new Ocean(15, 15);
Ocean oceanEnemy = new Ocean(15, 15);
ocean.fillOcean();
for (int i =0; i < shipsObj.length; i++) {
ocean.placeShip(shipsObj[i]);
}
oceanEnemy.fillOcean();
for (int i =0; i < shipsObj2.length; i++) {
oceanEnemy.placeShip(shipsObj2[i]);
}
System.out.println("Computer 1 board:");
while (true){
System.out.println("Score: " + ocean.score);
ocean.printOcean();
ocean.placeRandomShoot();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Score enemy: " + oceanEnemy.score);
oceanEnemy.printOcean();
oceanEnemy.placeRandomShoot();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (ocean.score > 1 ) {
System.out.println("Computer 1 won!!!");
break;
}
if (oceanEnemy.score > 1) {
System.out.println("Computer 2 won!!!");
break;
}
}
}
} | null |
3928_0 | MiloszCzaniecki/CivilizationArena | 544 | src/Cywilizacja.java | package src;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static java.lang.Thread.sleep;
public class Cywilizacja {
public static void main(String[] args) throws InterruptedException {
//próbowałem usilnie dodać jakoś mechanikę sprawdzania do kogo należy dany punkt
//wewnątrz klas, ale niestety się nie dało :/// więc improwizuję w taki sposób
List<State> stateList = new ArrayList<>();//ale widziałem że to normalne, że trzeba użyć tego typu listy
Map map = new Map(10,10); //więc może i jest git
State Wro = new State(new int[]{0,0},10,100,100);
State Wwa = new State(new int[]{4,4},100,100,100);
stateList.add(Wro);
stateList.add(Wwa);
//testy eksploracji
TextGUI GUI = new TextGUI();
for(int i=0;i<1000;i++) //próby\
{
map.ExplorationTick(stateList);
/*
System.out.println("tick"+i);
System.out.println("Wrocław");
map.OUTTEXTPOINTSCMD(Wro);
System.out.println("Warszawa");
map.OUTTEXTPOINTSCMD(Wwa);
System.out.println();
*/
GUI.gui(Wro, Wwa,map);
sleep(100);
for(int n=0;n!=300;n++)
{
System.out.println();
}
}
GUI.gui(Wro, Wwa,map);
sleep(100);
// map.CMDPOINTREADER(G.GeneratePointOutOf(10,10,Wro));
}
}
| //próbowałem usilnie dodać jakoś mechanikę sprawdzania do kogo należy dany punkt | package src;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static java.lang.Thread.sleep;
public class Cywilizacja {
public static void main(String[] args) throws InterruptedException {
//próbowałem usilnie <SUF>
//wewnątrz klas, ale niestety się nie dało :/// więc improwizuję w taki sposób
List<State> stateList = new ArrayList<>();//ale widziałem że to normalne, że trzeba użyć tego typu listy
Map map = new Map(10,10); //więc może i jest git
State Wro = new State(new int[]{0,0},10,100,100);
State Wwa = new State(new int[]{4,4},100,100,100);
stateList.add(Wro);
stateList.add(Wwa);
//testy eksploracji
TextGUI GUI = new TextGUI();
for(int i=0;i<1000;i++) //próby\
{
map.ExplorationTick(stateList);
/*
System.out.println("tick"+i);
System.out.println("Wrocław");
map.OUTTEXTPOINTSCMD(Wro);
System.out.println("Warszawa");
map.OUTTEXTPOINTSCMD(Wwa);
System.out.println();
*/
GUI.gui(Wro, Wwa,map);
sleep(100);
for(int n=0;n!=300;n++)
{
System.out.println();
}
}
GUI.gui(Wro, Wwa,map);
sleep(100);
// map.CMDPOINTREADER(G.GeneratePointOutOf(10,10,Wro));
}
}
| null |
6244_1 | MrHerbat/progrobie | 197 | LessonEleven/src/package1/Gra.java | package package1;
public class Gra
{
{
Pojazd pojazd = new Pojazd();
System.out.println("==================");
// System.out.println(pojazd.owner); //private niedziała w innych klasach
System.out.println(pojazd.value); //pole z modyfikatorem public działa wszędzie
System.out.println(pojazd.maximalSpeed); //pole z modyfikatorem protected działa w tym samym pakiecie w którym był utworzony
System.out.println(pojazd.isElectric); //pole bez modyfikatora działa w tym samym pakiecie w którym był utworzony
}
}
| //pole z modyfikatorem public działa wszędzie
| package package1;
public class Gra
{
{
Pojazd pojazd = new Pojazd();
System.out.println("==================");
// System.out.println(pojazd.owner); //private niedziała w innych klasach
System.out.println(pojazd.value); //pole z <SUF>
System.out.println(pojazd.maximalSpeed); //pole z modyfikatorem protected działa w tym samym pakiecie w którym był utworzony
System.out.println(pojazd.isElectric); //pole bez modyfikatora działa w tym samym pakiecie w którym był utworzony
}
}
| null |
3775_2 | Nekito-Development/openkito | 2,151 | src/main/java/wtf/norma/nekito/module/impl/visuals/CustomModel.java | package wtf.norma.nekito.module.impl.visuals;
import me.zero.alpine.listener.Listener;
import me.zero.alpine.listener.Subscribe;
import me.zero.alpine.listener.Subscriber;
import net.minecraft.client.entity.AbstractClientPlayer;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.entity.RenderManager;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
import wtf.norma.nekito.Nekito;
import wtf.norma.nekito.module.Module;
import wtf.norma.nekito.event.impl.render.EventCustomModel;
import wtf.norma.nekito.settings.impl.ModeSetting;
import wtf.norma.nekito.util.math.MathUtility;
import wtf.norma.nekito.util.render.models.TessellatorModel;
public class CustomModel extends Module implements Subscriber {
public ModeSetting mode = new ModeSetting("Mode", "Hitla", "Hitla", "Jake", "Baba");
private TessellatorModel hitlerHead;
private TessellatorModel hitlerBody;
private TessellatorModel jake;
private TessellatorModel baba;
public CustomModel() {
super("CustomModel", Category.VISUALS, Keyboard.KEY_NONE);
addSettings(mode);
}
@Override
public void onEnable() {
super.onEnable();
Nekito.EVENT_BUS.subscribe(this);
this.hitlerHead = new TessellatorModel("/assets/minecraft/nekito/head.obj");
this.hitlerBody = new TessellatorModel("/assets/minecraft/nekito/body.obj");
this.jake = new TessellatorModel("/assets/minecraft/nekito/Jake.obj");
this.baba = new TessellatorModel("/assets/minecraft/nekito/Aether.obj"); // ta z genshina kojarze ja bo gralem
// cwele z mihoyo kiedy kurwa wkoncu ten jeabny nintendo switch support bo na tym jebanym nvidia now sie grac nie dai
}
@Override
public void onDisable() {
super.onDisable();
Nekito.EVENT_BUS.unsubscribe(this);
this.hitlerHead = null;
this.jake = null;
this.hitlerBody = null;
this.baba = null;
}
// nie wiem
// https://www.youtube.com/watch?v=xjD8MiCe9BU
@Subscribe
private final Listener<EventCustomModel> listener = new Listener<>(event -> {
GlStateManager.pushMatrix();
AbstractClientPlayer entity = mc.thePlayer; // tu mozna zmienic np na friends jak dodam ale mi sie nie chce Xddddddddd
RenderManager manager = mc.getRenderManager();
double x = MathUtility.interpolate(entity.posX, entity.lastTickPosX, mc.getRenderPartialTicks()) - RenderManager.renderPosX;
double y = MathUtility.interpolate(entity.posY, entity.lastTickPosY, mc.getRenderPartialTicks()) - RenderManager.renderPosY;
double z = MathUtility.interpolate(entity.posZ, entity.lastTickPosZ, mc.getRenderPartialTicks()) - RenderManager.renderPosZ;
float yaw = mc.thePlayer.prevRotationYaw + (mc.thePlayer.rotationYaw - mc.thePlayer.prevRotationYaw) * mc.getRenderPartialTicks();
boolean sneak = mc.thePlayer.isSneaking();
GL11.glTranslated(x, y, z);
if (!(mc.currentScreen instanceof GuiContainer))
GL11.glRotatef(-yaw, 0.0F, mc.thePlayer.height, 0.0F);
switch (mode.getMode()) {
case "Hitla":
GlStateManager.scale(0.03, sneak ? 0.027 : 0.029, 0.03);
GlStateManager.disableLighting();
GlStateManager.color(1, 1, 1, 1.0F);
this.hitlerHead.render();
this.hitlerBody.render();
break;
case "Jake":
GlStateManager.scale(0.3, sneak ? 0.27 : 0.29, 0.3);
GlStateManager.disableLighting();
GlStateManager.color(1, 1, 1, 1.0F);
this.jake.render();
break;
case "Baba":
GlStateManager.scale(0.3, sneak ? 0.12 : 0.15, 0.3);
GlStateManager.disableLighting();
GlStateManager.color(1, 1, 1, 1.0F);
this.baba.render();
break;
}
GlStateManager.enableLighting();
GlStateManager.resetColor();
GlStateManager.popMatrix();
});
//Commented out by DevOfDeath 😂😂😂😂😂
// public void onEvent(Event event) {
// if (event instanceof EventCustomModel) {
// GlStateManager.pushMatrix();
// AbstractClientPlayer entity = mc.thePlayer; // tu mozna zmienic np na friends jak dodam ale mi sie nie chce Xddddddddd
// RenderManager manager = mc.getRenderManager();
// double x = MathUtility.interpolate(entity.posX, entity.lastTickPosX, mc.getRenderPartialTicks()) - RenderManager.renderPosX;
// double y = MathUtility.interpolate(entity.posY, entity.lastTickPosY, mc.getRenderPartialTicks()) - RenderManager.renderPosY;
// double z = MathUtility.interpolate(entity.posZ, entity.lastTickPosZ, mc.getRenderPartialTicks()) - RenderManager.renderPosZ;
// float yaw = mc.thePlayer.prevRotationYaw + (mc.thePlayer.rotationYaw - mc.thePlayer.prevRotationYaw) * mc.getRenderPartialTicks();
// boolean sneak = mc.thePlayer.isSneaking();
// GL11.glTranslated(x, y, z);
// if (!(mc.currentScreen instanceof GuiContainer))
// GL11.glRotatef(-yaw, 0.0F, mc.thePlayer.height, 0.0F);
//
//
// switch (mode.getMode()) {
// case "Hitla":
// GlStateManager.scale(0.03, sneak ? 0.027 : 0.029, 0.03);
// GlStateManager.disableLighting();
// GlStateManager.color(1, 1, 1, 1.0F);
// this.hitlerHead.render();
// this.hitlerBody.render();
// break;
// case "Jake":
// GlStateManager.scale(0.3, sneak ? 0.27 : 0.29, 0.3);
// GlStateManager.disableLighting();
// GlStateManager.color(1, 1, 1, 1.0F);
// this.jake.render();
// break;
// case "Baba":
// GlStateManager.scale(0.3, sneak ? 0.12 : 0.15, 0.3);
// GlStateManager.disableLighting();
// GlStateManager.color(1, 1, 1, 1.0F);
// this.baba.render();
// break;
// }
// GlStateManager.enableLighting();
// GlStateManager.resetColor();
// GlStateManager.popMatrix();
// }
// }
}
| // tu mozna zmienic np na friends jak dodam ale mi sie nie chce Xddddddddd | package wtf.norma.nekito.module.impl.visuals;
import me.zero.alpine.listener.Listener;
import me.zero.alpine.listener.Subscribe;
import me.zero.alpine.listener.Subscriber;
import net.minecraft.client.entity.AbstractClientPlayer;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.entity.RenderManager;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
import wtf.norma.nekito.Nekito;
import wtf.norma.nekito.module.Module;
import wtf.norma.nekito.event.impl.render.EventCustomModel;
import wtf.norma.nekito.settings.impl.ModeSetting;
import wtf.norma.nekito.util.math.MathUtility;
import wtf.norma.nekito.util.render.models.TessellatorModel;
public class CustomModel extends Module implements Subscriber {
public ModeSetting mode = new ModeSetting("Mode", "Hitla", "Hitla", "Jake", "Baba");
private TessellatorModel hitlerHead;
private TessellatorModel hitlerBody;
private TessellatorModel jake;
private TessellatorModel baba;
public CustomModel() {
super("CustomModel", Category.VISUALS, Keyboard.KEY_NONE);
addSettings(mode);
}
@Override
public void onEnable() {
super.onEnable();
Nekito.EVENT_BUS.subscribe(this);
this.hitlerHead = new TessellatorModel("/assets/minecraft/nekito/head.obj");
this.hitlerBody = new TessellatorModel("/assets/minecraft/nekito/body.obj");
this.jake = new TessellatorModel("/assets/minecraft/nekito/Jake.obj");
this.baba = new TessellatorModel("/assets/minecraft/nekito/Aether.obj"); // ta z genshina kojarze ja bo gralem
// cwele z mihoyo kiedy kurwa wkoncu ten jeabny nintendo switch support bo na tym jebanym nvidia now sie grac nie dai
}
@Override
public void onDisable() {
super.onDisable();
Nekito.EVENT_BUS.unsubscribe(this);
this.hitlerHead = null;
this.jake = null;
this.hitlerBody = null;
this.baba = null;
}
// nie wiem
// https://www.youtube.com/watch?v=xjD8MiCe9BU
@Subscribe
private final Listener<EventCustomModel> listener = new Listener<>(event -> {
GlStateManager.pushMatrix();
AbstractClientPlayer entity = mc.thePlayer; // tu mozna <SUF>
RenderManager manager = mc.getRenderManager();
double x = MathUtility.interpolate(entity.posX, entity.lastTickPosX, mc.getRenderPartialTicks()) - RenderManager.renderPosX;
double y = MathUtility.interpolate(entity.posY, entity.lastTickPosY, mc.getRenderPartialTicks()) - RenderManager.renderPosY;
double z = MathUtility.interpolate(entity.posZ, entity.lastTickPosZ, mc.getRenderPartialTicks()) - RenderManager.renderPosZ;
float yaw = mc.thePlayer.prevRotationYaw + (mc.thePlayer.rotationYaw - mc.thePlayer.prevRotationYaw) * mc.getRenderPartialTicks();
boolean sneak = mc.thePlayer.isSneaking();
GL11.glTranslated(x, y, z);
if (!(mc.currentScreen instanceof GuiContainer))
GL11.glRotatef(-yaw, 0.0F, mc.thePlayer.height, 0.0F);
switch (mode.getMode()) {
case "Hitla":
GlStateManager.scale(0.03, sneak ? 0.027 : 0.029, 0.03);
GlStateManager.disableLighting();
GlStateManager.color(1, 1, 1, 1.0F);
this.hitlerHead.render();
this.hitlerBody.render();
break;
case "Jake":
GlStateManager.scale(0.3, sneak ? 0.27 : 0.29, 0.3);
GlStateManager.disableLighting();
GlStateManager.color(1, 1, 1, 1.0F);
this.jake.render();
break;
case "Baba":
GlStateManager.scale(0.3, sneak ? 0.12 : 0.15, 0.3);
GlStateManager.disableLighting();
GlStateManager.color(1, 1, 1, 1.0F);
this.baba.render();
break;
}
GlStateManager.enableLighting();
GlStateManager.resetColor();
GlStateManager.popMatrix();
});
//Commented out by DevOfDeath 😂😂😂😂😂
// public void onEvent(Event event) {
// if (event instanceof EventCustomModel) {
// GlStateManager.pushMatrix();
// AbstractClientPlayer entity = mc.thePlayer; // tu mozna zmienic np na friends jak dodam ale mi sie nie chce Xddddddddd
// RenderManager manager = mc.getRenderManager();
// double x = MathUtility.interpolate(entity.posX, entity.lastTickPosX, mc.getRenderPartialTicks()) - RenderManager.renderPosX;
// double y = MathUtility.interpolate(entity.posY, entity.lastTickPosY, mc.getRenderPartialTicks()) - RenderManager.renderPosY;
// double z = MathUtility.interpolate(entity.posZ, entity.lastTickPosZ, mc.getRenderPartialTicks()) - RenderManager.renderPosZ;
// float yaw = mc.thePlayer.prevRotationYaw + (mc.thePlayer.rotationYaw - mc.thePlayer.prevRotationYaw) * mc.getRenderPartialTicks();
// boolean sneak = mc.thePlayer.isSneaking();
// GL11.glTranslated(x, y, z);
// if (!(mc.currentScreen instanceof GuiContainer))
// GL11.glRotatef(-yaw, 0.0F, mc.thePlayer.height, 0.0F);
//
//
// switch (mode.getMode()) {
// case "Hitla":
// GlStateManager.scale(0.03, sneak ? 0.027 : 0.029, 0.03);
// GlStateManager.disableLighting();
// GlStateManager.color(1, 1, 1, 1.0F);
// this.hitlerHead.render();
// this.hitlerBody.render();
// break;
// case "Jake":
// GlStateManager.scale(0.3, sneak ? 0.27 : 0.29, 0.3);
// GlStateManager.disableLighting();
// GlStateManager.color(1, 1, 1, 1.0F);
// this.jake.render();
// break;
// case "Baba":
// GlStateManager.scale(0.3, sneak ? 0.12 : 0.15, 0.3);
// GlStateManager.disableLighting();
// GlStateManager.color(1, 1, 1, 1.0F);
// this.baba.render();
// break;
// }
// GlStateManager.enableLighting();
// GlStateManager.resetColor();
// GlStateManager.popMatrix();
// }
// }
}
| null |
2045_44 | NekoX-Dev/NekoX | 3,374 | TMessagesProj/src/main/java/org/webrtc/RendererCommon.java | /*
* Copyright 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
package org.webrtc;
import android.graphics.Point;
import android.opengl.Matrix;
import android.view.View;
/**
* Static helper functions for renderer implementations.
*/
public class RendererCommon {
/** Interface for reporting rendering events. */
public static interface RendererEvents {
/**
* Callback fired once first frame is rendered.
*/
public void onFirstFrameRendered();
/**
* Callback fired when rendered frame resolution or rotation has changed.
*/
public void onFrameResolutionChanged(int videoWidth, int videoHeight, int rotation);
}
/**
* Interface for rendering frames on an EGLSurface with specified viewport location. Rotation,
* mirror, and cropping is specified using a 4x4 texture coordinate transform matrix. The frame
* input can either be an OES texture, RGB texture, or YUV textures in I420 format. The function
* release() must be called manually to free the resources held by this object.
*/
public interface GlDrawer {
/**
* Functions for drawing frames with different sources. The rendering surface target is
* implied by the current EGL context of the calling thread and requires no explicit argument.
* The coordinates specify the viewport location on the surface target.
*/
void drawOes(int oesTextureId, int originalWidth, int originalHeight, int rotatedWidth, int rotatedHeight, float[] texMatrix, int frameWidth, int frameHeight,
int viewportX, int viewportY, int viewportWidth, int viewportHeight, boolean blur);
void drawRgb(int textureId, int originalWidth, int originalHeight, int rotatedWidth, int rotatedHeight, float[] texMatrix, int frameWidth, int frameHeight, int viewportX,
int viewportY, int viewportWidth, int viewportHeight, boolean blur);
void drawYuv(int[] yuvTextures, int originalWidth, int originalHeight, int rotatedWidth, int rotatedHeight, float[] texMatrix, int frameWidth, int frameHeight,
int viewportX, int viewportY, int viewportWidth, int viewportHeight, boolean blur);
/**
* Release all GL resources. This needs to be done manually, otherwise resources may leak.
*/
void release();
}
/**
* Helper class for determining layout size based on layout requirements, scaling type, and video
* aspect ratio.
*/
public static class VideoLayoutMeasure {
// The scaling type determines how the video will fill the allowed layout area in measure(). It
// can be specified separately for the case when video has matched orientation with layout size
// and when there is an orientation mismatch.
private float visibleFractionMatchOrientation =
convertScalingTypeToVisibleFraction(ScalingType.SCALE_ASPECT_BALANCED);
private float visibleFractionMismatchOrientation =
convertScalingTypeToVisibleFraction(ScalingType.SCALE_ASPECT_BALANCED);
public void setScalingType(ScalingType scalingType) {
setScalingType(/* scalingTypeMatchOrientation= */ scalingType,
/* scalingTypeMismatchOrientation= */ scalingType);
}
public void setScalingType(
ScalingType scalingTypeMatchOrientation, ScalingType scalingTypeMismatchOrientation) {
this.visibleFractionMatchOrientation =
convertScalingTypeToVisibleFraction(scalingTypeMatchOrientation);
this.visibleFractionMismatchOrientation =
convertScalingTypeToVisibleFraction(scalingTypeMismatchOrientation);
}
public void setVisibleFraction(
float visibleFractionMatchOrientation, float visibleFractionMismatchOrientation) {
this.visibleFractionMatchOrientation = visibleFractionMatchOrientation;
this.visibleFractionMismatchOrientation = visibleFractionMismatchOrientation;
}
public Point measure(boolean applyRotation, int widthSpec, int heightSpec, int frameWidth, int frameHeight) {
// Calculate max allowed layout size.
final int maxWidth = View.getDefaultSize(Integer.MAX_VALUE, widthSpec);
final int maxHeight = View.getDefaultSize(Integer.MAX_VALUE, heightSpec);
if (frameWidth == 0 || frameHeight == 0 || maxWidth == 0 || maxHeight == 0) {
return new Point(maxWidth, maxHeight);
}
// Calculate desired display size based on scaling type, video aspect ratio,
// and maximum layout size.
final float frameAspect = frameWidth / (float) frameHeight;
final float displayAspect = maxWidth / (float) maxHeight;
final float visibleFraction = (frameAspect > 1.0f) == (displayAspect > 1.0f)
? visibleFractionMatchOrientation
: visibleFractionMismatchOrientation;
final Point layoutSize = getDisplaySize(visibleFraction, frameAspect, maxWidth, maxHeight);
// If the measure specification is forcing a specific size - yield.
if (!applyRotation) {
if (View.MeasureSpec.getMode(widthSpec) == View.MeasureSpec.EXACTLY) {
layoutSize.x = maxWidth;
}
if (View.MeasureSpec.getMode(heightSpec) == View.MeasureSpec.EXACTLY || frameAspect > 1.0f == displayAspect > 1.0f) {
layoutSize.y = maxHeight;
}
}
return layoutSize;
}
}
// Types of video scaling:
// SCALE_ASPECT_FIT - video frame is scaled to fit the size of the view by
// maintaining the aspect ratio (black borders may be displayed).
// SCALE_ASPECT_FILL - video frame is scaled to fill the size of the view by
// maintaining the aspect ratio. Some portion of the video frame may be
// clipped.
// SCALE_ASPECT_BALANCED - Compromise between FIT and FILL. Video frame will fill as much as
// possible of the view while maintaining aspect ratio, under the constraint that at least
// |BALANCED_VISIBLE_FRACTION| of the frame content will be shown.
public static enum ScalingType { SCALE_ASPECT_FIT, SCALE_ASPECT_FILL, SCALE_ASPECT_BALANCED }
// The minimum fraction of the frame content that will be shown for |SCALE_ASPECT_BALANCED|.
// This limits excessive cropping when adjusting display size.
private static float BALANCED_VISIBLE_FRACTION = 0.5625f;
/**
* Returns layout transformation matrix that applies an optional mirror effect and compensates
* for video vs display aspect ratio.
*/
public static float[] getLayoutMatrix(
boolean mirror, float videoAspectRatio, float displayAspectRatio) {
float scaleX = 1;
float scaleY = 1;
// Scale X or Y dimension so that video and display size have same aspect ratio.
if (displayAspectRatio > videoAspectRatio) {
scaleY = videoAspectRatio / displayAspectRatio;
} else {
scaleX = displayAspectRatio / videoAspectRatio;
}
// Apply optional horizontal flip.
if (mirror) {
scaleX *= -1;
}
final float matrix[] = new float[16];
Matrix.setIdentityM(matrix, 0);
Matrix.scaleM(matrix, 0, scaleX, scaleY, 1);
adjustOrigin(matrix);
return matrix;
}
/** Converts a float[16] matrix array to android.graphics.Matrix. */
public static android.graphics.Matrix convertMatrixToAndroidGraphicsMatrix(float[] matrix4x4) {
// clang-format off
float[] values = {
matrix4x4[0 * 4 + 0], matrix4x4[1 * 4 + 0], matrix4x4[3 * 4 + 0],
matrix4x4[0 * 4 + 1], matrix4x4[1 * 4 + 1], matrix4x4[3 * 4 + 1],
matrix4x4[0 * 4 + 3], matrix4x4[1 * 4 + 3], matrix4x4[3 * 4 + 3],
};
// clang-format on
android.graphics.Matrix matrix = new android.graphics.Matrix();
matrix.setValues(values);
return matrix;
}
/** Converts android.graphics.Matrix to a float[16] matrix array. */
public static float[] convertMatrixFromAndroidGraphicsMatrix(android.graphics.Matrix matrix) {
float[] values = new float[9];
matrix.getValues(values);
// The android.graphics.Matrix looks like this:
// [x1 y1 w1]
// [x2 y2 w2]
// [x3 y3 w3]
// We want to contruct a matrix that looks like this:
// [x1 y1 0 w1]
// [x2 y2 0 w2]
// [ 0 0 1 0]
// [x3 y3 0 w3]
// Since it is stored in column-major order, it looks like this:
// [x1 x2 0 x3
// y1 y2 0 y3
// 0 0 1 0
// w1 w2 0 w3]
// clang-format off
float[] matrix4x4 = {
values[0 * 3 + 0], values[1 * 3 + 0], 0, values[2 * 3 + 0],
values[0 * 3 + 1], values[1 * 3 + 1], 0, values[2 * 3 + 1],
0, 0, 1, 0,
values[0 * 3 + 2], values[1 * 3 + 2], 0, values[2 * 3 + 2],
};
// clang-format on
return matrix4x4;
}
/**
* Calculate display size based on scaling type, video aspect ratio, and maximum display size.
*/
public static Point getDisplaySize(
ScalingType scalingType, float videoAspectRatio, int maxDisplayWidth, int maxDisplayHeight) {
return getDisplaySize(convertScalingTypeToVisibleFraction(scalingType), videoAspectRatio,
maxDisplayWidth, maxDisplayHeight);
}
/**
* Move |matrix| transformation origin to (0.5, 0.5). This is the origin for texture coordinates
* that are in the range 0 to 1.
*/
private static void adjustOrigin(float[] matrix) {
// Note that OpenGL is using column-major order.
// Pre translate with -0.5 to move coordinates to range [-0.5, 0.5].
matrix[12] -= 0.5f * (matrix[0] + matrix[4]);
matrix[13] -= 0.5f * (matrix[1] + matrix[5]);
// Post translate with 0.5 to move coordinates to range [0, 1].
matrix[12] += 0.5f;
matrix[13] += 0.5f;
}
/**
* Each scaling type has a one-to-one correspondence to a numeric minimum fraction of the video
* that must remain visible.
*/
private static float convertScalingTypeToVisibleFraction(ScalingType scalingType) {
switch (scalingType) {
case SCALE_ASPECT_FIT:
return 1.0f;
case SCALE_ASPECT_FILL:
return 0.0f;
case SCALE_ASPECT_BALANCED:
return BALANCED_VISIBLE_FRACTION;
default:
throw new IllegalArgumentException();
}
}
/**
* Calculate display size based on minimum fraction of the video that must remain visible,
* video aspect ratio, and maximum display size.
*/
public static Point getDisplaySize(
float minVisibleFraction, float videoAspectRatio, int maxDisplayWidth, int maxDisplayHeight) {
// If there is no constraint on the amount of cropping, fill the allowed display area.
if (minVisibleFraction == 0 || videoAspectRatio == 0) {
return new Point(maxDisplayWidth, maxDisplayHeight);
}
// Each dimension is constrained on max display size and how much we are allowed to crop.
final int width = Math.min(
maxDisplayWidth, Math.round(maxDisplayHeight / minVisibleFraction * videoAspectRatio));
final int height = Math.min(
maxDisplayHeight, Math.round(maxDisplayWidth / minVisibleFraction / videoAspectRatio));
return new Point(width, height);
}
}
| // w1 w2 0 w3] | /*
* Copyright 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
package org.webrtc;
import android.graphics.Point;
import android.opengl.Matrix;
import android.view.View;
/**
* Static helper functions for renderer implementations.
*/
public class RendererCommon {
/** Interface for reporting rendering events. */
public static interface RendererEvents {
/**
* Callback fired once first frame is rendered.
*/
public void onFirstFrameRendered();
/**
* Callback fired when rendered frame resolution or rotation has changed.
*/
public void onFrameResolutionChanged(int videoWidth, int videoHeight, int rotation);
}
/**
* Interface for rendering frames on an EGLSurface with specified viewport location. Rotation,
* mirror, and cropping is specified using a 4x4 texture coordinate transform matrix. The frame
* input can either be an OES texture, RGB texture, or YUV textures in I420 format. The function
* release() must be called manually to free the resources held by this object.
*/
public interface GlDrawer {
/**
* Functions for drawing frames with different sources. The rendering surface target is
* implied by the current EGL context of the calling thread and requires no explicit argument.
* The coordinates specify the viewport location on the surface target.
*/
void drawOes(int oesTextureId, int originalWidth, int originalHeight, int rotatedWidth, int rotatedHeight, float[] texMatrix, int frameWidth, int frameHeight,
int viewportX, int viewportY, int viewportWidth, int viewportHeight, boolean blur);
void drawRgb(int textureId, int originalWidth, int originalHeight, int rotatedWidth, int rotatedHeight, float[] texMatrix, int frameWidth, int frameHeight, int viewportX,
int viewportY, int viewportWidth, int viewportHeight, boolean blur);
void drawYuv(int[] yuvTextures, int originalWidth, int originalHeight, int rotatedWidth, int rotatedHeight, float[] texMatrix, int frameWidth, int frameHeight,
int viewportX, int viewportY, int viewportWidth, int viewportHeight, boolean blur);
/**
* Release all GL resources. This needs to be done manually, otherwise resources may leak.
*/
void release();
}
/**
* Helper class for determining layout size based on layout requirements, scaling type, and video
* aspect ratio.
*/
public static class VideoLayoutMeasure {
// The scaling type determines how the video will fill the allowed layout area in measure(). It
// can be specified separately for the case when video has matched orientation with layout size
// and when there is an orientation mismatch.
private float visibleFractionMatchOrientation =
convertScalingTypeToVisibleFraction(ScalingType.SCALE_ASPECT_BALANCED);
private float visibleFractionMismatchOrientation =
convertScalingTypeToVisibleFraction(ScalingType.SCALE_ASPECT_BALANCED);
public void setScalingType(ScalingType scalingType) {
setScalingType(/* scalingTypeMatchOrientation= */ scalingType,
/* scalingTypeMismatchOrientation= */ scalingType);
}
public void setScalingType(
ScalingType scalingTypeMatchOrientation, ScalingType scalingTypeMismatchOrientation) {
this.visibleFractionMatchOrientation =
convertScalingTypeToVisibleFraction(scalingTypeMatchOrientation);
this.visibleFractionMismatchOrientation =
convertScalingTypeToVisibleFraction(scalingTypeMismatchOrientation);
}
public void setVisibleFraction(
float visibleFractionMatchOrientation, float visibleFractionMismatchOrientation) {
this.visibleFractionMatchOrientation = visibleFractionMatchOrientation;
this.visibleFractionMismatchOrientation = visibleFractionMismatchOrientation;
}
public Point measure(boolean applyRotation, int widthSpec, int heightSpec, int frameWidth, int frameHeight) {
// Calculate max allowed layout size.
final int maxWidth = View.getDefaultSize(Integer.MAX_VALUE, widthSpec);
final int maxHeight = View.getDefaultSize(Integer.MAX_VALUE, heightSpec);
if (frameWidth == 0 || frameHeight == 0 || maxWidth == 0 || maxHeight == 0) {
return new Point(maxWidth, maxHeight);
}
// Calculate desired display size based on scaling type, video aspect ratio,
// and maximum layout size.
final float frameAspect = frameWidth / (float) frameHeight;
final float displayAspect = maxWidth / (float) maxHeight;
final float visibleFraction = (frameAspect > 1.0f) == (displayAspect > 1.0f)
? visibleFractionMatchOrientation
: visibleFractionMismatchOrientation;
final Point layoutSize = getDisplaySize(visibleFraction, frameAspect, maxWidth, maxHeight);
// If the measure specification is forcing a specific size - yield.
if (!applyRotation) {
if (View.MeasureSpec.getMode(widthSpec) == View.MeasureSpec.EXACTLY) {
layoutSize.x = maxWidth;
}
if (View.MeasureSpec.getMode(heightSpec) == View.MeasureSpec.EXACTLY || frameAspect > 1.0f == displayAspect > 1.0f) {
layoutSize.y = maxHeight;
}
}
return layoutSize;
}
}
// Types of video scaling:
// SCALE_ASPECT_FIT - video frame is scaled to fit the size of the view by
// maintaining the aspect ratio (black borders may be displayed).
// SCALE_ASPECT_FILL - video frame is scaled to fill the size of the view by
// maintaining the aspect ratio. Some portion of the video frame may be
// clipped.
// SCALE_ASPECT_BALANCED - Compromise between FIT and FILL. Video frame will fill as much as
// possible of the view while maintaining aspect ratio, under the constraint that at least
// |BALANCED_VISIBLE_FRACTION| of the frame content will be shown.
public static enum ScalingType { SCALE_ASPECT_FIT, SCALE_ASPECT_FILL, SCALE_ASPECT_BALANCED }
// The minimum fraction of the frame content that will be shown for |SCALE_ASPECT_BALANCED|.
// This limits excessive cropping when adjusting display size.
private static float BALANCED_VISIBLE_FRACTION = 0.5625f;
/**
* Returns layout transformation matrix that applies an optional mirror effect and compensates
* for video vs display aspect ratio.
*/
public static float[] getLayoutMatrix(
boolean mirror, float videoAspectRatio, float displayAspectRatio) {
float scaleX = 1;
float scaleY = 1;
// Scale X or Y dimension so that video and display size have same aspect ratio.
if (displayAspectRatio > videoAspectRatio) {
scaleY = videoAspectRatio / displayAspectRatio;
} else {
scaleX = displayAspectRatio / videoAspectRatio;
}
// Apply optional horizontal flip.
if (mirror) {
scaleX *= -1;
}
final float matrix[] = new float[16];
Matrix.setIdentityM(matrix, 0);
Matrix.scaleM(matrix, 0, scaleX, scaleY, 1);
adjustOrigin(matrix);
return matrix;
}
/** Converts a float[16] matrix array to android.graphics.Matrix. */
public static android.graphics.Matrix convertMatrixToAndroidGraphicsMatrix(float[] matrix4x4) {
// clang-format off
float[] values = {
matrix4x4[0 * 4 + 0], matrix4x4[1 * 4 + 0], matrix4x4[3 * 4 + 0],
matrix4x4[0 * 4 + 1], matrix4x4[1 * 4 + 1], matrix4x4[3 * 4 + 1],
matrix4x4[0 * 4 + 3], matrix4x4[1 * 4 + 3], matrix4x4[3 * 4 + 3],
};
// clang-format on
android.graphics.Matrix matrix = new android.graphics.Matrix();
matrix.setValues(values);
return matrix;
}
/** Converts android.graphics.Matrix to a float[16] matrix array. */
public static float[] convertMatrixFromAndroidGraphicsMatrix(android.graphics.Matrix matrix) {
float[] values = new float[9];
matrix.getValues(values);
// The android.graphics.Matrix looks like this:
// [x1 y1 w1]
// [x2 y2 w2]
// [x3 y3 w3]
// We want to contruct a matrix that looks like this:
// [x1 y1 0 w1]
// [x2 y2 0 w2]
// [ 0 0 1 0]
// [x3 y3 0 w3]
// Since it is stored in column-major order, it looks like this:
// [x1 x2 0 x3
// y1 y2 0 y3
// 0 0 1 0
// w1 w2 <SUF>
// clang-format off
float[] matrix4x4 = {
values[0 * 3 + 0], values[1 * 3 + 0], 0, values[2 * 3 + 0],
values[0 * 3 + 1], values[1 * 3 + 1], 0, values[2 * 3 + 1],
0, 0, 1, 0,
values[0 * 3 + 2], values[1 * 3 + 2], 0, values[2 * 3 + 2],
};
// clang-format on
return matrix4x4;
}
/**
* Calculate display size based on scaling type, video aspect ratio, and maximum display size.
*/
public static Point getDisplaySize(
ScalingType scalingType, float videoAspectRatio, int maxDisplayWidth, int maxDisplayHeight) {
return getDisplaySize(convertScalingTypeToVisibleFraction(scalingType), videoAspectRatio,
maxDisplayWidth, maxDisplayHeight);
}
/**
* Move |matrix| transformation origin to (0.5, 0.5). This is the origin for texture coordinates
* that are in the range 0 to 1.
*/
private static void adjustOrigin(float[] matrix) {
// Note that OpenGL is using column-major order.
// Pre translate with -0.5 to move coordinates to range [-0.5, 0.5].
matrix[12] -= 0.5f * (matrix[0] + matrix[4]);
matrix[13] -= 0.5f * (matrix[1] + matrix[5]);
// Post translate with 0.5 to move coordinates to range [0, 1].
matrix[12] += 0.5f;
matrix[13] += 0.5f;
}
/**
* Each scaling type has a one-to-one correspondence to a numeric minimum fraction of the video
* that must remain visible.
*/
private static float convertScalingTypeToVisibleFraction(ScalingType scalingType) {
switch (scalingType) {
case SCALE_ASPECT_FIT:
return 1.0f;
case SCALE_ASPECT_FILL:
return 0.0f;
case SCALE_ASPECT_BALANCED:
return BALANCED_VISIBLE_FRACTION;
default:
throw new IllegalArgumentException();
}
}
/**
* Calculate display size based on minimum fraction of the video that must remain visible,
* video aspect ratio, and maximum display size.
*/
public static Point getDisplaySize(
float minVisibleFraction, float videoAspectRatio, int maxDisplayWidth, int maxDisplayHeight) {
// If there is no constraint on the amount of cropping, fill the allowed display area.
if (minVisibleFraction == 0 || videoAspectRatio == 0) {
return new Point(maxDisplayWidth, maxDisplayHeight);
}
// Each dimension is constrained on max display size and how much we are allowed to crop.
final int width = Math.min(
maxDisplayWidth, Math.round(maxDisplayHeight / minVisibleFraction * videoAspectRatio));
final int height = Math.min(
maxDisplayHeight, Math.round(maxDisplayWidth / minVisibleFraction / videoAspectRatio));
return new Point(width, height);
}
}
| null |
10550_2 | Neot0x/PIO-zajecia | 744 | Game.java | package com.mycompany.zajecia;
import com.mycompany.zajecia.players.Player;
import com.mycompany.zajecia.statistics.Statistics;
import java.util.Random;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Game {
private Statistics statistics;
private Random dice = new Random();
private Player player;
private List<Player> players = new ArrayList<>();
public Game(){
this(null);
}
public Game(Statistics statistics){
if(statistics != null)
this.statistics = statistics;
else
this.statistics = NullStatistics();
}
public void addPlayer(Player player){
if(nameExists(player.getName())){
player.setName(player.getName() + dice.nextInt(10));
addPlayer(player);
}else{
//this.player = player;
players.add(player);
}
}
public void printPlayers(){
System.out.println("-------");
players.forEach(player -> {System.out.println(player.getName());});
}
public void removePlayer(String name){
/* for(int i=0; i < players.size(); ++i){
if(players.get(i).getName().equals(name)){
players.remove(i);
break;
}
}*/
for(Iterator<Player> it=players.iterator(); it.hasNext();){
if(it.next().getName().equals(name)){
it.remove();
break;
}
}
// players.removeIf( player -> player.getName().equals(name)); //zawsze przejży całość
}
private boolean nameExists(String name){
for(Player player : players){
if(player.getName().equals(name)){
return true;
}
}
return false;
}
public void play(){
int number;
int guess;
boolean repeat = true;
do{
number = dice.nextInt(6)+1;
System.out.println(number);
for(Player player : players){
guess = player.guess();
System.out.println(player.getName() + ": " + guess );
if(guess == number){
System.out.println("Zgadles");
repeat = false;
statistics.winner(player);
}else{
System.out.println("Nie zgadles");
}
}
}while(repeat);
}
public void printStats(){
statistics.print();
}
} | // players.removeIf( player -> player.getName().equals(name)); //zawsze przejży całość
| package com.mycompany.zajecia;
import com.mycompany.zajecia.players.Player;
import com.mycompany.zajecia.statistics.Statistics;
import java.util.Random;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Game {
private Statistics statistics;
private Random dice = new Random();
private Player player;
private List<Player> players = new ArrayList<>();
public Game(){
this(null);
}
public Game(Statistics statistics){
if(statistics != null)
this.statistics = statistics;
else
this.statistics = NullStatistics();
}
public void addPlayer(Player player){
if(nameExists(player.getName())){
player.setName(player.getName() + dice.nextInt(10));
addPlayer(player);
}else{
//this.player = player;
players.add(player);
}
}
public void printPlayers(){
System.out.println("-------");
players.forEach(player -> {System.out.println(player.getName());});
}
public void removePlayer(String name){
/* for(int i=0; i < players.size(); ++i){
if(players.get(i).getName().equals(name)){
players.remove(i);
break;
}
}*/
for(Iterator<Player> it=players.iterator(); it.hasNext();){
if(it.next().getName().equals(name)){
it.remove();
break;
}
}
// players.removeIf( player <SUF>
}
private boolean nameExists(String name){
for(Player player : players){
if(player.getName().equals(name)){
return true;
}
}
return false;
}
public void play(){
int number;
int guess;
boolean repeat = true;
do{
number = dice.nextInt(6)+1;
System.out.println(number);
for(Player player : players){
guess = player.guess();
System.out.println(player.getName() + ": " + guess );
if(guess == number){
System.out.println("Zgadles");
repeat = false;
statistics.winner(player);
}else{
System.out.println("Nie zgadles");
}
}
}while(repeat);
}
public void printStats(){
statistics.print();
}
} | null |
1630_11 | NoiseQuintet/Sudoku-HelpBot | 7,574 | ChatBot.java | package MAIN;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import java.awt.Color;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.lang.Math;
public class ChatBot extends JFrame implements KeyListener{
/**
*
*/
private static final long serialVersionUID = 1L;
JPanel MainWindow=new JPanel();
JTextArea c = new JTextArea();
JTextArea ChatBox=new JTextArea(20,70);
JTextArea TextInput=new JTextArea(1,70);
JScrollPane Scroll=new JScrollPane(
ChatBox,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
);
String[][] ChatBotText={
//demo
{"demo"},
{"Cześc \n jestem botem który umili ci czas podczas grania W Cudowne SUDOKU \n możesz mnie zapytac o wiele ciekawych informacji \n które znajdziesz pod komendą 'help'"},
//powitania
{"siema"},
{"Dzień Dobry","Szczęśc Boże"},
{"dzien dobry"},
{"Dzień Dobry","Szczęśc Boże"},
{"czesc"},
{"Dzień Dobry","Szczęśc Boże"},
{"hej"},
{"Dzień Dobry","Szczęśc Boże"},
{"siemano"},
{"Dzień Dobry","Szczęśc Boże"},
{"witaj", "witam"},
{"Dzień Dobry"},
{"witam"},
{"Dzień Dobry","Szczęśc Boże"},
//pozegnania
{"do widzenia"},
{"Nara","Bywaj","Z Bogiem","Daswidania"},
{"dobranoc",},
{"Nara","Bywaj","Z Bogiem","Daswidania"},
{"na razie"},
{"Nara","Bywaj","Z Bogiem","Daswidania"},
{"do zobaczenia"},
{"Nara","Bywaj","Z Bogiem","Daswidania"},
{"zegnaj"},
{"Nara","Bywaj","Z Bogiem","Daswidania"},
//pytania o samopoczucie
{"co tam","jak tam","co u ciebie","jak sie czujesz"},
{"Niezgorzej","Obleci", "Tak se"},
//regu³y gry w sudoku
{"zasady"},
{"W sudoku gra siê na planszy o wymiarach 9x9 podzielonej na \n mniejsze obszary o wymiarach 3x3. Na poczttku gry niektóre z pól \n planszy Sudoku s¹ ju¿ wype³nione liczbami. Celem gry jest \n uzupelnienie pozostalych pól planszy cyframi od 1 do 9 \n (po jednej cyfrze w kazdym polu)."},
{"podasz mi reguly sudoku?"},
{"W sudoku gra siê na planszy o wymiarach 9x9 podzielonej na \n mniejsze obszary o wymiarach 3x3. Na poczttku gry niektóre z pól \n planszy Sudoku s¹ ju¿ wype³nione liczbami. Celem gry jest \n uzupelnienie pozostalych pól planszy cyframi od 1 do 9 \n (po jednej cyfrze w kazdym polu)."},
{"jakie sa zasady sudoku?"},
{"W sudoku gra siê na planszy o wymiarach 9x9 podzielonej na \n mniejsze obszary o wymiarach 3x3. Na poczttku gry niektóre z pól \n planszy Sudoku s¹ ju¿ wype³nione liczbami. Celem gry jest \n uzupelnienie pozostalych pól planszy cyframi od 1 do 9 \n (po jednej cyfrze w kazdym polu)."},
{"jak grac w sudoku?"},
{"W sudoku gra siê na planszy o wymiarach 9x9 podzielonej na \n mniejsze obszary o wymiarach 3x3. Na poczttku gry niektóre z pól \n planszy Sudoku s¹ ju¿ wype³nione liczbami. Celem gry jest \n uzupelnienie pozostalych pól planszy cyframi od 1 do 9 \n (po jednej cyfrze w kazdym polu)."},
{"znasz reguly sudoku?"},
{"W sudoku gra siê na planszy o wymiarach 9x9 podzielonej na \n mniejsze obszary o wymiarach 3x3. Na poczttku gry niektóre z pól \n planszy Sudoku s¹ ju¿ wype³nione liczbami. Celem gry jest \n uzupelnienie pozostalych pól planszy cyframi od 1 do 9 \n (po jednej cyfrze w kazdym polu)."},
//NIE
{"tak"},
{"Dlaczego tak?","A mo¿e nie?","Nie Nie Nie!!!!!!!"},
//NIE
{"nie"},
{"Dlaczego nie?","A mo¿e tak?","TAK TAK TAK!!!!!!!"},
//osobowosc
{"co lubisz?"},
{"nie wiem, jestem botem","co Ty slepy?","bota pytasz?"},
{"Twoja ulubiona rzecz?"},
{"nie wiem, jestem botem","co Ty slepy?","bota pytasz?"},
{"masz zainteresowania?"},
{"nie wiem, jestem botem","co Ty slepy?","bota pytasz?"},
{"czy myslisz?"},
{"jestem człowiekobotem, jasne ze czuję i myślę","a jak Ty sądzisz?","nie wiem czy chcê odpowiadaæ na to pytanie"},
{"masz hobby?"},
{"nie wiem, jestem botem","co Ty slepy?","bota pytasz?"},
{"masz pasje?"},
{"nie wiem, jestem botem","co Ty slepy?","bota pytasz?"},
//helperr
{"czy mozesz mi pomoc?","chcia³bym bys mi pomogl","potrzebuje pomocy","pomozesz mi?"},
{"why not?","no dobra ³ajzo","je¿eli ¿¹dasz","a ile p³acisz? no dobra nie jestem materialist¹ jestem botem","niech pomyœlê...ok..."},
//helper
{"masz mi pomoc"},
{"co ja murzyn?","nie będę Twoim niewolnikiem","wal się","no chyba nie","skąd się urwałeś?"},
{"do roboty"},
{"co ja murzyn?","nie będę Twoim niewolnikiem","wal się","no chyba nie","skąd się urwałeś?"},
{"musisz mi pomoc"},
{"co ja murzyn?","nie będę Twoim niewolnikiem","wal się","no chyba nie","skąd się urwałeś?"},
{"rób!"},
{"co ja murzyn?","nie będę Twoim niewolnikiem","wal się","no chyba nie","skąd się urwałeś?"},
//obrazliwe
{"Ty debilu"},
{"nie gadam z Tobą","chyba Ty tej","zal..."},
{"jestes głupi"},
{"nie gadam z Tobą","chyba Ty tej","zal..."},
{"kretyn"},
{"nie gadam z Tobą","chyba Ty tej","zal..."},
{"idiota"},
{"taaa"},
{"pełnym zdaniem proszę","nie wiem, Ty musiszz zdecydowac","jestem elokwentniejszy"},
{"i?"},
{"pełnym zdaniem proszę","nie wiem, Ty musiszz zdecydowac","jestem elokwentniejszy"},
{"nie gadam z Tobą","chyba Ty tej","zal..."},
{"Imbecyl"},
{"nie gadam z Tobą","chyba Ty tej","zal..."},
//opowiastki
{"powiesz cos ciekawego?"},
{"przecież jestem botem, nie znam historyjek","mam bugi w kodzie","pssst, moi programiœci nic nie umieją"},
{"opowiedz cos"},
{"przecież jestem botem, nie znam historyjek","mam bugi w kodzie","pssst, moi programiœci nic nie umieją"},
{"co tam w świecie?"},
{"przecież jestem botem, nie znam historyjek","mam bugi w kodzie","pssst, moi programiœci nic nie umieją"},
{"opowiedz historie"},
{"przecież jestem botem, nie znam historyjek","mam bugi w kodzie","pssst, moi programiœci nic nie umieją"},
//podtrzymanie rozmowy
{"no i?"},
{"pełnym zdaniem proszę","nie wiem, Ty musiszz zdecydowac","jestem elokwentniejszy"},
{"co z tego?"},
{"pełnym zdaniem proszę","nie wiem, Ty musiszz zdecydowac","jestem elokwentniejszy"},
{"co dalej?",},
{"pełnym zdaniem proszę","nie wiem, Ty musiszz zdecydowac","jestem elokwentniejszy"},
{"mhm"},
{"pełnym zdaniem proszę","nie wiem, Ty musiszz zdecydowac","jestem elokwentniejszy"},
{"hmmm"},
{"pełnym zdaniem proszę","nie wiem, Ty musiszz zdecydowac","jestem elokwentniejszy"},
//bycie botem
{"jestes botem?"},
{"jestem człowiekobotem, jasne ze czuję i myślę","a jak Ty sądzisz?","nie wiem czy chcê odpowiadaæ na to pytanie"},
{"jestes czlowiekiem?"},
{"jestem człowiekobotem, jasne ze czuję i myślę","a jak Ty sądzisz?","nie wiem czy chcê odpowiadaæ na to pytanie"},
{"Ty idioto"},
{"nie gadam z Tobą","chyba Ty tej","zal..."},
{"Ty kretynie"},
{"nie gadam z Tobą","chyba Ty tej","zal..."},
{"potrafisz czuc?"},
{"jestem człowiekobotem, jasne ze czuję i myślę","a jak Ty sądzisz?","nie wiem czy chcê odpowiadaæ na to pytanie"},
{"czy masz uczucia?"},
{"jestem człowiekobotem, jasne ze czuję i myślę","a jak Ty sądzisz?","nie wiem czy chcê odpowiadaæ na to pytanie"},
//sens istnienia
{"sens zycia","jaki jest sens istnienia?","jaki jest sens zycia?","po co ¿yjemy?","co sie w zyciu liczy?","jak zyc?"},
{"jedno s³owo - JAVA"},
//wiara
{"jestes wierzacy?"},
{"nie jestem upowa¿niony do odpowiadania \n na tego typu pytania \n #poprawnoœcPolityczna"},
{"istnieje bog?"},
{"nie jestem upowa¿niony do odpowiadania \n na tego typu pytania \n #poprawnoœcPolityczna"},
{"chodzisz do kosciola?"},
{"nie jestem upowa¿niony do odpowiadania \n na tego typu pytania \n #poprawnoœcPolityczna"},
//lol
{"pomoc"},
{"help - wyświetla pomoc (o nikt na to nie wpadł...) \n zasady - wyświetla ogólne zasady \n jak wpisywac cyfry w wierszu? - \n jak wpisywac cyfry w kolumnie? - \n jak wpisywac cyfry w kwadracie? - \n czy w kolumnie musza byc rozne cyfry? - \n podpowiedz - wyświetla podpowiedź(och... Rly?) \n cyfry w kwadracie/kolumnie/wierszu - wyświetla podpowiedż na temat kwadratu/kolumny/wiersza \n podpowiedz kwadrat/kolumne/wiersz - podpowiada najłatwiejszy kwadrat/kolumne/wiersz \n opowiedz cos \n jaki jest sens zycia? "},
{"podpowiedz"},
{"w x=2 y=4 moze byc odpowiedz 9","w x=5 y=1 moze byc odpowiedz 6","w x=7 y=5 moze byc odpowiedz 3","w x=9 y=3 moze byc odpowiedz 6","w x=1 y=3 moze byc odpowiedz 4","w x=6 y=6 moze byc odpowiedz 2","w x=7 y=4 moze byc odpowiedz 9","w x=5 y=3 moze byc odpowiedz 9","w x=3 y=4 moze byc odpowiedz 1","w x=8 y=7 moze byc odpowiedz 9","w x=3 y=7 moze byc odpowiedz 7","w x=9 y=1 moze byc odpowiedz 4",},
//cd -wiersze-ok
{"czy w wierszu musza byc rozne cyfry?"},
{"tak","oczywiœcie"},
{"kazda cyfra w wierszu musi byc inna?"},
{"tak","oczywiœcie"},
//cd -wiersze-nie ok
{"nie moge wpisac dwoch identycznych cyfr w wierszu?"},
{"Cyfry nie mogą się powtarzac","Każda cyfra może się pojawic tylko raz w każdym wierszu"},
{"czy cyfry w wierszu moga sie powtarzac?"},
{"Cyfry nie mogą się powtarzac","Każda cyfra może się pojawic tylko raz w każdym wierszu"},
{"jak wpisywac cyfry w wierszu?"},
{"Cyfry nie mogą się powtarzac","Każda cyfra może się pojawic tylko raz w każdym wierszu"},
//cd -kolumny-ok
{"kazda cyfra w kolumnie musi byc inna?"},
{"tak","oczywiœcie"},
{"czy w kolumnie musza byc rozne cyfry?"},
{"tak","oczywiœcie"},
//cd -kolumny-nie ok
{"nie moge wpisac dwoch identycznych cyfr w kolumny?"},
{"Cyfry nie mog¹ siê powtarzaæ","Ka¿da cyfra mo¿e siê pojawiæ tylko raz w ka¿dej kolumnie"},
{"czy cyfry w kolumnie moga sie powtarzac?"},
{"Cyfry nie mog¹ siê powtarzaæ","Ka¿da cyfra mo¿e siê pojawiæ tylko raz w ka¿dej kolumnie"},
{"jak wpisywac cyfry w kolumnie?"},
{"Cyfry nie mog¹ siê powtarzaæ","Ka¿da cyfra mo¿e siê pojawiæ tylko raz w ka¿dej kolumnie"},
//cd -kwadraty-ok
{"czy w kwadracie musza byc rozne cyfry?"},
{"tak","oczywiœcie"},
{"kazda cyfra w kwadracie musi byc inna?"},
{"tak","oczywiœcie"},
//cd -kwadraty-nie ok
{"nie moge wpisac dwoch identycznych cyfr w kwadracie?","czy cyfry w kwadracie moga sie powtarzac?","jak wpisywac cyfry w kwadracie?"},
{"Cyfry nie mog¹ siê powtarzaæ","Ka¿da cyfra mo¿e siê pojawiæ tylko raz w ka¿dym kwadracie"},
{"kim jestes?"},
{"jestem człowiekobotem, jasne ze czuję i myślę","a jak Ty sądzisz?","nie wiem czy chcê odpowiadaæ na to pytanie"},
//regu³y wiersz
{"jakie sa reguly w wierszu?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym wierszu. Cyfry od 1 do 9"},
{"wiersz?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym wierszu. Cyfry od 1 do 9"},
{"jak wpisywac cyfry do wiersza?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym wierszu. Cyfry od 1 do 9"},
{"jakie cyfry wpisywac do wiersza?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym wierszu. Cyfry od 1 do 9"},
//regu³y kolumna
{"jakie sa reguly w kolumnie?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdej kolumnie. Cyfry od 1 do 9"},
{"kolumna?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdej kolumnie. Cyfry od 1 do 9"},
{"jak wpisywac cyfry do kolumny?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdej kolumnie. Cyfry od 1 do 9"},
{"jakie cyfry wpisywac do kolumny?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdej kolumnie. Cyfry od 1 do 9"},
{"pomoz"},
{"help - wyświetla pomoc (o nikt na to nie wpadł...) \n zasady - wyświetla ogólne zasady \n jak wpisywac cyfry w wierszu? - \n jak wpisywac cyfry w kolumnie? - \n jak wpisywac cyfry w kwadracie? - \n czy w kolumnie musza byc rozne cyfry? - \n podpowiedz - wyświetla podpowiedź(och... Rly?) \n cyfry w kwadracie/kolumnie/wierszu - wyświetla podpowiedż na temat kwadratu/kolumny/wiersza \n podpowiedz kwadrat/kolumne/wiersz - podpowiada najłatwiejszy kwadrat/kolumne/wiersz \n opowiedz cos \n jaki jest sens zycia? "},
{"jakie sa reguly w kwadracie?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym kwadracie. Cyfry od 1 do 9"},
{"kwadrat?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym kwadracie. Cyfry od 1 do 9"},
{"jak wpisywac cyfry do kwadratu?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym kwadracie. Cyfry od 1 do 9"},
{"jakie cyfry wpisywac do kwadratu?","kwadrat-jak wpisywac?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym kwadracie. Cyfry od 1 do 9"},
//regu³y wiersz
{"jakie sa reguly w kwadracie?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym kwadracie. Cyfry od 1 do 9"},
{"kwadrat?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym kwadracie. Cyfry od 1 do 9"},
{"jak wpisywac cyfry do kwadratu?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym kwadracie. Cyfry od 1 do 9"},
{"jakie cyfry wpisywac do kwadratu?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym kwadracie. Cyfry od 1 do 9"},
{"kwadrat-jak wpisywac?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym kwadracie. Cyfry od 1 do 9"},
//regu³y-nie zrozumiane
{"jak grac?"},
{"nie rozumiem, uzyj googla albo inaczej sformuuj pytanie o zasady jaśniej"},
//HELP
{"help"},
{"help - wyświetla pomoc (o nikt na to nie wpadł...) \n zasady - wyświetla ogólne zasady \n kim jestes? \n jak wpisywac cyfry w wierszu? - \n jak wpisywac cyfry w kolumnie? - \n jak wpisywac cyfry w kwadracie? - \n czy w kolumnie musza byc rozne cyfry? - \n podpowiedz - wyświetla podpowiedź(och... Rly?) \n cyfry w kwadracie/kolumnie/wierszu - wyświetla podpowiedż na temat kwadratu/kolumny/wiersza \n podpowiedz kwadrat/kolumne/wiersz - podpowiada najłatwiejszy kwadrat/kolumne/wiersz \n opowiedz cos \n jaki jest sens zycia? "},
//Historia
{"bajka"},
{"Piał kogucik: kukuryku! \n Wstawaj rano, mój chłopczyku.\n A chłopczyk się ze snu budzi,\n Patrzy.... dużo chodzi ludzi;\n Więc się szybko zrywa z łóżka,\n By nie uszedł za leniuszka;\n I rzekł: za twe kukuryku\n Dziękuję ci koguciku."},
{"opowiedz mi bajke"},
{"Piał kogucik: kukuryku! \n Wstawaj rano, mój chłopczyku.\n A chłopczyk się ze snu budzi,\n Patrzy.... dużo chodzi ludzi;\n Więc się szybko zrywa z łóżka,\n By nie uszedł za leniuszka;\n I rzekł: za twe kukuryku\n Dziękuję ci koguciku."},
//Standard
{"Nie panimaju","Napisz coś normalnego...","Facepalm","Nie rozumie",
"Nie wiem o co chodzi. Masz ziemniaka.", "No ten tego, nie wiem", "że co?"},
};
public void keyReleased(KeyEvent e){
if(e.getKeyCode()==KeyEvent.VK_ENTER){
TextInput.setEditable(true);
}
}
public void keyTyped(KeyEvent e){}
public void addTextToBox(String s){
ChatBox.setText(ChatBox.getText()+s);
}
//fcja sprawdza czy stringi s¹ sobie równe
public boolean Match(String in,String[] s){
boolean match=false;
for(int i=0;i<s.length;i++){
if(s[i].equals(in)){
match=true;
}
}
return match;
}
public ChatBot(){
super("Sudoku Chat Bot");
setSize(800,400);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
ChatBox.setEditable(false);
TextInput.addKeyListener(this);
MainWindow.setBackground(new Color(0,200,0));
MainWindow.add(Scroll);
MainWindow.add(TextInput);
add(MainWindow);
setVisible(true);
//addTextToBox(Integer.toString(ChatBotText.length-1)+"\n");
//addTextToBox(Integer.toString(ChatBotText[ChatBotText.length-1].length)+"\n");
}
public void keyPressed(KeyEvent e){
if(e.getKeyCode()==KeyEvent.VK_ENTER){
TextInput.setEditable(false);
String input=TextInput.getText();
TextInput.setText("");
addTextToBox("--->You:\t"+input);
input.trim();
//while(
// input.charAt(input.length()-1)=='!' ||
// input.charAt(input.length()-1)=='.' ||
// input.charAt(input.length()-1)=='?'
//){
// input=input.substring(0,input.length()-1);
//}
input.trim();
byte re=0;
//lenght -1 poniewaz nie interesuje nas zawartosc ostatniego wiersza
// wiersze parzyste to odpowiedzi bota
// wiersze nieparzyste to input uzytkownika
//--Szukamy odpowiedzi bota na input
int j=0;//w ktorej grupie jestesmy
while(re==0){
if(Match(input.toLowerCase(),ChatBotText[j*2])){
re=2;
// losujemy odpowiedŸ
int r=(int)Math.floor(Math.random()*ChatBotText[(j*2)+1].length);
addTextToBox("\n-->SBOT:\t"+ChatBotText[(j*2)+1][r]);
}
j++;
//nie znalezlismy odpowiedzi
if(j*2==ChatBotText.length-1 && re==0){
re=1;
}
}
//-----Standatdowy output bota (jak nie znajdzie odpowiedzi)--------------
if(re==1){
// losujemy odpowiedŸ
int r=(int)Math.floor(Math.random()*ChatBotText[ChatBotText.length-1].length);
addTextToBox("\n-->SBOT:\t"+ChatBotText[ChatBotText.length-1][r]);
}
addTextToBox("\n");
}
}
}
| //nie znalezlismy odpowiedzi | package MAIN;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import java.awt.Color;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.lang.Math;
public class ChatBot extends JFrame implements KeyListener{
/**
*
*/
private static final long serialVersionUID = 1L;
JPanel MainWindow=new JPanel();
JTextArea c = new JTextArea();
JTextArea ChatBox=new JTextArea(20,70);
JTextArea TextInput=new JTextArea(1,70);
JScrollPane Scroll=new JScrollPane(
ChatBox,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
);
String[][] ChatBotText={
//demo
{"demo"},
{"Cześc \n jestem botem który umili ci czas podczas grania W Cudowne SUDOKU \n możesz mnie zapytac o wiele ciekawych informacji \n które znajdziesz pod komendą 'help'"},
//powitania
{"siema"},
{"Dzień Dobry","Szczęśc Boże"},
{"dzien dobry"},
{"Dzień Dobry","Szczęśc Boże"},
{"czesc"},
{"Dzień Dobry","Szczęśc Boże"},
{"hej"},
{"Dzień Dobry","Szczęśc Boże"},
{"siemano"},
{"Dzień Dobry","Szczęśc Boże"},
{"witaj", "witam"},
{"Dzień Dobry"},
{"witam"},
{"Dzień Dobry","Szczęśc Boże"},
//pozegnania
{"do widzenia"},
{"Nara","Bywaj","Z Bogiem","Daswidania"},
{"dobranoc",},
{"Nara","Bywaj","Z Bogiem","Daswidania"},
{"na razie"},
{"Nara","Bywaj","Z Bogiem","Daswidania"},
{"do zobaczenia"},
{"Nara","Bywaj","Z Bogiem","Daswidania"},
{"zegnaj"},
{"Nara","Bywaj","Z Bogiem","Daswidania"},
//pytania o samopoczucie
{"co tam","jak tam","co u ciebie","jak sie czujesz"},
{"Niezgorzej","Obleci", "Tak se"},
//regu³y gry w sudoku
{"zasady"},
{"W sudoku gra siê na planszy o wymiarach 9x9 podzielonej na \n mniejsze obszary o wymiarach 3x3. Na poczttku gry niektóre z pól \n planszy Sudoku s¹ ju¿ wype³nione liczbami. Celem gry jest \n uzupelnienie pozostalych pól planszy cyframi od 1 do 9 \n (po jednej cyfrze w kazdym polu)."},
{"podasz mi reguly sudoku?"},
{"W sudoku gra siê na planszy o wymiarach 9x9 podzielonej na \n mniejsze obszary o wymiarach 3x3. Na poczttku gry niektóre z pól \n planszy Sudoku s¹ ju¿ wype³nione liczbami. Celem gry jest \n uzupelnienie pozostalych pól planszy cyframi od 1 do 9 \n (po jednej cyfrze w kazdym polu)."},
{"jakie sa zasady sudoku?"},
{"W sudoku gra siê na planszy o wymiarach 9x9 podzielonej na \n mniejsze obszary o wymiarach 3x3. Na poczttku gry niektóre z pól \n planszy Sudoku s¹ ju¿ wype³nione liczbami. Celem gry jest \n uzupelnienie pozostalych pól planszy cyframi od 1 do 9 \n (po jednej cyfrze w kazdym polu)."},
{"jak grac w sudoku?"},
{"W sudoku gra siê na planszy o wymiarach 9x9 podzielonej na \n mniejsze obszary o wymiarach 3x3. Na poczttku gry niektóre z pól \n planszy Sudoku s¹ ju¿ wype³nione liczbami. Celem gry jest \n uzupelnienie pozostalych pól planszy cyframi od 1 do 9 \n (po jednej cyfrze w kazdym polu)."},
{"znasz reguly sudoku?"},
{"W sudoku gra siê na planszy o wymiarach 9x9 podzielonej na \n mniejsze obszary o wymiarach 3x3. Na poczttku gry niektóre z pól \n planszy Sudoku s¹ ju¿ wype³nione liczbami. Celem gry jest \n uzupelnienie pozostalych pól planszy cyframi od 1 do 9 \n (po jednej cyfrze w kazdym polu)."},
//NIE
{"tak"},
{"Dlaczego tak?","A mo¿e nie?","Nie Nie Nie!!!!!!!"},
//NIE
{"nie"},
{"Dlaczego nie?","A mo¿e tak?","TAK TAK TAK!!!!!!!"},
//osobowosc
{"co lubisz?"},
{"nie wiem, jestem botem","co Ty slepy?","bota pytasz?"},
{"Twoja ulubiona rzecz?"},
{"nie wiem, jestem botem","co Ty slepy?","bota pytasz?"},
{"masz zainteresowania?"},
{"nie wiem, jestem botem","co Ty slepy?","bota pytasz?"},
{"czy myslisz?"},
{"jestem człowiekobotem, jasne ze czuję i myślę","a jak Ty sądzisz?","nie wiem czy chcê odpowiadaæ na to pytanie"},
{"masz hobby?"},
{"nie wiem, jestem botem","co Ty slepy?","bota pytasz?"},
{"masz pasje?"},
{"nie wiem, jestem botem","co Ty slepy?","bota pytasz?"},
//helperr
{"czy mozesz mi pomoc?","chcia³bym bys mi pomogl","potrzebuje pomocy","pomozesz mi?"},
{"why not?","no dobra ³ajzo","je¿eli ¿¹dasz","a ile p³acisz? no dobra nie jestem materialist¹ jestem botem","niech pomyœlê...ok..."},
//helper
{"masz mi pomoc"},
{"co ja murzyn?","nie będę Twoim niewolnikiem","wal się","no chyba nie","skąd się urwałeś?"},
{"do roboty"},
{"co ja murzyn?","nie będę Twoim niewolnikiem","wal się","no chyba nie","skąd się urwałeś?"},
{"musisz mi pomoc"},
{"co ja murzyn?","nie będę Twoim niewolnikiem","wal się","no chyba nie","skąd się urwałeś?"},
{"rób!"},
{"co ja murzyn?","nie będę Twoim niewolnikiem","wal się","no chyba nie","skąd się urwałeś?"},
//obrazliwe
{"Ty debilu"},
{"nie gadam z Tobą","chyba Ty tej","zal..."},
{"jestes głupi"},
{"nie gadam z Tobą","chyba Ty tej","zal..."},
{"kretyn"},
{"nie gadam z Tobą","chyba Ty tej","zal..."},
{"idiota"},
{"taaa"},
{"pełnym zdaniem proszę","nie wiem, Ty musiszz zdecydowac","jestem elokwentniejszy"},
{"i?"},
{"pełnym zdaniem proszę","nie wiem, Ty musiszz zdecydowac","jestem elokwentniejszy"},
{"nie gadam z Tobą","chyba Ty tej","zal..."},
{"Imbecyl"},
{"nie gadam z Tobą","chyba Ty tej","zal..."},
//opowiastki
{"powiesz cos ciekawego?"},
{"przecież jestem botem, nie znam historyjek","mam bugi w kodzie","pssst, moi programiœci nic nie umieją"},
{"opowiedz cos"},
{"przecież jestem botem, nie znam historyjek","mam bugi w kodzie","pssst, moi programiœci nic nie umieją"},
{"co tam w świecie?"},
{"przecież jestem botem, nie znam historyjek","mam bugi w kodzie","pssst, moi programiœci nic nie umieją"},
{"opowiedz historie"},
{"przecież jestem botem, nie znam historyjek","mam bugi w kodzie","pssst, moi programiœci nic nie umieją"},
//podtrzymanie rozmowy
{"no i?"},
{"pełnym zdaniem proszę","nie wiem, Ty musiszz zdecydowac","jestem elokwentniejszy"},
{"co z tego?"},
{"pełnym zdaniem proszę","nie wiem, Ty musiszz zdecydowac","jestem elokwentniejszy"},
{"co dalej?",},
{"pełnym zdaniem proszę","nie wiem, Ty musiszz zdecydowac","jestem elokwentniejszy"},
{"mhm"},
{"pełnym zdaniem proszę","nie wiem, Ty musiszz zdecydowac","jestem elokwentniejszy"},
{"hmmm"},
{"pełnym zdaniem proszę","nie wiem, Ty musiszz zdecydowac","jestem elokwentniejszy"},
//bycie botem
{"jestes botem?"},
{"jestem człowiekobotem, jasne ze czuję i myślę","a jak Ty sądzisz?","nie wiem czy chcê odpowiadaæ na to pytanie"},
{"jestes czlowiekiem?"},
{"jestem człowiekobotem, jasne ze czuję i myślę","a jak Ty sądzisz?","nie wiem czy chcê odpowiadaæ na to pytanie"},
{"Ty idioto"},
{"nie gadam z Tobą","chyba Ty tej","zal..."},
{"Ty kretynie"},
{"nie gadam z Tobą","chyba Ty tej","zal..."},
{"potrafisz czuc?"},
{"jestem człowiekobotem, jasne ze czuję i myślę","a jak Ty sądzisz?","nie wiem czy chcê odpowiadaæ na to pytanie"},
{"czy masz uczucia?"},
{"jestem człowiekobotem, jasne ze czuję i myślę","a jak Ty sądzisz?","nie wiem czy chcê odpowiadaæ na to pytanie"},
//sens istnienia
{"sens zycia","jaki jest sens istnienia?","jaki jest sens zycia?","po co ¿yjemy?","co sie w zyciu liczy?","jak zyc?"},
{"jedno s³owo - JAVA"},
//wiara
{"jestes wierzacy?"},
{"nie jestem upowa¿niony do odpowiadania \n na tego typu pytania \n #poprawnoœcPolityczna"},
{"istnieje bog?"},
{"nie jestem upowa¿niony do odpowiadania \n na tego typu pytania \n #poprawnoœcPolityczna"},
{"chodzisz do kosciola?"},
{"nie jestem upowa¿niony do odpowiadania \n na tego typu pytania \n #poprawnoœcPolityczna"},
//lol
{"pomoc"},
{"help - wyświetla pomoc (o nikt na to nie wpadł...) \n zasady - wyświetla ogólne zasady \n jak wpisywac cyfry w wierszu? - \n jak wpisywac cyfry w kolumnie? - \n jak wpisywac cyfry w kwadracie? - \n czy w kolumnie musza byc rozne cyfry? - \n podpowiedz - wyświetla podpowiedź(och... Rly?) \n cyfry w kwadracie/kolumnie/wierszu - wyświetla podpowiedż na temat kwadratu/kolumny/wiersza \n podpowiedz kwadrat/kolumne/wiersz - podpowiada najłatwiejszy kwadrat/kolumne/wiersz \n opowiedz cos \n jaki jest sens zycia? "},
{"podpowiedz"},
{"w x=2 y=4 moze byc odpowiedz 9","w x=5 y=1 moze byc odpowiedz 6","w x=7 y=5 moze byc odpowiedz 3","w x=9 y=3 moze byc odpowiedz 6","w x=1 y=3 moze byc odpowiedz 4","w x=6 y=6 moze byc odpowiedz 2","w x=7 y=4 moze byc odpowiedz 9","w x=5 y=3 moze byc odpowiedz 9","w x=3 y=4 moze byc odpowiedz 1","w x=8 y=7 moze byc odpowiedz 9","w x=3 y=7 moze byc odpowiedz 7","w x=9 y=1 moze byc odpowiedz 4",},
//cd -wiersze-ok
{"czy w wierszu musza byc rozne cyfry?"},
{"tak","oczywiœcie"},
{"kazda cyfra w wierszu musi byc inna?"},
{"tak","oczywiœcie"},
//cd -wiersze-nie ok
{"nie moge wpisac dwoch identycznych cyfr w wierszu?"},
{"Cyfry nie mogą się powtarzac","Każda cyfra może się pojawic tylko raz w każdym wierszu"},
{"czy cyfry w wierszu moga sie powtarzac?"},
{"Cyfry nie mogą się powtarzac","Każda cyfra może się pojawic tylko raz w każdym wierszu"},
{"jak wpisywac cyfry w wierszu?"},
{"Cyfry nie mogą się powtarzac","Każda cyfra może się pojawic tylko raz w każdym wierszu"},
//cd -kolumny-ok
{"kazda cyfra w kolumnie musi byc inna?"},
{"tak","oczywiœcie"},
{"czy w kolumnie musza byc rozne cyfry?"},
{"tak","oczywiœcie"},
//cd -kolumny-nie ok
{"nie moge wpisac dwoch identycznych cyfr w kolumny?"},
{"Cyfry nie mog¹ siê powtarzaæ","Ka¿da cyfra mo¿e siê pojawiæ tylko raz w ka¿dej kolumnie"},
{"czy cyfry w kolumnie moga sie powtarzac?"},
{"Cyfry nie mog¹ siê powtarzaæ","Ka¿da cyfra mo¿e siê pojawiæ tylko raz w ka¿dej kolumnie"},
{"jak wpisywac cyfry w kolumnie?"},
{"Cyfry nie mog¹ siê powtarzaæ","Ka¿da cyfra mo¿e siê pojawiæ tylko raz w ka¿dej kolumnie"},
//cd -kwadraty-ok
{"czy w kwadracie musza byc rozne cyfry?"},
{"tak","oczywiœcie"},
{"kazda cyfra w kwadracie musi byc inna?"},
{"tak","oczywiœcie"},
//cd -kwadraty-nie ok
{"nie moge wpisac dwoch identycznych cyfr w kwadracie?","czy cyfry w kwadracie moga sie powtarzac?","jak wpisywac cyfry w kwadracie?"},
{"Cyfry nie mog¹ siê powtarzaæ","Ka¿da cyfra mo¿e siê pojawiæ tylko raz w ka¿dym kwadracie"},
{"kim jestes?"},
{"jestem człowiekobotem, jasne ze czuję i myślę","a jak Ty sądzisz?","nie wiem czy chcê odpowiadaæ na to pytanie"},
//regu³y wiersz
{"jakie sa reguly w wierszu?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym wierszu. Cyfry od 1 do 9"},
{"wiersz?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym wierszu. Cyfry od 1 do 9"},
{"jak wpisywac cyfry do wiersza?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym wierszu. Cyfry od 1 do 9"},
{"jakie cyfry wpisywac do wiersza?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym wierszu. Cyfry od 1 do 9"},
//regu³y kolumna
{"jakie sa reguly w kolumnie?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdej kolumnie. Cyfry od 1 do 9"},
{"kolumna?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdej kolumnie. Cyfry od 1 do 9"},
{"jak wpisywac cyfry do kolumny?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdej kolumnie. Cyfry od 1 do 9"},
{"jakie cyfry wpisywac do kolumny?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdej kolumnie. Cyfry od 1 do 9"},
{"pomoz"},
{"help - wyświetla pomoc (o nikt na to nie wpadł...) \n zasady - wyświetla ogólne zasady \n jak wpisywac cyfry w wierszu? - \n jak wpisywac cyfry w kolumnie? - \n jak wpisywac cyfry w kwadracie? - \n czy w kolumnie musza byc rozne cyfry? - \n podpowiedz - wyświetla podpowiedź(och... Rly?) \n cyfry w kwadracie/kolumnie/wierszu - wyświetla podpowiedż na temat kwadratu/kolumny/wiersza \n podpowiedz kwadrat/kolumne/wiersz - podpowiada najłatwiejszy kwadrat/kolumne/wiersz \n opowiedz cos \n jaki jest sens zycia? "},
{"jakie sa reguly w kwadracie?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym kwadracie. Cyfry od 1 do 9"},
{"kwadrat?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym kwadracie. Cyfry od 1 do 9"},
{"jak wpisywac cyfry do kwadratu?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym kwadracie. Cyfry od 1 do 9"},
{"jakie cyfry wpisywac do kwadratu?","kwadrat-jak wpisywac?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym kwadracie. Cyfry od 1 do 9"},
//regu³y wiersz
{"jakie sa reguly w kwadracie?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym kwadracie. Cyfry od 1 do 9"},
{"kwadrat?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym kwadracie. Cyfry od 1 do 9"},
{"jak wpisywac cyfry do kwadratu?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym kwadracie. Cyfry od 1 do 9"},
{"jakie cyfry wpisywac do kwadratu?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym kwadracie. Cyfry od 1 do 9"},
{"kwadrat-jak wpisywac?"},
{"Kazda cyfra moze sie pojawic tylko raz w kazdym kwadracie. Cyfry od 1 do 9"},
//regu³y-nie zrozumiane
{"jak grac?"},
{"nie rozumiem, uzyj googla albo inaczej sformuuj pytanie o zasady jaśniej"},
//HELP
{"help"},
{"help - wyświetla pomoc (o nikt na to nie wpadł...) \n zasady - wyświetla ogólne zasady \n kim jestes? \n jak wpisywac cyfry w wierszu? - \n jak wpisywac cyfry w kolumnie? - \n jak wpisywac cyfry w kwadracie? - \n czy w kolumnie musza byc rozne cyfry? - \n podpowiedz - wyświetla podpowiedź(och... Rly?) \n cyfry w kwadracie/kolumnie/wierszu - wyświetla podpowiedż na temat kwadratu/kolumny/wiersza \n podpowiedz kwadrat/kolumne/wiersz - podpowiada najłatwiejszy kwadrat/kolumne/wiersz \n opowiedz cos \n jaki jest sens zycia? "},
//Historia
{"bajka"},
{"Piał kogucik: kukuryku! \n Wstawaj rano, mój chłopczyku.\n A chłopczyk się ze snu budzi,\n Patrzy.... dużo chodzi ludzi;\n Więc się szybko zrywa z łóżka,\n By nie uszedł za leniuszka;\n I rzekł: za twe kukuryku\n Dziękuję ci koguciku."},
{"opowiedz mi bajke"},
{"Piał kogucik: kukuryku! \n Wstawaj rano, mój chłopczyku.\n A chłopczyk się ze snu budzi,\n Patrzy.... dużo chodzi ludzi;\n Więc się szybko zrywa z łóżka,\n By nie uszedł za leniuszka;\n I rzekł: za twe kukuryku\n Dziękuję ci koguciku."},
//Standard
{"Nie panimaju","Napisz coś normalnego...","Facepalm","Nie rozumie",
"Nie wiem o co chodzi. Masz ziemniaka.", "No ten tego, nie wiem", "że co?"},
};
public void keyReleased(KeyEvent e){
if(e.getKeyCode()==KeyEvent.VK_ENTER){
TextInput.setEditable(true);
}
}
public void keyTyped(KeyEvent e){}
public void addTextToBox(String s){
ChatBox.setText(ChatBox.getText()+s);
}
//fcja sprawdza czy stringi s¹ sobie równe
public boolean Match(String in,String[] s){
boolean match=false;
for(int i=0;i<s.length;i++){
if(s[i].equals(in)){
match=true;
}
}
return match;
}
public ChatBot(){
super("Sudoku Chat Bot");
setSize(800,400);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
ChatBox.setEditable(false);
TextInput.addKeyListener(this);
MainWindow.setBackground(new Color(0,200,0));
MainWindow.add(Scroll);
MainWindow.add(TextInput);
add(MainWindow);
setVisible(true);
//addTextToBox(Integer.toString(ChatBotText.length-1)+"\n");
//addTextToBox(Integer.toString(ChatBotText[ChatBotText.length-1].length)+"\n");
}
public void keyPressed(KeyEvent e){
if(e.getKeyCode()==KeyEvent.VK_ENTER){
TextInput.setEditable(false);
String input=TextInput.getText();
TextInput.setText("");
addTextToBox("--->You:\t"+input);
input.trim();
//while(
// input.charAt(input.length()-1)=='!' ||
// input.charAt(input.length()-1)=='.' ||
// input.charAt(input.length()-1)=='?'
//){
// input=input.substring(0,input.length()-1);
//}
input.trim();
byte re=0;
//lenght -1 poniewaz nie interesuje nas zawartosc ostatniego wiersza
// wiersze parzyste to odpowiedzi bota
// wiersze nieparzyste to input uzytkownika
//--Szukamy odpowiedzi bota na input
int j=0;//w ktorej grupie jestesmy
while(re==0){
if(Match(input.toLowerCase(),ChatBotText[j*2])){
re=2;
// losujemy odpowiedŸ
int r=(int)Math.floor(Math.random()*ChatBotText[(j*2)+1].length);
addTextToBox("\n-->SBOT:\t"+ChatBotText[(j*2)+1][r]);
}
j++;
//nie znalezlismy <SUF>
if(j*2==ChatBotText.length-1 && re==0){
re=1;
}
}
//-----Standatdowy output bota (jak nie znajdzie odpowiedzi)--------------
if(re==1){
// losujemy odpowiedŸ
int r=(int)Math.floor(Math.random()*ChatBotText[ChatBotText.length-1].length);
addTextToBox("\n-->SBOT:\t"+ChatBotText[ChatBotText.length-1][r]);
}
addTextToBox("\n");
}
}
}
| null |
5147_4 | NorwinYu/UoN-Final-Year-Project-Public-Database | 3,261 | Download-Java-Files/Defective/i-696-c-1-Polish.java | package tillerino.tillerinobot.lang;
import java.util.List;
import java.util.Random;
import org.tillerino.osuApiModel.Mods;
import org.tillerino.osuApiModel.OsuApiUser;
import tillerino.tillerinobot.CommandHandler.Action;
import tillerino.tillerinobot.CommandHandler.Message;
import tillerino.tillerinobot.CommandHandler.Response;
/**
* Polish language implementation.
* Pawwit https://osu.ppy.sh/u/2070907 & LilSilv https://github.com/LilSilv https://osu.ppy.sh/users/8488688
*/
public class Polish extends AbstractMutableLanguage {
private static final long serialVersionUID = 1L;
static final Random rnd = new Random();
@Override
public String unknownBeatmap() {
return "Przykro mi, nie rozpoznaję tej mapy. Możliwe że jest nowa, bardzo trudna, nierankingowa lub z innego trybu niż osu!standard";
}
@Override
public String internalException(String marker) {
return "Ugh... Wygląda na to, że ludzki Tillerino uszkodził moje obwody."
+ " Gdyby wkrótce tego nie zauważył, mógłbyś go [https://github.com/Tillerino/Tillerinobot/wiki/Contact poinformować]? (odwołanie "
+ marker + ")";
}
@Override
public String externalException(String marker) {
return "Co jest?! Odpowiedź serwera osu nie ma sensu. Możesz mi powiedzieć, co to ma znaczyć? 0011101001010000"
+ " Ludzki Tillerino mówi, żeby się tym nie przejmować, i że powinniśmy spróbować jeszcze raz."
+ " Jeżeli z jakiegoś powodu jesteś zaniepokojony, możesz [https://github.com/Tillerino/Tillerinobot/wiki/Contact powiedzieć mu] o tym. (odwołanie "
+ marker + ")";
}
@Override
public String noInformationForModsShort() {
return "brak danych dla wskazanych modów";
}
@Override
public Response welcomeUser(OsuApiUser apiUser, long inactiveTime) {
if (inactiveTime < 60 * 1000) {
return new Message("beep boop");
} else if (inactiveTime < 24 * 60 * 60 * 1000) {
return new Message("Witaj ponownie, " + apiUser.getUserName() + ".");
} else if (inactiveTime > 7l * 24 * 60 * 60 * 1000) {
return new Message(apiUser.getUserName() + "...")
.then(new Message("...czy to Ty? Minęło sporo czasu!"))
.then(new Message("Dobrze znowu Cię widzieć. Chcesz usłyszeć kilka rekomendacji?"));
} else {
String[] messages = {
"wyglądasz jakbyś chciał rekomendacji.",
"jak dobrze Cię widzieć! :)",
"mój ulubiony człowiek. (Nie mów o tym innym człowiekom!)",
"jakie miłe zaskoczenie! ^.^",
"Miałem nadzieję, że się pojawisz. Jesteś fajniejszy niż inni ludzie, ale nie mów im, że Ci to powiedziałem! :3",
"na co masz dzisiaj ochotę?",
};
Random random = new Random();
String message = messages[random.nextInt(messages.length)];
return new Message(apiUser.getUserName() + ", " + message);
}
}
@Override
public String unknownCommand(String command) {
return "Nieznana komenda \"" + command
+ "\". Napisz !help jeśli potrzebujesz pomocy!";
}
@Override
public String noInformationForMods() {
return "Przykro mi, nie mogę dostarczyć informacji dla tych modów w tym momencie.";
}
@Override
public String malformattedMods(String mods) {
return "Coś się nie zgadza. Mody mogą być dowolną kombinacją DT HR HD HT EZ NC FL SO NF. Łącz je nie używając spacji ani żadnych znaków. Przykład: !with HDHR, !with DTEZ";
}
@Override
public String noLastSongInfo() {
return "Nie pamiętam, żebyś pytał się ostatnio o jakąś mapę...";
}
@Override
public String tryWithMods() {
return "Spróbuj zagrać tę mapę z modami!";
}
@Override
public String tryWithMods(List<Mods> mods) {
return "Spróbuj zagrać tę mapę z " + Mods.toShortNamesContinuous(mods) + "!";
}
@Override
public String excuseForError() {
return "Wybacz, widziałem piękną sekwencję zer i jedynek, przez co trochę się rozkojarzyłem. Mógłbyś powtórzyć co chciałeś?";
}
@Override
public String complaint() {
return "Twoje zgłoszenie zostało wypełnione. Tillerino zerknie na nie, jak tylko będzie mógł.";
}
@Override
public Response hug(OsuApiUser apiUser) {
return new Message("Chodź no tu!")
.then(new Action("przytula " + apiUser.getUserName()));
}
@Override
public String help() {
return "Hej! Jestem robotem, który zabił Tillerino i przejął jego konto. Żartowałem, ale często używam tego konta."
+ " [https://twitter.com/Tillerinobot status i aktualizacje]"
+ " - [https://github.com/Tillerino/Tillerinobot/wiki komendy]"
+ " - [http://ppaddict.tillerino.org/ ppaddict]"
+ " - [https://github.com/Tillerino/Tillerinobot/wiki/Contact kontakt]";
}
@Override
public String faq() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ Często zadawane pytania]";
}
@Override
public String featureRankRestricted(String feature, int minRank, OsuApiUser user) {
return "Wybacz, ale w tym momencie " + feature + " jest dostępna tylko dla graczy, którzy przekroczyli pozycję " + minRank + " w rankingu.";
}
@Override
public String mixedNomodAndMods() {
return "Jak chcesz połączyć brak modów z modami?";
}
@Override
public String outOfRecommendations() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do"
+ " Skończyły mi się pomysły co mogę Ci jeszcze polecić]."
+ " Sprawdź inne opcje polecania albo użyj komendy !reset. Jeśli potrzebujesz więcej szczegółów, wpisz !help.";
}
@Override
public String notRanked() {
return "Wygląda na to, że ta mapa nie jest rankingowa.";
}
@Override
public String invalidAccuracy(String acc) {
return "Nieprawidłowa celność: \"" + acc + "\"";
}
@Override
public Response optionalCommentOnLanguage(OsuApiUser apiUser) {
return new Message("[https://osu.ppy.sh/users/1698537 Pawwit] i [https://osu.ppy.sh/users/8488688 Lil Silv] nauczyli mnie mówić po polsku. Jeśli uważasz, że gdzieś się pomylili, napisz do nich na osu!");
}
@Override
public String invalidChoice(String invalid, String choices) {
return "Wybacz, nie wiem co oznacza \"" + invalid
+ "\". Spróbuj: " + choices + "!";
}
@Override
public String setFormat() {
return "Składnia polecenia !set jest następująca: !set opcja wartość. Wpisz !help jeśli potrzebujesz więcej wskazówek.";
}
StringShuffler apiTimeoutShuffler = new StringShuffler(rnd);
@Override
public String apiTimeoutException() {
registerModification();
final String message = "Serwery osu! obecnie działają bardzo wolno, więc w tym momencie nie mogę nic dla Ciebie zrobić. ";
return message + apiTimeoutShuffler.get(
"Powiedz... Kiedy był ostatni raz, gdy rozmawiałeś ze swoją babcią?",
"Może posprzątasz swój pokój, a potem zapytasz jeszcze raz?",
"Stawiam, że chętnie byś poszedł na spacerek. Wiesz... na zewnątrz",
"Jestem pewien, że masz kilka innych rzeczy do zrobienia. Może zrobisz je teraz?",
"Wyglądasz jakbyś potrzebował drzemki",
"Ale sprawdź tą super interesującą stronę na [https://pl.wikipedia.org/wiki/Special:Random Wikipedii]!",
"Sprawdźmy czy ktoś niezły teraz [http://www.twitch.tv/directory/game/Osu! streamuje]!",
"Zobacz, kolejna [http://dagobah.net/flash/Cursor_Invisible.swf gra], w którą pewnie ssiesz!",
"Powinieneś mieć teraz wystarczająco dużo czasu na przeczytanie [https://github.com/Tillerino/Tillerinobot/wiki mojej instrukcji].",
"Nie martw się, te [https://www.reddit.com/r/osugame dank memy] powinny Ci pomóc zabić czas.",
"Jeśli się nudzisz, wypróbuj [http://gabrielecirulli.github.io/2048/ 2048]!",
"Zabawne pytanie: Jeśli twój dysk twardy by się teraz zepsuł, ile twoich osobistych danych przepadłoby na zawsze?",
"Więc... Próbowałeś kiedyś [https://www.google.pl/search?q=bring%20sally%20up%20push%20up%20challenge wyzwania sally up push up]?",
"Możesz iść robić coś innego, lub możemy gapić się na siebie nawzajem. W ciszy."
);
}
@Override
public String noRecentPlays() {
return "Nie widziałem, żebyś ostatnio grał.";
}
@Override
public String isSetId() {
return "To odwołuje się do zestawu map, a nie do jednej mapy.";
}
}
| //github.com/Tillerino/Tillerinobot/wiki/FAQ Często zadawane pytania]"; | package tillerino.tillerinobot.lang;
import java.util.List;
import java.util.Random;
import org.tillerino.osuApiModel.Mods;
import org.tillerino.osuApiModel.OsuApiUser;
import tillerino.tillerinobot.CommandHandler.Action;
import tillerino.tillerinobot.CommandHandler.Message;
import tillerino.tillerinobot.CommandHandler.Response;
/**
* Polish language implementation.
* Pawwit https://osu.ppy.sh/u/2070907 & LilSilv https://github.com/LilSilv https://osu.ppy.sh/users/8488688
*/
public class Polish extends AbstractMutableLanguage {
private static final long serialVersionUID = 1L;
static final Random rnd = new Random();
@Override
public String unknownBeatmap() {
return "Przykro mi, nie rozpoznaję tej mapy. Możliwe że jest nowa, bardzo trudna, nierankingowa lub z innego trybu niż osu!standard";
}
@Override
public String internalException(String marker) {
return "Ugh... Wygląda na to, że ludzki Tillerino uszkodził moje obwody."
+ " Gdyby wkrótce tego nie zauważył, mógłbyś go [https://github.com/Tillerino/Tillerinobot/wiki/Contact poinformować]? (odwołanie "
+ marker + ")";
}
@Override
public String externalException(String marker) {
return "Co jest?! Odpowiedź serwera osu nie ma sensu. Możesz mi powiedzieć, co to ma znaczyć? 0011101001010000"
+ " Ludzki Tillerino mówi, żeby się tym nie przejmować, i że powinniśmy spróbować jeszcze raz."
+ " Jeżeli z jakiegoś powodu jesteś zaniepokojony, możesz [https://github.com/Tillerino/Tillerinobot/wiki/Contact powiedzieć mu] o tym. (odwołanie "
+ marker + ")";
}
@Override
public String noInformationForModsShort() {
return "brak danych dla wskazanych modów";
}
@Override
public Response welcomeUser(OsuApiUser apiUser, long inactiveTime) {
if (inactiveTime < 60 * 1000) {
return new Message("beep boop");
} else if (inactiveTime < 24 * 60 * 60 * 1000) {
return new Message("Witaj ponownie, " + apiUser.getUserName() + ".");
} else if (inactiveTime > 7l * 24 * 60 * 60 * 1000) {
return new Message(apiUser.getUserName() + "...")
.then(new Message("...czy to Ty? Minęło sporo czasu!"))
.then(new Message("Dobrze znowu Cię widzieć. Chcesz usłyszeć kilka rekomendacji?"));
} else {
String[] messages = {
"wyglądasz jakbyś chciał rekomendacji.",
"jak dobrze Cię widzieć! :)",
"mój ulubiony człowiek. (Nie mów o tym innym człowiekom!)",
"jakie miłe zaskoczenie! ^.^",
"Miałem nadzieję, że się pojawisz. Jesteś fajniejszy niż inni ludzie, ale nie mów im, że Ci to powiedziałem! :3",
"na co masz dzisiaj ochotę?",
};
Random random = new Random();
String message = messages[random.nextInt(messages.length)];
return new Message(apiUser.getUserName() + ", " + message);
}
}
@Override
public String unknownCommand(String command) {
return "Nieznana komenda \"" + command
+ "\". Napisz !help jeśli potrzebujesz pomocy!";
}
@Override
public String noInformationForMods() {
return "Przykro mi, nie mogę dostarczyć informacji dla tych modów w tym momencie.";
}
@Override
public String malformattedMods(String mods) {
return "Coś się nie zgadza. Mody mogą być dowolną kombinacją DT HR HD HT EZ NC FL SO NF. Łącz je nie używając spacji ani żadnych znaków. Przykład: !with HDHR, !with DTEZ";
}
@Override
public String noLastSongInfo() {
return "Nie pamiętam, żebyś pytał się ostatnio o jakąś mapę...";
}
@Override
public String tryWithMods() {
return "Spróbuj zagrać tę mapę z modami!";
}
@Override
public String tryWithMods(List<Mods> mods) {
return "Spróbuj zagrać tę mapę z " + Mods.toShortNamesContinuous(mods) + "!";
}
@Override
public String excuseForError() {
return "Wybacz, widziałem piękną sekwencję zer i jedynek, przez co trochę się rozkojarzyłem. Mógłbyś powtórzyć co chciałeś?";
}
@Override
public String complaint() {
return "Twoje zgłoszenie zostało wypełnione. Tillerino zerknie na nie, jak tylko będzie mógł.";
}
@Override
public Response hug(OsuApiUser apiUser) {
return new Message("Chodź no tu!")
.then(new Action("przytula " + apiUser.getUserName()));
}
@Override
public String help() {
return "Hej! Jestem robotem, który zabił Tillerino i przejął jego konto. Żartowałem, ale często używam tego konta."
+ " [https://twitter.com/Tillerinobot status i aktualizacje]"
+ " - [https://github.com/Tillerino/Tillerinobot/wiki komendy]"
+ " - [http://ppaddict.tillerino.org/ ppaddict]"
+ " - [https://github.com/Tillerino/Tillerinobot/wiki/Contact kontakt]";
}
@Override
public String faq() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ Często <SUF>
}
@Override
public String featureRankRestricted(String feature, int minRank, OsuApiUser user) {
return "Wybacz, ale w tym momencie " + feature + " jest dostępna tylko dla graczy, którzy przekroczyli pozycję " + minRank + " w rankingu.";
}
@Override
public String mixedNomodAndMods() {
return "Jak chcesz połączyć brak modów z modami?";
}
@Override
public String outOfRecommendations() {
return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do"
+ " Skończyły mi się pomysły co mogę Ci jeszcze polecić]."
+ " Sprawdź inne opcje polecania albo użyj komendy !reset. Jeśli potrzebujesz więcej szczegółów, wpisz !help.";
}
@Override
public String notRanked() {
return "Wygląda na to, że ta mapa nie jest rankingowa.";
}
@Override
public String invalidAccuracy(String acc) {
return "Nieprawidłowa celność: \"" + acc + "\"";
}
@Override
public Response optionalCommentOnLanguage(OsuApiUser apiUser) {
return new Message("[https://osu.ppy.sh/users/1698537 Pawwit] i [https://osu.ppy.sh/users/8488688 Lil Silv] nauczyli mnie mówić po polsku. Jeśli uważasz, że gdzieś się pomylili, napisz do nich na osu!");
}
@Override
public String invalidChoice(String invalid, String choices) {
return "Wybacz, nie wiem co oznacza \"" + invalid
+ "\". Spróbuj: " + choices + "!";
}
@Override
public String setFormat() {
return "Składnia polecenia !set jest następująca: !set opcja wartość. Wpisz !help jeśli potrzebujesz więcej wskazówek.";
}
StringShuffler apiTimeoutShuffler = new StringShuffler(rnd);
@Override
public String apiTimeoutException() {
registerModification();
final String message = "Serwery osu! obecnie działają bardzo wolno, więc w tym momencie nie mogę nic dla Ciebie zrobić. ";
return message + apiTimeoutShuffler.get(
"Powiedz... Kiedy był ostatni raz, gdy rozmawiałeś ze swoją babcią?",
"Może posprzątasz swój pokój, a potem zapytasz jeszcze raz?",
"Stawiam, że chętnie byś poszedł na spacerek. Wiesz... na zewnątrz",
"Jestem pewien, że masz kilka innych rzeczy do zrobienia. Może zrobisz je teraz?",
"Wyglądasz jakbyś potrzebował drzemki",
"Ale sprawdź tą super interesującą stronę na [https://pl.wikipedia.org/wiki/Special:Random Wikipedii]!",
"Sprawdźmy czy ktoś niezły teraz [http://www.twitch.tv/directory/game/Osu! streamuje]!",
"Zobacz, kolejna [http://dagobah.net/flash/Cursor_Invisible.swf gra], w którą pewnie ssiesz!",
"Powinieneś mieć teraz wystarczająco dużo czasu na przeczytanie [https://github.com/Tillerino/Tillerinobot/wiki mojej instrukcji].",
"Nie martw się, te [https://www.reddit.com/r/osugame dank memy] powinny Ci pomóc zabić czas.",
"Jeśli się nudzisz, wypróbuj [http://gabrielecirulli.github.io/2048/ 2048]!",
"Zabawne pytanie: Jeśli twój dysk twardy by się teraz zepsuł, ile twoich osobistych danych przepadłoby na zawsze?",
"Więc... Próbowałeś kiedyś [https://www.google.pl/search?q=bring%20sally%20up%20push%20up%20challenge wyzwania sally up push up]?",
"Możesz iść robić coś innego, lub możemy gapić się na siebie nawzajem. W ciszy."
);
}
@Override
public String noRecentPlays() {
return "Nie widziałem, żebyś ostatnio grał.";
}
@Override
public String isSetId() {
return "To odwołuje się do zestawu map, a nie do jednej mapy.";
}
}
| null |
6058_1 | OkaeriPoland/okaeri-minecraft | 660 | noproxy/shared/src/main/java/eu/okaeri/minecraft/noproxy/shared/NoProxyConfig.java | /*
* OK! No.Proxy Minecraft
* Copyright (C) 2021 Okaeri, Dawid Sawicki
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.okaeri.minecraft.noproxy.shared;
import eu.okaeri.configs.OkaeriConfig;
import eu.okaeri.configs.annotation.*;
import eu.okaeri.platform.core.annotation.Configuration;
import lombok.Getter;
import java.util.Collections;
import java.util.List;
@Getter
@Configuration
@Header("################################################################")
@Header("# #")
@Header("# OK! No.Proxy Minecraft #")
@Header("# #")
@Header("# Nie wiesz jak skonfigurować? Zerknij do dokumentacji! #")
@Header("# https://wiki.okaeri.cloud/pl/uslugi/noproxy/minecraft #")
@Header("# #")
@Header("# Trouble configuring? Check out the documentation! #")
@Header("# https://wiki.okaeri.cloud/en/services/noproxy/minecraft #")
@Header("# #")
@Header("################################################################")
public class NoProxyConfig extends OkaeriConfig {
@Variable("NOPROXY_TOKEN")
@Comment({"Klucz prywatny API", "API secret"})
private String token = "";
@Comment("Biala lista (wpisane nicki lub ip nie beda blokowane)")
@Comment("Whitelist (nicknames or ips)")
private List<String> whitelist = Collections.singletonList("127.0.0.1");
@Comment({"Webhooki", "Webhooks"})
private List<NoProxyWebhook> webhooks = Collections.emptyList();
}
| //wiki.okaeri.cloud/pl/uslugi/noproxy/minecraft #") | /*
* OK! No.Proxy Minecraft
* Copyright (C) 2021 Okaeri, Dawid Sawicki
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.okaeri.minecraft.noproxy.shared;
import eu.okaeri.configs.OkaeriConfig;
import eu.okaeri.configs.annotation.*;
import eu.okaeri.platform.core.annotation.Configuration;
import lombok.Getter;
import java.util.Collections;
import java.util.List;
@Getter
@Configuration
@Header("################################################################")
@Header("# #")
@Header("# OK! No.Proxy Minecraft #")
@Header("# #")
@Header("# Nie wiesz jak skonfigurować? Zerknij do dokumentacji! #")
@Header("# https://wiki.okaeri.cloud/pl/uslugi/noproxy/minecraft <SUF>
@Header("# #")
@Header("# Trouble configuring? Check out the documentation! #")
@Header("# https://wiki.okaeri.cloud/en/services/noproxy/minecraft #")
@Header("# #")
@Header("################################################################")
public class NoProxyConfig extends OkaeriConfig {
@Variable("NOPROXY_TOKEN")
@Comment({"Klucz prywatny API", "API secret"})
private String token = "";
@Comment("Biala lista (wpisane nicki lub ip nie beda blokowane)")
@Comment("Whitelist (nicknames or ips)")
private List<String> whitelist = Collections.singletonList("127.0.0.1");
@Comment({"Webhooki", "Webhooks"})
private List<NoProxyWebhook> webhooks = Collections.emptyList();
}
| null |
7027_0 | OlehKorsun/First | 257 | GwiazdyX.java | import java.util.Scanner;
public class GwiazdyX {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Wprowadz wysokosc litery: ");
int n = scan.nextInt();
if(n<3 || n%2==0){
System.out.println("Nieprawidlowe dane!");
return;
}
int a = 1, b = 1, c = 2;
for(int i = 0; i<(n/2); i++){
System.out.print(" ".repeat(i)); // trzeba jeszcze dorobic
System.out.print("*");
for( int j = 0; j<n-c; j++){
System.out.print(" ");
}
c+=2;
System.out.print("*" + "\n");
}
}
}
| // trzeba jeszcze dorobic
| import java.util.Scanner;
public class GwiazdyX {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Wprowadz wysokosc litery: ");
int n = scan.nextInt();
if(n<3 || n%2==0){
System.out.println("Nieprawidlowe dane!");
return;
}
int a = 1, b = 1, c = 2;
for(int i = 0; i<(n/2); i++){
System.out.print(" ".repeat(i)); // trzeba jeszcze <SUF>
System.out.print("*");
for( int j = 0; j<n-c; j++){
System.out.print(" ");
}
c+=2;
System.out.print("*" + "\n");
}
}
}
| null |
6952_1 | OlehRadchenko/JAVA | 1,289 | school_practice_java/lab3-OlehRadchenko/src/main/java/zadanie2/Main.java | package zadanie2;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;
public class Main {
public static void main(String[] args){
Person jan = new Person(1, "jan", LocalDate.of(1990,01,01));
Person jan_kopia = jan.copy();
if(!jan.equals(jan_kopia) && jan!=jan_kopia){
System.out.println("Kopie obiektu powinny być sobie równe. Powinny to być różne referencje."+"\n"+jan+"\n"+jan_kopia);
System.out.println("Należy nadpisać metodę 'equals' odziedziczoną po klasie 'Object'");
return;
}
Person zdzislaw = jan.copy();
zdzislaw.setName("zdzislaw");
zdzislaw.setId(2);
zdzislaw.setDateOfBirth(jan.getDateOfBirth().plusMonths(2));
if(zdzislaw.equals(jan)){
System.out.println("obiekty NIE powinny być sobie równe");
System.out.println("Należy nadpisać metodę 'equals' odziedziczoną po klasie 'Object', " +
"tak aby jakakolwiek różnica w polach obiektów powodowała zwrot 'false'");
return;
}
Address adresJana = new Address(1, "Gdansk", "80-001");
adresJana.getAddressLines().add("Brzegi 55");
Address adresKopiiJana = new Address(1, "Gdynia", "80-002");
adresKopiiJana.getAddressLines().add("Brzegi 55");
jan.getAddresses().add(adresJana);
jan_kopia.getAddresses().add(adresKopiiJana);
if(jan.equals(jan_kopia)){
System.out.println("jan i jego kopia mają różne adresy ! - metoda 'equals' powinna to uwzględniać");
return;
}
adresJana.getAddressLines().add("dziekanat szkoly");
System.out.println(jan);
System.out.println(adresJana);
HashMap<Person, ArrayList<Address>> addressesByPerson = new HashMap<>();
addressesByPerson.put(jan, jan.getAddresses());
addressesByPerson.put(jan_kopia, jan_kopia.getAddresses());
addressesByPerson.put(zdzislaw, jan.getAddresses());
Person drugaKopiaJana = jan.copy();
addressesByPerson.put(drugaKopiaJana, drugaKopiaJana.getAddresses());
/**
* NIE chcę aby obiekt, który jest identyczny jak jakiś wcześniej dodany element
* był dodany w nowe miejsce HashMapy.
* W tym celu należy nadpisać metodę 'hashCode' dziedziczoną po klasie 'Object'
* wskazówka - można wykorzystać metodę 'toString' napisaną wcześniej
*/
if(addressesByPerson.keySet().size()>3){
System.out.println("druga kopia jana powinna wejść na miejsce jana, więc rozmiar kolekcji nie powinien być większy od 3 ");
System.out.println("w tym celu nalezy nadpisać metodę 'hashCode' odziedziczoną z klasy 'Object'");
return;
}
//
// Person trzeciaKopiaJana = jan.copy();
// trzeciaKopiaJana.getAddresses().add(new Address(2, "Sopot", "80-003"));
// addressesByPerson.put(trzeciaKopiaJana, trzeciaKopiaJana.getAddresses());
/**
* koelejny obiekt dodawany do hasmapy jest już inny (ma inny adres),
* więc powinna się dla niego utworzyć nowa pozycja w HashMapie
*/
// if(addressesByPerson.keySet().size()!=4){
// System.out.println("dodanie adresu do trzeciej kopii jana powinno zmienić wynik metody 'hashCode' " +
// "- stąd nowy element powinien móc być dodany do kolekcji");
// return;
// }
//System.out.println("wszystko dziala");
}
}
| // Person trzeciaKopiaJana = jan.copy();
| package zadanie2;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;
public class Main {
public static void main(String[] args){
Person jan = new Person(1, "jan", LocalDate.of(1990,01,01));
Person jan_kopia = jan.copy();
if(!jan.equals(jan_kopia) && jan!=jan_kopia){
System.out.println("Kopie obiektu powinny być sobie równe. Powinny to być różne referencje."+"\n"+jan+"\n"+jan_kopia);
System.out.println("Należy nadpisać metodę 'equals' odziedziczoną po klasie 'Object'");
return;
}
Person zdzislaw = jan.copy();
zdzislaw.setName("zdzislaw");
zdzislaw.setId(2);
zdzislaw.setDateOfBirth(jan.getDateOfBirth().plusMonths(2));
if(zdzislaw.equals(jan)){
System.out.println("obiekty NIE powinny być sobie równe");
System.out.println("Należy nadpisać metodę 'equals' odziedziczoną po klasie 'Object', " +
"tak aby jakakolwiek różnica w polach obiektów powodowała zwrot 'false'");
return;
}
Address adresJana = new Address(1, "Gdansk", "80-001");
adresJana.getAddressLines().add("Brzegi 55");
Address adresKopiiJana = new Address(1, "Gdynia", "80-002");
adresKopiiJana.getAddressLines().add("Brzegi 55");
jan.getAddresses().add(adresJana);
jan_kopia.getAddresses().add(adresKopiiJana);
if(jan.equals(jan_kopia)){
System.out.println("jan i jego kopia mają różne adresy ! - metoda 'equals' powinna to uwzględniać");
return;
}
adresJana.getAddressLines().add("dziekanat szkoly");
System.out.println(jan);
System.out.println(adresJana);
HashMap<Person, ArrayList<Address>> addressesByPerson = new HashMap<>();
addressesByPerson.put(jan, jan.getAddresses());
addressesByPerson.put(jan_kopia, jan_kopia.getAddresses());
addressesByPerson.put(zdzislaw, jan.getAddresses());
Person drugaKopiaJana = jan.copy();
addressesByPerson.put(drugaKopiaJana, drugaKopiaJana.getAddresses());
/**
* NIE chcę aby obiekt, który jest identyczny jak jakiś wcześniej dodany element
* był dodany w nowe miejsce HashMapy.
* W tym celu należy nadpisać metodę 'hashCode' dziedziczoną po klasie 'Object'
* wskazówka - można wykorzystać metodę 'toString' napisaną wcześniej
*/
if(addressesByPerson.keySet().size()>3){
System.out.println("druga kopia jana powinna wejść na miejsce jana, więc rozmiar kolekcji nie powinien być większy od 3 ");
System.out.println("w tym celu nalezy nadpisać metodę 'hashCode' odziedziczoną z klasy 'Object'");
return;
}
//
// Person trzeciaKopiaJana <SUF>
// trzeciaKopiaJana.getAddresses().add(new Address(2, "Sopot", "80-003"));
// addressesByPerson.put(trzeciaKopiaJana, trzeciaKopiaJana.getAddresses());
/**
* koelejny obiekt dodawany do hasmapy jest już inny (ma inny adres),
* więc powinna się dla niego utworzyć nowa pozycja w HashMapie
*/
// if(addressesByPerson.keySet().size()!=4){
// System.out.println("dodanie adresu do trzeciej kopii jana powinno zmienić wynik metody 'hashCode' " +
// "- stąd nowy element powinien móc być dodany do kolekcji");
// return;
// }
//System.out.println("wszystko dziala");
}
}
| null |
4457_0 | PGszafir/Focus_Stacking_Java_01 | 148 | src/main/java/PixelMap.java | public class PixelMap {
//mapowanie ostrości jako 2 macierz tej klasy
//poeracje na macierzach pixeli
//export do klasy FotoJpg
}
//Jacek Jak to widzisz to tutaj dodawaj swoje funkcjonalnsci z operacjami na pixelach patrz co zakomitował łukasz
// tak zeby wszystko się łaczyło
//Mój komentarz - Jacek
//PixelMapJPG*n -> PixelMap_mapa fęstości ostrości-> pixem map finalny-> JPG | //mapowanie ostrości jako 2 macierz tej klasy | public class PixelMap {
//mapowanie ostrości <SUF>
//poeracje na macierzach pixeli
//export do klasy FotoJpg
}
//Jacek Jak to widzisz to tutaj dodawaj swoje funkcjonalnsci z operacjami na pixelach patrz co zakomitował łukasz
// tak zeby wszystko się łaczyło
//Mój komentarz - Jacek
//PixelMapJPG*n -> PixelMap_mapa fęstości ostrości-> pixem map finalny-> JPG | null |
10060_13 | PJMPR/JAZ_Scheduler | 3,277 | schedulers/src/main/java/org/example/Main.java | package org.example;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Random;
public class Main {
public static void main(String[] args) {
/**
* Zanim zaczniesz pisać kod,
* zajrzyj do kodu poniższej metody
* i spróbuj zrozumieć o co w niej chodzi.
* Jest tam przykład prostej implementacji
* wzorca zwanego "metodą wytwórczą",
* czasem zwaną "fabrykującą",
* oraz prostej implementacji wzorca projektowego "budowniczego".
*
* zrozumienie implementacji tej metody
* pomoże Tobie w rozwiązaniu następnych zadań.
*/
checkThisOut();
/**
* Utwórz nowy interfejs
* z zadeklarowaną metodą "provideTime".
* Jego implementacje później będą wykorzystywane
* do określania, kiedy mają być wywoływane
* konkretne operacje
*/
IProvideNextExecutionTime nextExecutionTimeProvider;
/**
* dodaj adnotację @FunctionalInterface
* nad nowoutworzonym interfejsem
* aby zaznaczyć, że będzie on używany
* z operatorem lambda.
*
* poniżej masz dwie przykładowe implementacje
* tego interfejsu w postaci wyrażeń (metod) lambda
*/
nextExecutionTimeProvider = LocalDateTime::now;
nextExecutionTimeProvider = () -> LocalDateTime.now();
/**
* Twoim pierwszym zadaniem jest napisanie
* klasy o nazwie "Chron",
* która jest przykładem prostej implementacji
* wzorca projektowego "budowniczego".
* Budowniczy w tym przykładzie zwraca metodę
* wytwórczą, która ma być implementacją wcześniej utworzonego interfejsu.
*
* Chodzi o taką implemntację tych wzorców,
* gdzie można ustawić:
* -> setStartTime: godzinę startu (domyślnie teraz)
* -> setEndTime: godzinę końca (domyślnie nigdy),
* -> setMaxExecutionTimes: ilość powtórzeń wykonania
* (czyli ile kolejnych godzin\czasów ma zwrócić - domyślnie ma wykonywać w nieskończoność),
* -> setIntervalDuration: odstęp czasowy między kolejnymi godzinami/ czasami (domyślnie 1 sekunda)
*
* Metoda buildNextTimeExecutionProvider ma zwracać lambdę,
* która generuje kolejną godzinę według wcześniej podanych parametrów
* UAWAGA !
* Najlepiej zrobić tak, aby klasa Chron implementowała "buildera" (budowniczego) - w sensie nie robić buildera jako odrębnej klasy
*/
var chron = Chron.builder();
chron.setStartTime(LocalDateTime.now());
chron.setEndDate(LocalDateTime.now().plusSeconds(40));
chron.setIntervalDuration(Duration.ofMillis(300));
IProvideNextExecutionTime startsNowFor5SecondsMax5TimesWithDurationOf500Millis =
Chron.builder()
.setStartTime(LocalDateTime.now())
.setEndDate(LocalDateTime.now().plusSeconds(5))
.setMaxExecutionTimes(5)
.setIntervalDuration(Duration.ofMillis(500))
.buildNextTimeExecutionProvider();
// startsNowFor5SecondsMax5TimesWithDurationOf500Millis.provideNextExecutionTime();// czas teraz
// startsNowFor5SecondsMax5TimesWithDurationOf500Millis.provideNextExecutionTime();// czas teraz + 500 ms
// startsNowFor5SecondsMax5TimesWithDurationOf500Millis.provideNextExecutionTime();// czas teraz + 1000 ms
// startsNowFor5SecondsMax5TimesWithDurationOf500Millis.provideNextExecutionTime();// czas teraz + 1500 ms
// startsNowFor5SecondsMax5TimesWithDurationOf500Millis.provideNextExecutionTime();// czas teraz + 2000 ms
// //.....
// startsNowFor5SecondsMax5TimesWithDurationOf500Millis.provideNextExecutionTime();// null
/**
* Super udało się - jestem pod wielkim wrażeniem ;-]
* W dalszej części programu bedziemy potrzebowali
* kolejnego interfejsu, który będzie wykorzystywany
* jako lambda, która może rzucić wyjątkiem (błędem)
*/
IRunNotSafeAction throwAnError = ()->{ throw new Exception(); };
try {
throwAnError.executeNotSafeAction();
System.out.println("tutaj powinien wystąpić błąd, a nie wystąpił :(");
return;
}catch (Exception ex){
}
/**
* wykorzystajmy metodę,
* która co jakiś czas rzuca błedem
* jako implementacja powyższego interfejsu
*/
IRunNotSafeAction randomlyThrowsAnError = () -> randomlyThrowException();
/* albo inaczej: */
IRunNotSafeAction randomlyThrowsAnErrorMethodReference = Main::randomlyThrowException;
/**
* Jeśli myslałeś, że poprzednie zadanie było łatwe,
* to ciekawe co powiesz o tym...
*
* Teraz mamy zdefiniowene dwa interfejsy:
* 1. IProvideNextExecutionTime - implementacja zwraca kolejną godzinę,
* według ustawień podanych w builderze
* 2. IRunNotSafeAction - implementacje tego interfejsu będą definiować zadanie,
* które będzie wykonywane przez harmonogram
*
* Czas na zaimplementowanie klasy Scheduler,
* która to właśnie będzie odpowiadać za wykonywanie zadań,
* o konkretnych porach.
*
* Ta klasa będzie mixem 2 wzorców projektowych:
* 1. singletonu - chcemy, aby był tylko jeden harmonogram,
* w którym będą przechowywane informacje o wszystkich zadaniach jakie mają być wykonane (Implementacje IRunNotSafeAction),
* oraz o metodzie lambda która zwraca kolejne czasy wykonania danego zadania (implementacja IProvideNextExecutionTime)
* 2. budowniczego:
* -> forAction: metoda do definiowania zadania do wykonania
* -> onError: metoda która przyjmuje lambdę, która to z kolei jako parametr ma przyjąć wyjątek, i jakoś go obsłużyć
* -> onSingleActionCompleted: przyjmuje lambdę, która definiuje co ma się stać po wykonaniu pojednyczego zadania
* -> onCompleted: przyjmuje lambdę, która definiuje co ma się stać gdy wszystkie zadania danego typu się zakończą
* -> schedule: zapisuje wszystkie powyższe dane do pewnej kolekcji
*
* UWAGA!
* W tym zadaniu pewnie będziesz musiał napisac kilka własnych klas/ inetrfejsów pomocniczych,
* których nie spotkasz w tym miejscu (tzn. w ciele funkcji main, w której aktualnie się znajdujemy)
*/
Scheduler scheduler = Scheduler.getInstance();
scheduler
.forAction(randomlyThrowsAnError)
.useExecutionTimeProvider(startsNowFor5SecondsMax5TimesWithDurationOf500Millis)
.onError(ex->handleException(ex))
.onSingleActionCompleted(()->System.out.println("wykonano akcje z powodzeniem"))
.onCompleted(()->System.out.println("Zakończyłem pracę"))
.schedule();
/**
* Jeżeli już tutaj się znalazłeś i samemu rozwiązałeeś powyższe zadania,
* to wiedz, że drzemie w Tobie duży potencjał - tak trzymać !
*
* No to mamy już możliwość tworzenia harmonogramów zadań
* teraz przyda się nam jakiś wątek, który będzie mógł uruchamiać te zadania,
* w tle działania aplikacji
* Utwórz klasę SchedulerThread,
* która implementuje interfejs Runnable (ten interfejs jest utworzony w frameworku JAVY),
* w taki sposób, że bierze zadania z singletonu Schedule'ra i odpala je o konkretnych porach.
*
* Np. co sekunde z kolekcji zadań sprawdza czas wykonania zadania
* i jeśli czas na te zadanie właśnie mija/minał,
* a zadanie się jeszcze nie wykonało,
* to je wykonuje.
*/
Runnable schedulerThread = new SchedulerThread();
new Thread(schedulerThread).start();
/**
* na zakończenie sprawdźmy co się stanie,
* jeśli 'zbuduję' jeszcze jedno zadanie
* i dodam je do Schedulera
*/
scheduler.forAction(()->System.out.println("chyba zaczynam to rozumieć"))
.useExecutionTimeProvider(Chron.builder()
.setMaxExecutionTimes(1)
.buildNextTimeExecutionProvider())
.onCompleted(()->System.out.println("Nie wierzę... działa!"))
.schedule();
/**
* to jest tylko po to aby main sam nie kończyl się wykonywać.
*/
runForever();
}
private static void handleException(Exception ex) {
System.out.println("Wystąpił błąd :(");
}
static void randomlyThrowException() throws Exception {
int nextInt = new Random().nextInt(10);
if(nextInt<2){
System.out.println("O nie... coś się popsuło");
throw new Exception(":(");
}
System.out.println("Działam sobie normalnie :)");
Thread.sleep(nextInt*100);
}
static void runForever(){
new Thread(()->{
while (true){
try {
Thread.currentThread().join();
//Thread.sleep(1000);
}catch (Exception ignored){}
}
}).start();
}
static void checkThisOut(){
IProvide<Person> janKowalskiProvider = Person.builder()
.setName("Jan")
.setSurname("Kowalski")
.buildPersonProvider();
Person janKowalski = janKowalskiProvider.provide();
}
}
class Person{
private String name;
private String surname;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public static PersonBuilder builder(){
return new PersonBuilder();
}
}
interface IProvide<T>{
T provide();
}
class PersonBuilder{
String name, surname;
public PersonBuilder setName(String name){
this.name = name;
return this;
}
public PersonBuilder setSurname(String surname){
this.surname = surname;
return this;
}
public IProvide<Person> buildPersonProvider()
{
return ()->{
Person p = new Person();
p.setName(name);
p.setSurname(surname);
return p;
};
}
}
| /**
* na zakończenie sprawdźmy co się stanie,
* jeśli 'zbuduję' jeszcze jedno zadanie
* i dodam je do Schedulera
*/ | package org.example;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Random;
public class Main {
public static void main(String[] args) {
/**
* Zanim zaczniesz pisać kod,
* zajrzyj do kodu poniższej metody
* i spróbuj zrozumieć o co w niej chodzi.
* Jest tam przykład prostej implementacji
* wzorca zwanego "metodą wytwórczą",
* czasem zwaną "fabrykującą",
* oraz prostej implementacji wzorca projektowego "budowniczego".
*
* zrozumienie implementacji tej metody
* pomoże Tobie w rozwiązaniu następnych zadań.
*/
checkThisOut();
/**
* Utwórz nowy interfejs
* z zadeklarowaną metodą "provideTime".
* Jego implementacje później będą wykorzystywane
* do określania, kiedy mają być wywoływane
* konkretne operacje
*/
IProvideNextExecutionTime nextExecutionTimeProvider;
/**
* dodaj adnotację @FunctionalInterface
* nad nowoutworzonym interfejsem
* aby zaznaczyć, że będzie on używany
* z operatorem lambda.
*
* poniżej masz dwie przykładowe implementacje
* tego interfejsu w postaci wyrażeń (metod) lambda
*/
nextExecutionTimeProvider = LocalDateTime::now;
nextExecutionTimeProvider = () -> LocalDateTime.now();
/**
* Twoim pierwszym zadaniem jest napisanie
* klasy o nazwie "Chron",
* która jest przykładem prostej implementacji
* wzorca projektowego "budowniczego".
* Budowniczy w tym przykładzie zwraca metodę
* wytwórczą, która ma być implementacją wcześniej utworzonego interfejsu.
*
* Chodzi o taką implemntację tych wzorców,
* gdzie można ustawić:
* -> setStartTime: godzinę startu (domyślnie teraz)
* -> setEndTime: godzinę końca (domyślnie nigdy),
* -> setMaxExecutionTimes: ilość powtórzeń wykonania
* (czyli ile kolejnych godzin\czasów ma zwrócić - domyślnie ma wykonywać w nieskończoność),
* -> setIntervalDuration: odstęp czasowy między kolejnymi godzinami/ czasami (domyślnie 1 sekunda)
*
* Metoda buildNextTimeExecutionProvider ma zwracać lambdę,
* która generuje kolejną godzinę według wcześniej podanych parametrów
* UAWAGA !
* Najlepiej zrobić tak, aby klasa Chron implementowała "buildera" (budowniczego) - w sensie nie robić buildera jako odrębnej klasy
*/
var chron = Chron.builder();
chron.setStartTime(LocalDateTime.now());
chron.setEndDate(LocalDateTime.now().plusSeconds(40));
chron.setIntervalDuration(Duration.ofMillis(300));
IProvideNextExecutionTime startsNowFor5SecondsMax5TimesWithDurationOf500Millis =
Chron.builder()
.setStartTime(LocalDateTime.now())
.setEndDate(LocalDateTime.now().plusSeconds(5))
.setMaxExecutionTimes(5)
.setIntervalDuration(Duration.ofMillis(500))
.buildNextTimeExecutionProvider();
// startsNowFor5SecondsMax5TimesWithDurationOf500Millis.provideNextExecutionTime();// czas teraz
// startsNowFor5SecondsMax5TimesWithDurationOf500Millis.provideNextExecutionTime();// czas teraz + 500 ms
// startsNowFor5SecondsMax5TimesWithDurationOf500Millis.provideNextExecutionTime();// czas teraz + 1000 ms
// startsNowFor5SecondsMax5TimesWithDurationOf500Millis.provideNextExecutionTime();// czas teraz + 1500 ms
// startsNowFor5SecondsMax5TimesWithDurationOf500Millis.provideNextExecutionTime();// czas teraz + 2000 ms
// //.....
// startsNowFor5SecondsMax5TimesWithDurationOf500Millis.provideNextExecutionTime();// null
/**
* Super udało się - jestem pod wielkim wrażeniem ;-]
* W dalszej części programu bedziemy potrzebowali
* kolejnego interfejsu, który będzie wykorzystywany
* jako lambda, która może rzucić wyjątkiem (błędem)
*/
IRunNotSafeAction throwAnError = ()->{ throw new Exception(); };
try {
throwAnError.executeNotSafeAction();
System.out.println("tutaj powinien wystąpić błąd, a nie wystąpił :(");
return;
}catch (Exception ex){
}
/**
* wykorzystajmy metodę,
* która co jakiś czas rzuca błedem
* jako implementacja powyższego interfejsu
*/
IRunNotSafeAction randomlyThrowsAnError = () -> randomlyThrowException();
/* albo inaczej: */
IRunNotSafeAction randomlyThrowsAnErrorMethodReference = Main::randomlyThrowException;
/**
* Jeśli myslałeś, że poprzednie zadanie było łatwe,
* to ciekawe co powiesz o tym...
*
* Teraz mamy zdefiniowene dwa interfejsy:
* 1. IProvideNextExecutionTime - implementacja zwraca kolejną godzinę,
* według ustawień podanych w builderze
* 2. IRunNotSafeAction - implementacje tego interfejsu będą definiować zadanie,
* które będzie wykonywane przez harmonogram
*
* Czas na zaimplementowanie klasy Scheduler,
* która to właśnie będzie odpowiadać za wykonywanie zadań,
* o konkretnych porach.
*
* Ta klasa będzie mixem 2 wzorców projektowych:
* 1. singletonu - chcemy, aby był tylko jeden harmonogram,
* w którym będą przechowywane informacje o wszystkich zadaniach jakie mają być wykonane (Implementacje IRunNotSafeAction),
* oraz o metodzie lambda która zwraca kolejne czasy wykonania danego zadania (implementacja IProvideNextExecutionTime)
* 2. budowniczego:
* -> forAction: metoda do definiowania zadania do wykonania
* -> onError: metoda która przyjmuje lambdę, która to z kolei jako parametr ma przyjąć wyjątek, i jakoś go obsłużyć
* -> onSingleActionCompleted: przyjmuje lambdę, która definiuje co ma się stać po wykonaniu pojednyczego zadania
* -> onCompleted: przyjmuje lambdę, która definiuje co ma się stać gdy wszystkie zadania danego typu się zakończą
* -> schedule: zapisuje wszystkie powyższe dane do pewnej kolekcji
*
* UWAGA!
* W tym zadaniu pewnie będziesz musiał napisac kilka własnych klas/ inetrfejsów pomocniczych,
* których nie spotkasz w tym miejscu (tzn. w ciele funkcji main, w której aktualnie się znajdujemy)
*/
Scheduler scheduler = Scheduler.getInstance();
scheduler
.forAction(randomlyThrowsAnError)
.useExecutionTimeProvider(startsNowFor5SecondsMax5TimesWithDurationOf500Millis)
.onError(ex->handleException(ex))
.onSingleActionCompleted(()->System.out.println("wykonano akcje z powodzeniem"))
.onCompleted(()->System.out.println("Zakończyłem pracę"))
.schedule();
/**
* Jeżeli już tutaj się znalazłeś i samemu rozwiązałeeś powyższe zadania,
* to wiedz, że drzemie w Tobie duży potencjał - tak trzymać !
*
* No to mamy już możliwość tworzenia harmonogramów zadań
* teraz przyda się nam jakiś wątek, który będzie mógł uruchamiać te zadania,
* w tle działania aplikacji
* Utwórz klasę SchedulerThread,
* która implementuje interfejs Runnable (ten interfejs jest utworzony w frameworku JAVY),
* w taki sposób, że bierze zadania z singletonu Schedule'ra i odpala je o konkretnych porach.
*
* Np. co sekunde z kolekcji zadań sprawdza czas wykonania zadania
* i jeśli czas na te zadanie właśnie mija/minał,
* a zadanie się jeszcze nie wykonało,
* to je wykonuje.
*/
Runnable schedulerThread = new SchedulerThread();
new Thread(schedulerThread).start();
/**
* na zakończenie sprawdźmy <SUF>*/
scheduler.forAction(()->System.out.println("chyba zaczynam to rozumieć"))
.useExecutionTimeProvider(Chron.builder()
.setMaxExecutionTimes(1)
.buildNextTimeExecutionProvider())
.onCompleted(()->System.out.println("Nie wierzę... działa!"))
.schedule();
/**
* to jest tylko po to aby main sam nie kończyl się wykonywać.
*/
runForever();
}
private static void handleException(Exception ex) {
System.out.println("Wystąpił błąd :(");
}
static void randomlyThrowException() throws Exception {
int nextInt = new Random().nextInt(10);
if(nextInt<2){
System.out.println("O nie... coś się popsuło");
throw new Exception(":(");
}
System.out.println("Działam sobie normalnie :)");
Thread.sleep(nextInt*100);
}
static void runForever(){
new Thread(()->{
while (true){
try {
Thread.currentThread().join();
//Thread.sleep(1000);
}catch (Exception ignored){}
}
}).start();
}
static void checkThisOut(){
IProvide<Person> janKowalskiProvider = Person.builder()
.setName("Jan")
.setSurname("Kowalski")
.buildPersonProvider();
Person janKowalski = janKowalskiProvider.provide();
}
}
class Person{
private String name;
private String surname;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public static PersonBuilder builder(){
return new PersonBuilder();
}
}
interface IProvide<T>{
T provide();
}
class PersonBuilder{
String name, surname;
public PersonBuilder setName(String name){
this.name = name;
return this;
}
public PersonBuilder setSurname(String surname){
this.surname = surname;
return this;
}
public IProvide<Person> buildPersonProvider()
{
return ()->{
Person p = new Person();
p.setName(name);
p.setSurname(surname);
return p;
};
}
}
| null |
8168_2 | PJULegio/Java_Basics_PJATK | 1,407 | GS/gs_labs_05/Zbiory.java | import java.util.Scanner;
public class Zbiory
{
public static void main(String[] args)
{
// ZADANIE I
{
int wrt = -4;
// SPOSÓB 1
if(((wrt>-15 && wrt<=-10) || (wrt>-5 && wrt<0) || (wrt>5 && wrt<10))
&& ((wrt<=-13) || (wrt>-8 && wrt<=-3))
&& (wrt>=-4))
{
System.out.println("OK");
}
// SPOSÓB 2
if((wrt>-15 && wrt<=-10) || (wrt>-5 && wrt<0) || (wrt>5 && wrt<10))
if((wrt<=-13) || (wrt>-8 && wrt<=-3))
if(wrt>=-4)
System.out.println("OK");
// SPOSÓB 3
if(wrt>=-4 && wrt<=-3)
System.out.println("OK");
}
// ZADANIE II
{
int a = 3;
int b = 4;
// Oryginalne wyrażenie
System.out.println(!(a < b) && !(a > b));
// Proste wyrażenie
System.out.println((a >= b) && (a <= b));
System.out.println((a == b));
}
// ZADANIE III
/* {
Scanner scan = new Scanner(System.in);
int miesiac = scan.nextInt();
int rok = scan.nextInt();
switch (miesiac)
{
case 2 ->
{
if (rok % 4 == 0 && (rok % 100 != 0 || rok % 400 == 0))
System.out.println(29);
else
System.out.println(28);
}
case 1, 3, 5, 7, 8, 10, 12 -> System.out.println(31);
case 4, 6, 9, 11 -> System.out.println(30);
default -> System.out.println("Bledne dane");
}
}
*/
// ZADANIE IV
/* {
Scanner scanner = new Scanner(System.in);
char ch = scanner.next().charAt(0);
if((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122))
{
boolean samogloska = switch (ch)
{
case 'a', 'e', 'i', 'o', 'u', 'y' -> { yield true; }
case 'A', 'E', 'I', 'O', 'U', 'Y' -> { yield true; }
default -> { yield false; }
};
System.out.println(samogloska?"Samogloska":"Spolgloska");
}
} */
// ZADANIE V
/* {
Scanner scanner = new Scanner(System.in);
double zmienna1 = scanner.nextDouble();
int zmienna1Int = (int)(zmienna1 * 100); // dokładność do 2 miejsc po przecinku
double zmienna2 = scanner.nextDouble();
int zmienna2Int = (int)(zmienna2 * 100);
if(zmienna1Int == zmienna2Int)
System.out.println("Sa takie same");
} */
// ZADANIE VI
/* {
Scanner scanner = new Scanner(System.in);
int A = scanner.nextInt();
int B = scanner.nextInt();
int C = scanner.nextInt();
int biggest;
if(A + B + C == 180)
{
System.out.println("Może istnieć");
if(A < 90 && B < 90 && C < 90)
System.out.println("Jest też ostrokątny");
}
else
{
System.out.println("NIE moze istniec!");
}
} */
}
} | /* {
Scanner scanner = new Scanner(System.in);
double zmienna1 = scanner.nextDouble();
int zmienna1Int = (int)(zmienna1 * 100); // dokładność do 2 miejsc po przecinku
double zmienna2 = scanner.nextDouble();
int zmienna2Int = (int)(zmienna2 * 100);
if(zmienna1Int == zmienna2Int)
System.out.println("Sa takie same");
} */ | import java.util.Scanner;
public class Zbiory
{
public static void main(String[] args)
{
// ZADANIE I
{
int wrt = -4;
// SPOSÓB 1
if(((wrt>-15 && wrt<=-10) || (wrt>-5 && wrt<0) || (wrt>5 && wrt<10))
&& ((wrt<=-13) || (wrt>-8 && wrt<=-3))
&& (wrt>=-4))
{
System.out.println("OK");
}
// SPOSÓB 2
if((wrt>-15 && wrt<=-10) || (wrt>-5 && wrt<0) || (wrt>5 && wrt<10))
if((wrt<=-13) || (wrt>-8 && wrt<=-3))
if(wrt>=-4)
System.out.println("OK");
// SPOSÓB 3
if(wrt>=-4 && wrt<=-3)
System.out.println("OK");
}
// ZADANIE II
{
int a = 3;
int b = 4;
// Oryginalne wyrażenie
System.out.println(!(a < b) && !(a > b));
// Proste wyrażenie
System.out.println((a >= b) && (a <= b));
System.out.println((a == b));
}
// ZADANIE III
/* {
Scanner scan = new Scanner(System.in);
int miesiac = scan.nextInt();
int rok = scan.nextInt();
switch (miesiac)
{
case 2 ->
{
if (rok % 4 == 0 && (rok % 100 != 0 || rok % 400 == 0))
System.out.println(29);
else
System.out.println(28);
}
case 1, 3, 5, 7, 8, 10, 12 -> System.out.println(31);
case 4, 6, 9, 11 -> System.out.println(30);
default -> System.out.println("Bledne dane");
}
}
*/
// ZADANIE IV
/* {
Scanner scanner = new Scanner(System.in);
char ch = scanner.next().charAt(0);
if((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122))
{
boolean samogloska = switch (ch)
{
case 'a', 'e', 'i', 'o', 'u', 'y' -> { yield true; }
case 'A', 'E', 'I', 'O', 'U', 'Y' -> { yield true; }
default -> { yield false; }
};
System.out.println(samogloska?"Samogloska":"Spolgloska");
}
} */
// ZADANIE V
/* {
<SUF>*/
// ZADANIE VI
/* {
Scanner scanner = new Scanner(System.in);
int A = scanner.nextInt();
int B = scanner.nextInt();
int C = scanner.nextInt();
int biggest;
if(A + B + C == 180)
{
System.out.println("Może istnieć");
if(A < 90 && B < 90 && C < 90)
System.out.println("Jest też ostrokątny");
}
else
{
System.out.println("NIE moze istniec!");
}
} */
}
} | null |
7657_3 | PJULegio/Java_Coop | 431 | 2023-12/src/Palindrome.java | public class Palindrome
{
public static void main(String[] args)
{
boolean palindrome = true;
//int[] tab = {1,2,3,4,4,3,2,1};
int[] tab = {1,2,3,4,5,3,2,1};
for (int i = 0; i < tab.length/2; i++) {
// Dla i = 0, ( tab[i] != tab[tab.length-1-i] ), równa się ( tab[0] != tab[7] )
// Dla tablicy 8-elementowej nie istnieje tab[8]
if(tab[i] != tab[tab.length-1-i]){
palindrome = false;
}
}
System.out.println(palindrome);
}
}
/* (tab.length / 2) żeby się nie powtarzać
(tab.length) porównałby elementy 8 razy
tab[0] i tab[7]
tab[1] i tab[6]
tab[2] i tab[5]
tab[3] i tab[4]
tab[4] i tab[3] tu zaczynamy się powtarzać
tab[5] i tab[2]
tab[6] i tab[1]
tab[7] i tab[0]
(tab.length / 2) porówna elementy 4 razy
tab[0] i tab[7]
tab[1] i tab[6]
tab[2] i tab[5]
tab[3] i tab[4]
Wystarczy, wszystkie elementy porównane
*/ | /* (tab.length / 2) żeby się nie powtarzać
(tab.length) porównałby elementy 8 razy
tab[0] i tab[7]
tab[1] i tab[6]
tab[2] i tab[5]
tab[3] i tab[4]
tab[4] i tab[3] tu zaczynamy się powtarzać
tab[5] i tab[2]
tab[6] i tab[1]
tab[7] i tab[0]
(tab.length / 2) porówna elementy 4 razy
tab[0] i tab[7]
tab[1] i tab[6]
tab[2] i tab[5]
tab[3] i tab[4]
Wystarczy, wszystkie elementy porównane
*/ | public class Palindrome
{
public static void main(String[] args)
{
boolean palindrome = true;
//int[] tab = {1,2,3,4,4,3,2,1};
int[] tab = {1,2,3,4,5,3,2,1};
for (int i = 0; i < tab.length/2; i++) {
// Dla i = 0, ( tab[i] != tab[tab.length-1-i] ), równa się ( tab[0] != tab[7] )
// Dla tablicy 8-elementowej nie istnieje tab[8]
if(tab[i] != tab[tab.length-1-i]){
palindrome = false;
}
}
System.out.println(palindrome);
}
}
/* (tab.length / 2) <SUF>*/ | null |
4065_1 | PR0R0CK/just_cook_mobile_app | 265 | app/src/main/java/com/example/justcook/activities/ConfirmationActivity.java | package com.example.justcook.activities;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.example.justcook.R;
public class ConfirmationActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_confirmation);
//TODO: edytowanie zawartości @+id/username_TextView_confirmation na nazwę zalogowanego użytkownia
//W nazewnictwie zmiennych używaj cammelCase
// "username_TextView_confirmation" - źle
// "username_textView_confirmation" - dobrze
// Drobny szczegół, ale razi. Popraw w activity_confirmation
}
public void confirmationContinue(View view) {
//TODO: przeniesienia użytkownika do głównego activity użytkowego aplikacji
}
}
| //W nazewnictwie zmiennych używaj cammelCase | package com.example.justcook.activities;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.example.justcook.R;
public class ConfirmationActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_confirmation);
//TODO: edytowanie zawartości @+id/username_TextView_confirmation na nazwę zalogowanego użytkownia
//W nazewnictwie <SUF>
// "username_TextView_confirmation" - źle
// "username_textView_confirmation" - dobrze
// Drobny szczegół, ale razi. Popraw w activity_confirmation
}
public void confirmationContinue(View view) {
//TODO: przeniesienia użytkownika do głównego activity użytkowego aplikacji
}
}
| null |
8302_5 | Pandoors/TinyGP | 3,255 | src/main/java/model/genetic/Solver.java | package model.genetic;
import lombok.NoArgsConstructor;
import model.Program;
import model.tokenNode.TokenNode;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.apache.commons.math3.util.IntegerSequence;
import visitor.BobaroLexer;
import visitor.BobaroParser;
import visitor.own.BobaroVisitor;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Solver {
private int epoch=0;
private final int epochs = 1000;
private List<Program> programs = new ArrayList<>();
private String outputFilename = "/Users/mikolajborowicz/Documents/Local/ProgramowanieGenetyczne/TinyGP/output.txt";
private int sigmaProgramId;
private int avgFitnessInEpoch;
private String path;
private double reachedFitness;
public Solver(String path) {
this.path = path;
this.reachedFitness = 0;
for (int i : new IntegerSequence.Range(0, 100, 1)) {
programs.add(new Program(false));
}
}
public void solve() {
// saveAndCompile(programs.get(0), " 100 0 0 0 0 0 0 0 ");
int size = programs.size();
for (int i : new IntegerSequence.Range(1, epochs, 1)) {
epoch = i;
// if (fBestPop > -1e-5) { todo
// System.out.print("PROBLEM SOLVED\n");
// System.exit(0);
// }
// for (Program indiv : programs) {
// evaluate(indiv);
//
// }
printEpochStarted();
for (int j=0; j < size; j++){
evaluate(programs.get(j));
}
printEpoch();
}
}
public void evaluate(Program indiv) {
// tournament -> crossover2 best -> negative tournament -> mutation
switch (new Random().nextInt(2)) {
case 0:
Program new_mutated = mutation(indiv);
new_mutated.setReachedFitness(fitness(new_mutated));
this.reachedFitness = Math.max(new_mutated.getReachedFitness(), this.reachedFitness);
this.programs.add(new_mutated);
break;
case 1:
Program child = cross(indiv, tournament());
child.setReachedFitness(fitness(child));
this.reachedFitness = Math.max(child.getReachedFitness(), this.reachedFitness);
this.programs.add(child);
break;
}
// System.out.println("Best fitness: " + this.reachedFitness);
negativeTournament();
}
private Program cross(Program parent1, Program parent2){
return Operations.cross(parent1, parent2);
}
public Program tournament() {
for(Program program: programs){
if(program.getReachedFitness()==reachedFitness)
return program;
}
return programs.get(0); //i tak się to nigdy nie wykona ale wrzuciłem to żeby się nie darło
}
public void negativeTournament () {
double worstFitness = 0;
Integer index = null;
for (int i = 0; i < this.programs.size(); i++) {
if (programs.get(i).getReachedFitness() < worstFitness) {
index = i;
break;
}
}
if (index != null) {
this.programs.remove(index.intValue());
System.out.println("Usunieto w indeksie: " + index);
}
}
public Program mutation(Program a) {
return Operations.mutation(a);
}
public List<Integer> getProgramOutputs(){
try{
BufferedReader br = new BufferedReader(new FileReader(this.outputFilename));
String line;
String outputs = "";
while ((line = br.readLine()) != null) {
outputs = outputs = outputs + " " + line;
}
return convert2List(outputs);
} catch (IOException e) {
e.printStackTrace();
}
return null; // to nie powinno się nigdy wykona
}
public boolean isOutputEmpty(){
File file = new File(this.outputFilename);
if (file.length() == 0) {
System.out.println("The file is empty");
return true;
} else {
System.out.println("The file is not empty");
return false;
}
}
public double gradeOccurancesInFile(List<Integer> output) {
// List<Integer> programOutputs = getProgramOutputs();
// int count = 0;x
// for(int i= 0; i<output.size(); i++){
// for(int j=0; j<programOutputs.size();j++){
// count ++;
// }
// }
// return count/output.size();
// List<Integer> programOutputs = getProgramOutputs();
// if(output != null && !output.isEmpty() && programOutputs != null && !programOutputs.isEmpty()){
// for (Integer element : output) {
// if (programOutputs.contains(element)) {
// count++;
// }
// }}
// return count;
return 0.0;
}
public double gradeDistanceBetweenOutputs(List<Integer> output){
double grade = 0;
List<Integer> programOutputs = getProgramOutputs();
for(int i=0; i<output.size(); i++){
if(output.get(i)==programOutputs.get(i))
grade = 1_000_000;
else
grade = grade + (1/Math.abs(output.get(i)-programOutputs.get(i)));
}
return grade/output.size();
}
public boolean doesProgramRuns(){
try{
BufferedReader br = new BufferedReader(new FileReader(this.outputFilename));
String line;
while ((line = br.readLine()) != null) {
if(line.contains("ERROR")) return false;
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
public boolean doesProgramHaveExpectedOutputLength(int outputLength){
try {
BufferedReader br = new BufferedReader(new FileReader(this.outputFilename));
String line;
int i= 0;
while ((line = br.readLine()) != null) {
i++;
}
return outputLength==i;
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
private double fittnes4Case(List<Integer> outputs, int checkOutputLength){
//checking if the program returns error
if(!doesProgramRuns()||isOutputEmpty()) return -1;
if(checkOutputLength>0 ){
//checking if the number of length of outputs matches number of expected outputs
if(!doesProgramHaveExpectedOutputLength(outputs.size())) return 0.0;
//read the file and return the sqrt of sum of squares
return gradeDistanceBetweenOutputs(outputs);
}else {
return gradeOccurancesInFile(outputs);
}
}
private List<Integer> convert2List(String s){
String[] parts = s.split(" ");
List<String> stringList = Arrays.asList(parts);
List<Integer> numbers = stringList.stream().filter(n-> n!= null && !Objects.equals(n, ""))
.map(Integer::parseInt)
.collect(Collectors.toList());
return numbers;
}
private double fitness(Program program){ // TODO: szczerze powiedziawszy to ja bym zrobił, że im mniejszy błąd tym lepszy fitness case?
String line;
try (BufferedReader br = new BufferedReader(new FileReader(this.path))) {
String headerLine = br.readLine();
List<Integer> numbers = convert2List(headerLine);
int rotations = numbers.get(0);
int inputs = numbers.get(1);
int outputs = numbers.get(2);
int test_cases = numbers.get(3);
double avg_fitness = 0;
for(int i=0; i<test_cases; i++){
//read line and complile program using input and calculate fitness for single case
String testCase = br.readLine();
List<Integer> n = convert2List(testCase);
List<Integer> inputsList = n.subList(0,inputs);
List<Integer> outputsList = new ArrayList<>();
outputsList.addAll(n.subList(inputs, n.size()));
inputsList.add(0, rotations);
String input = String.join(" ", inputsList.stream().map(Object::toString).collect(Collectors.toList()));
saveAndCompile(program, input);
avg_fitness+=fittnes4Case( outputsList, outputs);
}
return avg_fitness/test_cases;
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
private void saveAndCompile(Program program, String input) {
try{
String program_txt = program.getTreeProgTxt();
// System.out.println("\n ------- program txt in Bobaro-------\n");
// System.out.println(program_txt);
// System.out.println("\n ------- program txt end -------\n");
CharStream charStream1 = CharStreams.fromString(program_txt);
BobaroLexer lexer = new BobaroLexer(charStream1);
CommonTokenStream tokens = new CommonTokenStream(lexer);
BobaroParser parser = new BobaroParser(tokens);
String str = new BobaroVisitor().visit(parser.program());
StringBuilder sb = new StringBuilder();
if(program.getVariables()!=null && !program.getVariables().isEmpty()) {
sb.append("int ");
boolean first = true;
for (TokenNode tn : program.getVariables()) {
if(!first){
sb.append(", ");
}
sb.append(tn.getToken());
first=false;
}
sb.append(";");
}
String toInsert = sb.toString();
String searchPhrase = "char *argv[]) {";
int pos_str = str.indexOf(searchPhrase)+searchPhrase.length();
str = new StringBuilder(str).insert(pos_str, toInsert).toString();
// System.out.println("\n ------- program txt in Cpp -------\n");
// System.out.println(str);
// System.out.println("\n ------- program txt in Cpp end -------\n");
try (PrintWriter out = new PrintWriter("/Users/mikolajborowicz/Documents/Local/ProgramowanieGenetyczne/TinyGP/program.cpp")) {
out.println(str);
}catch (Exception e){
e.printStackTrace();
}
ProcessBuilder build =
new ProcessBuilder("g++", "/Users/mikolajborowicz/Documents/Local/ProgramowanieGenetyczne/TinyGP/program.cpp");
// create the process
Process process = build.start();
process.waitFor();
ProcessBuilder build2 =
new ProcessBuilder("/Users/mikolajborowicz/Documents/Local/ProgramowanieGenetyczne/TinyGP/a.out");
// create the process
Process process2 = build2.start();
process2.waitFor();
}catch (Exception e){
e.printStackTrace();
}
}
private void printEpoch(){
System.out.println("Epoch: " + epoch + "score: " + reachedFitness);
}
private void printEpochStarted(){
System.out.println("Epoch: " + epoch + " just started.");
}
}
| //i tak się to nigdy nie wykona ale wrzuciłem to żeby się nie darło | package model.genetic;
import lombok.NoArgsConstructor;
import model.Program;
import model.tokenNode.TokenNode;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.apache.commons.math3.util.IntegerSequence;
import visitor.BobaroLexer;
import visitor.BobaroParser;
import visitor.own.BobaroVisitor;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Solver {
private int epoch=0;
private final int epochs = 1000;
private List<Program> programs = new ArrayList<>();
private String outputFilename = "/Users/mikolajborowicz/Documents/Local/ProgramowanieGenetyczne/TinyGP/output.txt";
private int sigmaProgramId;
private int avgFitnessInEpoch;
private String path;
private double reachedFitness;
public Solver(String path) {
this.path = path;
this.reachedFitness = 0;
for (int i : new IntegerSequence.Range(0, 100, 1)) {
programs.add(new Program(false));
}
}
public void solve() {
// saveAndCompile(programs.get(0), " 100 0 0 0 0 0 0 0 ");
int size = programs.size();
for (int i : new IntegerSequence.Range(1, epochs, 1)) {
epoch = i;
// if (fBestPop > -1e-5) { todo
// System.out.print("PROBLEM SOLVED\n");
// System.exit(0);
// }
// for (Program indiv : programs) {
// evaluate(indiv);
//
// }
printEpochStarted();
for (int j=0; j < size; j++){
evaluate(programs.get(j));
}
printEpoch();
}
}
public void evaluate(Program indiv) {
// tournament -> crossover2 best -> negative tournament -> mutation
switch (new Random().nextInt(2)) {
case 0:
Program new_mutated = mutation(indiv);
new_mutated.setReachedFitness(fitness(new_mutated));
this.reachedFitness = Math.max(new_mutated.getReachedFitness(), this.reachedFitness);
this.programs.add(new_mutated);
break;
case 1:
Program child = cross(indiv, tournament());
child.setReachedFitness(fitness(child));
this.reachedFitness = Math.max(child.getReachedFitness(), this.reachedFitness);
this.programs.add(child);
break;
}
// System.out.println("Best fitness: " + this.reachedFitness);
negativeTournament();
}
private Program cross(Program parent1, Program parent2){
return Operations.cross(parent1, parent2);
}
public Program tournament() {
for(Program program: programs){
if(program.getReachedFitness()==reachedFitness)
return program;
}
return programs.get(0); //i tak <SUF>
}
public void negativeTournament () {
double worstFitness = 0;
Integer index = null;
for (int i = 0; i < this.programs.size(); i++) {
if (programs.get(i).getReachedFitness() < worstFitness) {
index = i;
break;
}
}
if (index != null) {
this.programs.remove(index.intValue());
System.out.println("Usunieto w indeksie: " + index);
}
}
public Program mutation(Program a) {
return Operations.mutation(a);
}
public List<Integer> getProgramOutputs(){
try{
BufferedReader br = new BufferedReader(new FileReader(this.outputFilename));
String line;
String outputs = "";
while ((line = br.readLine()) != null) {
outputs = outputs = outputs + " " + line;
}
return convert2List(outputs);
} catch (IOException e) {
e.printStackTrace();
}
return null; // to nie powinno się nigdy wykona
}
public boolean isOutputEmpty(){
File file = new File(this.outputFilename);
if (file.length() == 0) {
System.out.println("The file is empty");
return true;
} else {
System.out.println("The file is not empty");
return false;
}
}
public double gradeOccurancesInFile(List<Integer> output) {
// List<Integer> programOutputs = getProgramOutputs();
// int count = 0;x
// for(int i= 0; i<output.size(); i++){
// for(int j=0; j<programOutputs.size();j++){
// count ++;
// }
// }
// return count/output.size();
// List<Integer> programOutputs = getProgramOutputs();
// if(output != null && !output.isEmpty() && programOutputs != null && !programOutputs.isEmpty()){
// for (Integer element : output) {
// if (programOutputs.contains(element)) {
// count++;
// }
// }}
// return count;
return 0.0;
}
public double gradeDistanceBetweenOutputs(List<Integer> output){
double grade = 0;
List<Integer> programOutputs = getProgramOutputs();
for(int i=0; i<output.size(); i++){
if(output.get(i)==programOutputs.get(i))
grade = 1_000_000;
else
grade = grade + (1/Math.abs(output.get(i)-programOutputs.get(i)));
}
return grade/output.size();
}
public boolean doesProgramRuns(){
try{
BufferedReader br = new BufferedReader(new FileReader(this.outputFilename));
String line;
while ((line = br.readLine()) != null) {
if(line.contains("ERROR")) return false;
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
public boolean doesProgramHaveExpectedOutputLength(int outputLength){
try {
BufferedReader br = new BufferedReader(new FileReader(this.outputFilename));
String line;
int i= 0;
while ((line = br.readLine()) != null) {
i++;
}
return outputLength==i;
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
private double fittnes4Case(List<Integer> outputs, int checkOutputLength){
//checking if the program returns error
if(!doesProgramRuns()||isOutputEmpty()) return -1;
if(checkOutputLength>0 ){
//checking if the number of length of outputs matches number of expected outputs
if(!doesProgramHaveExpectedOutputLength(outputs.size())) return 0.0;
//read the file and return the sqrt of sum of squares
return gradeDistanceBetweenOutputs(outputs);
}else {
return gradeOccurancesInFile(outputs);
}
}
private List<Integer> convert2List(String s){
String[] parts = s.split(" ");
List<String> stringList = Arrays.asList(parts);
List<Integer> numbers = stringList.stream().filter(n-> n!= null && !Objects.equals(n, ""))
.map(Integer::parseInt)
.collect(Collectors.toList());
return numbers;
}
private double fitness(Program program){ // TODO: szczerze powiedziawszy to ja bym zrobił, że im mniejszy błąd tym lepszy fitness case?
String line;
try (BufferedReader br = new BufferedReader(new FileReader(this.path))) {
String headerLine = br.readLine();
List<Integer> numbers = convert2List(headerLine);
int rotations = numbers.get(0);
int inputs = numbers.get(1);
int outputs = numbers.get(2);
int test_cases = numbers.get(3);
double avg_fitness = 0;
for(int i=0; i<test_cases; i++){
//read line and complile program using input and calculate fitness for single case
String testCase = br.readLine();
List<Integer> n = convert2List(testCase);
List<Integer> inputsList = n.subList(0,inputs);
List<Integer> outputsList = new ArrayList<>();
outputsList.addAll(n.subList(inputs, n.size()));
inputsList.add(0, rotations);
String input = String.join(" ", inputsList.stream().map(Object::toString).collect(Collectors.toList()));
saveAndCompile(program, input);
avg_fitness+=fittnes4Case( outputsList, outputs);
}
return avg_fitness/test_cases;
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
private void saveAndCompile(Program program, String input) {
try{
String program_txt = program.getTreeProgTxt();
// System.out.println("\n ------- program txt in Bobaro-------\n");
// System.out.println(program_txt);
// System.out.println("\n ------- program txt end -------\n");
CharStream charStream1 = CharStreams.fromString(program_txt);
BobaroLexer lexer = new BobaroLexer(charStream1);
CommonTokenStream tokens = new CommonTokenStream(lexer);
BobaroParser parser = new BobaroParser(tokens);
String str = new BobaroVisitor().visit(parser.program());
StringBuilder sb = new StringBuilder();
if(program.getVariables()!=null && !program.getVariables().isEmpty()) {
sb.append("int ");
boolean first = true;
for (TokenNode tn : program.getVariables()) {
if(!first){
sb.append(", ");
}
sb.append(tn.getToken());
first=false;
}
sb.append(";");
}
String toInsert = sb.toString();
String searchPhrase = "char *argv[]) {";
int pos_str = str.indexOf(searchPhrase)+searchPhrase.length();
str = new StringBuilder(str).insert(pos_str, toInsert).toString();
// System.out.println("\n ------- program txt in Cpp -------\n");
// System.out.println(str);
// System.out.println("\n ------- program txt in Cpp end -------\n");
try (PrintWriter out = new PrintWriter("/Users/mikolajborowicz/Documents/Local/ProgramowanieGenetyczne/TinyGP/program.cpp")) {
out.println(str);
}catch (Exception e){
e.printStackTrace();
}
ProcessBuilder build =
new ProcessBuilder("g++", "/Users/mikolajborowicz/Documents/Local/ProgramowanieGenetyczne/TinyGP/program.cpp");
// create the process
Process process = build.start();
process.waitFor();
ProcessBuilder build2 =
new ProcessBuilder("/Users/mikolajborowicz/Documents/Local/ProgramowanieGenetyczne/TinyGP/a.out");
// create the process
Process process2 = build2.start();
process2.waitFor();
}catch (Exception e){
e.printStackTrace();
}
}
private void printEpoch(){
System.out.println("Epoch: " + epoch + "score: " + reachedFitness);
}
private void printEpochStarted(){
System.out.println("Epoch: " + epoch + " just started.");
}
}
| null |
10350_1 | Pastor-git/s23819projectGUI | 5,613 | src/components/eventComponents/GameControler.java | package components.eventComponents;
import Interface.MoveInterface;
import components.Const;
import components.backendComponents.Board;
import components.backendComponents.MainBoard;
import components.backendComponents.Tile;
import components.gameComponents.MainFrame;
import components.sideComponents.EndScreen;
import components.sideComponents.WelcomeMenu;
import enums.GameColors;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
public class GameControler implements MoveInterface {
// GABINET CIENI ROZGRYWKI - BACKEND ODPOWADAJACY ZA SPRAWDZANIE WSZSYKICH CZYNNIKÓW GRY NA PODSTAWIE STATE I INNYCH KOMPONENTÓ
State state;
MainBoard mainBoard;
int player_number = 1;
boolean endGame = false;
public static int x =0;
public static int y =0;
public static int bigX =0;
public static int bigY =0;
int gameResult = 0;
public GameControler() {
}
public GameControler(State state, MainBoard mainBoard) throws IOException {
this.state = state;
this.mainBoard = mainBoard;
stateGameLoad(state.gameLabel);
}
// SAVE GAME
public void saveGame() throws IOException {
SaveGame saveGame = new SaveGame(this.mainBoard,this.bigX,this.bigY,this.player_number);
System.out.println("gameControler Speaks: save game pressed");
saveGame.saveGameToTXT();
}
// GAME START
public void stateGameLoad(String label) throws IOException {
state.gameLunch();
System.out.println("inizalizacja gry z poziomu gameControler" + label);
if(label.equals("LOAD")) {
System.out.println("!Będę wczytywć grę z saveGame!");
this.player_number = state.player_turn;
this.bigX = state.bigX;
this.bigY = state.bigY;
this.mainBoard.setMainIntBoard(state.shadowMainBoard.getMainIntBoard());
for (int i =0;i<3;i++) {
for(int j =0; j<3;j++) {
mainBoard.getMainBoardTab()[i][j].setIntBoard(state.shadowMainBoard.getMainBoardTab()[i][j].getIntBoard());
}
}
resetTiles();
}
}
public void resetTiles() {
for (int i =0;i<3;i++) {
for(int j =0; j<3;j++) {
if(mainBoard.getMainIntBoard()[i][j]==3) {
for (int a =0;a<3;a++) {
for(int b =0; b<3;b++) {
setColorBorder(mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].getButton(), GameColors.GRAY);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].getButton().setIcon(Const.BASIC);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].setActive(false);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].setPressed(true);
}
}
} else if (mainBoard.getMainIntBoard()[i][j]==2) {
for (int a =0;a<3;a++) {
for(int b =0; b<3;b++) {
setColorBorder(mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].getButton(), GameColors.RED);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].getButton().setIcon(Const.GRACZ2);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].setActive(false);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].setPressed(true);
}
}
} else if (mainBoard.getMainIntBoard()[i][j]==1) {
for (int a =0;a<3;a++) {
for(int b =0; b<3;b++) {
setColorBorder(mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].getButton(), GameColors.BLUE);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].getButton().setIcon(Const.GRACZ1);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].setActive(false);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].setPressed(true);
}
}
} else if (mainBoard.getMainIntBoard()[i][j]==0){
for (int a =0;a<3;a++) {
for(int b =0; b<3;b++) {
if (mainBoard.getMainBoardTab()[i][j].getIntBoard()[a][b]==2) {
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].getButton().setIcon(Const.GRACZ2);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].setActive(false);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].setPressed(true);
} else if (mainBoard.getMainBoardTab()[i][j].getIntBoard()[a][b]==1) {
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].getButton().setIcon(Const.GRACZ1);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].setActive(false);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].setPressed(true);
} else {
// System.out.println("nic na tym polu nie ma!");
}
}
}
}
}
}
TicTacToaStyleMove();
}
// METHODS GAMEPLAY
//TICTACTOE STYLE
public void TicTacToaStyleMove() {
MainBoard boardTTT = getMainBoard();
if(boardTTT.getMainIntBoard()[this.bigX][this.bigY]!=0){
resetMainBoard();
System.out.println("plansza (X,Y): (" + this.bigX + "," + this.bigY + ") ma wartość: " + boardTTT.getMainIntBoard()[this.bigX][this.bigY]);
} else {
Board temBoard = getDobraBoardTablica(this.bigX, this.bigY);
resetMainBoardToFalse();
if(endGame==false) {
setColorInTileBoarder(temBoard.getTileBoard(), temBoard.getIntBoard(), GameColors.YELLOW);
}
}
}
public Board getDobraBoardTablica(int bigX, int bigY) {
Board board = mainBoard.getMainBoardTab()[bigX][bigY];
return board;
}
public void resetMainBoard() {
for (int i = 2; i>= 0;i--) {
for (int j = 0; j< 3; j++) {
resetBorderTileBoard(getDobraBoardTablica(j,i).getTileBoard(),getDobraBoardTablica(j,i).getIntBoard());
}
}
}
public void resetMainBoardToFalse() {
for (int i = 2; i>= 0;i--) {
for (int j = 0; j< 3; j++) {
setAllFalse(getDobraBoardTablica(j,i).getTileBoard(),getDobraBoardTablica(j,i).getIntBoard());
}
}
}
public void setAllFalse(Tile[][] tab, int[][]intTab) {
for (int i = 2; i>= 0;i--) {
for (int j = 0; j< 3; j++) {
if(intTab[j][i]==0) {
tab[j][i].setActive(false);
resetColorBorder(tab[j][i].getButton());
}
}
}
}
public void resetBorderTileBoard(Tile[][] tab, int[][]intTab) {
for (int i = 2; i>= 0;i--) {
for (int j = 0; j< 3; j++) {
if(intTab[j][i]==0) {
resetColorBorder(tab[j][i].getButton());
tab[j][i].setActive(true);
}
}
}
}
public void setColorInTileBoarder(Tile[][] tileTab,int[][]intTab, GameColors vale) {
for (int i = 2; i>= 0;i--) {
for (int j = 0; j< 3; j++) {
if(intTab[j][i]==0) {
setColorBorder(tileTab[j][i].getButton(), vale);
tileTab[j][i].setActive(true);
}
}
}
}
public void nextStep(int x, int y){
setX(this.bigX);
setY(this.bigY);
setBigX(x);
setBigY(y);
System.out.println("last move (x,y): (" + this.x + "," + this.y + ")");
System.out.println("next move (x,y): (" + this.bigX + "," + this.bigY + ")");
}
//TICTACTOE STYLE
//HERE IS MAIN ACTION!IT'S FINE WITH THAT BUT... ARE YOU GONA MOVE!?
public void move(int x, int y, int bigX, int bigY) {
switch (player_number) {
case 1:
getDobryPrzycisk(x, y, bigX, bigY).setIcon(Const.GRACZ1);
setButtonPressed(getDobryTile(x, y, bigX, bigY));
resetColorBorder(getDobryPrzycisk(x, y, bigX, bigY));
// int[][] section
setSmallIntTabCell(x,y,bigX,bigY,player_number);
printIntTab(getSmallIntTab(bigX,bigY));
int end1 = state.resultIntTab(getSmallIntTab(bigX,bigY));
System.out.println("move result: " + end1);
if (end1!=0) {
setTileBord(getGoodTileTab(bigX,bigY),end1);
setIntTab(getDobraBoardTablica(bigX,bigY).getIntBoard(),end1);
setBigIntTabCell(bigX,bigY,end1);
printIntTab(getBigIntTab());
}
endGame(end1);
// NEXT MOVE
player_number = 2;
nextStep(x,y);
TicTacToaStyleMove();
break;
case 2:
getDobryPrzycisk(x, y, bigX, bigY).setIcon(Const.GRACZ2);
setButtonPressed(getDobryTile(x, y, bigX, bigY));
resetColorBorder(getDobryPrzycisk(x, y, bigX, bigY));
// int[][] section
setSmallIntTabCell(x,y,bigX,bigY,player_number);
printIntTab(getSmallIntTab(bigX,bigY));
int end2 = state.resultIntTab(getSmallIntTab(bigX,bigY));
System.out.println("result: " + end2);
if (end2!=0) {
setTileBord(getGoodTileTab(bigX,bigY),end2);
setIntTab(getDobraBoardTablica(bigX,bigY).getIntBoard(),end2);
setBigIntTabCell(bigX,bigY,end2);
printIntTab(getBigIntTab());
}
endGame(end2);
// NEXT MOVE
player_number = 1;
nextStep(x,y);
TicTacToaStyleMove();
break;
}
System.out.println("gameContorler says: moved");
}
//SUPPORT METHODS
public void setIntTab(int[][] tab, int value) {
for (int i = 2; i>= 0;i--) {
for (int j = 0; j < 3; j++) {
if (tab[j][i] == 0) {
tab[j][i]=value;
}
}
}
}
public void endGame(int winner){
if(finalResult()!=0) {
endGame=true;
gameResult = finalResult();
String win;
if(winner==1) {
win="X";
}
else {
win="O";
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
EndScreen endScreen = new EndScreen(win);}
});
}
}
public int finalResult() {
int result = 0;
if((state.resultIntTab(getBigIntTab())==1)) {
result = 1;
} else if((state.resultIntTab(getBigIntTab())==2)) {
result = 2;
} else if((state.resultIntTab(getBigIntTab())==3)) {
result = 3;
} else {
result =0;
}
System.out.println("final resault: " + result);
return result;
}
public Tile[][] getGoodTileTab(int bigX, int bigY){
return this.mainBoard.getMainBoardTab()[bigX][bigY].getTileBoard();
}
public JButton getDobryPrzycisk(int x, int y, int bigX, int bigY) {
return this.mainBoard.getMainBoardTab()[bigX][bigY].getTileBoard()[x][y].getButton();
}
public Tile getDobryTile(int x, int y, int bigX, int bigY) {
return this.mainBoard.getMainBoardTab()[bigX][bigY].getTileBoard()[x][y];
}
public void setButtonPressed(Tile tile) {
tile.setPressed(true);
}
public void setBasicIcon(JButton button) {
button.setIcon(Const.BASIC2);
}
public void setIntCell(int xX, int yY, int[][] tab, int value) {
tab[xX][yY] = value;
}
public int returnIntCell() {
return 0;
}
public int[][] getBigIntTab() {
return this.mainBoard.getMainIntBoard();
}
public int[][] getSmallIntTab(int bigX, int bigY) {
return this.mainBoard.getMainBoardTab()[bigX][bigY].getIntBoard();
}
public void setBigIntTabCell(int bigX, int bigY, int value) {
this.mainBoard.getMainIntBoard()[bigX][bigY]=value;
}
public void setSmallIntTabCell(int x, int y, int bigX, int bigY, int value) {
this.mainBoard.getMainBoardTab()[bigX][bigY].getIntBoard()[x][y] = value;
}
// switchActiveButton()
// WINLOSECONDIDONS METHODS
public void setTileBord(Tile[][] tab, int player_number) {
// ANIMACJA!!!!!
int delay = 20;
Timer timer = new Timer(delay, null);
timer.addActionListener(new ActionListener() {
int k = tab.length - 1;
int l = 0;
@Override
public void actionPerformed(ActionEvent e) {
if (k >= 0) {
setButtonPressed(tab[l][k]);
if (player_number == 1) {
setColorBorder(tab[l][k].getButton(), GameColors.BLUE);
tab[l][k].getButton().setIcon(Const.GRACZ1);
} else if (player_number == 2) {
setColorBorder(tab[l][k].getButton(), GameColors.RED);
tab[l][k].getButton().setIcon(Const.GRACZ2);
} else {
setColorBorder(tab[l][k].getButton(), GameColors.GRAY);
tab[l][k].getButton().setIcon(Const.BASIC2);
}
l++;
if (l >= tab[k].length) {
l = 0;
k--;
}
if (k < 0) {
timer.stop();
}
}
}
});
// TU CISNIEMY Z WĄTKIEM DLA INSTANCJI TIMERA
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
timer.setInitialDelay(40);
timer.start();
}
});
// timer.setInitialDelay(100);
// timer.start();
}
public void setColorBorder (JButton button, GameColors value) {
Color borderColor;
switch (value) {
case RED:
borderColor = Color.RED;
break;
case BLUE:
borderColor = Color.BLUE;
break;
case GREEN:
borderColor = Color.GREEN;
break;
case GRAY:
borderColor = Color.GRAY;
break;
case YELLOW:
borderColor = Color.YELLOW;
break;
default:
borderColor = Color.BLACK;
break;
}
int borderWidth = 4;
Border lineBorder = BorderFactory.createLineBorder(borderColor, borderWidth);
button.setBorder(lineBorder);
}
//KASOWANIE RAMKI
public static void resetColorBorder(JButton button) {
button.setBorder(null);
// button.setBorder(BorderFactory.createEtchedBorder());
}
// TEST METHODS
public void testPrint(int x, int y, int bigX, int bigY) {
System.out.println("GameControlerSpeaks:");
System.out.println("x:"+x + "y:" + y);
System.out.println("bigX:"+bigX + "bigY:" + bigY);
}
public void printIntTab(int[][] tab){
System.out.println("wywyłana tablica: ");
for(int i = tab.length-1;i >=0; i--) {
for (int j = 0; j<tab.length;j++) {
System.out.print(tab[j][i]);
}
System.out.println();
}
}
//BOILER PLATE
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public MainBoard getMainBoard() {
return mainBoard;
}
public void setMainBoard(MainBoard mainBoard) {
this.mainBoard = mainBoard;
}
public int getPlayer_number() {
return player_number;
}
public void setPlayer_number(int player_number) {
this.player_number = player_number;
}
public boolean isEndGame() {
return endGame;
}
public void setEndGame(boolean endGame) {
this.endGame = endGame;
}
public int getGameResult() {
return gameResult;
}
public void setGameResult(int gameResult) {
this.gameResult = gameResult;
}
public static int getBigX() {
return bigX;
}
public static void setBigX(int bigX) {
GameControler.bigX = bigX;
}
public static int getBigY() {
return bigY;
}
public static void setBigY(int bigY) {
GameControler.bigY = bigY;
}
public static int getX() {
return x;
}
public static void setX(int x) {
GameControler.x = x;
}
public static int getY() {
return y;
}
public static void setY(int y) {
GameControler.y = y;
}
}
| // System.out.println("nic na tym polu nie ma!"); | package components.eventComponents;
import Interface.MoveInterface;
import components.Const;
import components.backendComponents.Board;
import components.backendComponents.MainBoard;
import components.backendComponents.Tile;
import components.gameComponents.MainFrame;
import components.sideComponents.EndScreen;
import components.sideComponents.WelcomeMenu;
import enums.GameColors;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
public class GameControler implements MoveInterface {
// GABINET CIENI ROZGRYWKI - BACKEND ODPOWADAJACY ZA SPRAWDZANIE WSZSYKICH CZYNNIKÓW GRY NA PODSTAWIE STATE I INNYCH KOMPONENTÓ
State state;
MainBoard mainBoard;
int player_number = 1;
boolean endGame = false;
public static int x =0;
public static int y =0;
public static int bigX =0;
public static int bigY =0;
int gameResult = 0;
public GameControler() {
}
public GameControler(State state, MainBoard mainBoard) throws IOException {
this.state = state;
this.mainBoard = mainBoard;
stateGameLoad(state.gameLabel);
}
// SAVE GAME
public void saveGame() throws IOException {
SaveGame saveGame = new SaveGame(this.mainBoard,this.bigX,this.bigY,this.player_number);
System.out.println("gameControler Speaks: save game pressed");
saveGame.saveGameToTXT();
}
// GAME START
public void stateGameLoad(String label) throws IOException {
state.gameLunch();
System.out.println("inizalizacja gry z poziomu gameControler" + label);
if(label.equals("LOAD")) {
System.out.println("!Będę wczytywć grę z saveGame!");
this.player_number = state.player_turn;
this.bigX = state.bigX;
this.bigY = state.bigY;
this.mainBoard.setMainIntBoard(state.shadowMainBoard.getMainIntBoard());
for (int i =0;i<3;i++) {
for(int j =0; j<3;j++) {
mainBoard.getMainBoardTab()[i][j].setIntBoard(state.shadowMainBoard.getMainBoardTab()[i][j].getIntBoard());
}
}
resetTiles();
}
}
public void resetTiles() {
for (int i =0;i<3;i++) {
for(int j =0; j<3;j++) {
if(mainBoard.getMainIntBoard()[i][j]==3) {
for (int a =0;a<3;a++) {
for(int b =0; b<3;b++) {
setColorBorder(mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].getButton(), GameColors.GRAY);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].getButton().setIcon(Const.BASIC);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].setActive(false);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].setPressed(true);
}
}
} else if (mainBoard.getMainIntBoard()[i][j]==2) {
for (int a =0;a<3;a++) {
for(int b =0; b<3;b++) {
setColorBorder(mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].getButton(), GameColors.RED);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].getButton().setIcon(Const.GRACZ2);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].setActive(false);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].setPressed(true);
}
}
} else if (mainBoard.getMainIntBoard()[i][j]==1) {
for (int a =0;a<3;a++) {
for(int b =0; b<3;b++) {
setColorBorder(mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].getButton(), GameColors.BLUE);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].getButton().setIcon(Const.GRACZ1);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].setActive(false);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].setPressed(true);
}
}
} else if (mainBoard.getMainIntBoard()[i][j]==0){
for (int a =0;a<3;a++) {
for(int b =0; b<3;b++) {
if (mainBoard.getMainBoardTab()[i][j].getIntBoard()[a][b]==2) {
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].getButton().setIcon(Const.GRACZ2);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].setActive(false);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].setPressed(true);
} else if (mainBoard.getMainBoardTab()[i][j].getIntBoard()[a][b]==1) {
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].getButton().setIcon(Const.GRACZ1);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].setActive(false);
mainBoard.getMainBoardTab()[i][j].getTileBoard()[a][b].setPressed(true);
} else {
// System.out.println("nic na <SUF>
}
}
}
}
}
}
TicTacToaStyleMove();
}
// METHODS GAMEPLAY
//TICTACTOE STYLE
public void TicTacToaStyleMove() {
MainBoard boardTTT = getMainBoard();
if(boardTTT.getMainIntBoard()[this.bigX][this.bigY]!=0){
resetMainBoard();
System.out.println("plansza (X,Y): (" + this.bigX + "," + this.bigY + ") ma wartość: " + boardTTT.getMainIntBoard()[this.bigX][this.bigY]);
} else {
Board temBoard = getDobraBoardTablica(this.bigX, this.bigY);
resetMainBoardToFalse();
if(endGame==false) {
setColorInTileBoarder(temBoard.getTileBoard(), temBoard.getIntBoard(), GameColors.YELLOW);
}
}
}
public Board getDobraBoardTablica(int bigX, int bigY) {
Board board = mainBoard.getMainBoardTab()[bigX][bigY];
return board;
}
public void resetMainBoard() {
for (int i = 2; i>= 0;i--) {
for (int j = 0; j< 3; j++) {
resetBorderTileBoard(getDobraBoardTablica(j,i).getTileBoard(),getDobraBoardTablica(j,i).getIntBoard());
}
}
}
public void resetMainBoardToFalse() {
for (int i = 2; i>= 0;i--) {
for (int j = 0; j< 3; j++) {
setAllFalse(getDobraBoardTablica(j,i).getTileBoard(),getDobraBoardTablica(j,i).getIntBoard());
}
}
}
public void setAllFalse(Tile[][] tab, int[][]intTab) {
for (int i = 2; i>= 0;i--) {
for (int j = 0; j< 3; j++) {
if(intTab[j][i]==0) {
tab[j][i].setActive(false);
resetColorBorder(tab[j][i].getButton());
}
}
}
}
public void resetBorderTileBoard(Tile[][] tab, int[][]intTab) {
for (int i = 2; i>= 0;i--) {
for (int j = 0; j< 3; j++) {
if(intTab[j][i]==0) {
resetColorBorder(tab[j][i].getButton());
tab[j][i].setActive(true);
}
}
}
}
public void setColorInTileBoarder(Tile[][] tileTab,int[][]intTab, GameColors vale) {
for (int i = 2; i>= 0;i--) {
for (int j = 0; j< 3; j++) {
if(intTab[j][i]==0) {
setColorBorder(tileTab[j][i].getButton(), vale);
tileTab[j][i].setActive(true);
}
}
}
}
public void nextStep(int x, int y){
setX(this.bigX);
setY(this.bigY);
setBigX(x);
setBigY(y);
System.out.println("last move (x,y): (" + this.x + "," + this.y + ")");
System.out.println("next move (x,y): (" + this.bigX + "," + this.bigY + ")");
}
//TICTACTOE STYLE
//HERE IS MAIN ACTION!IT'S FINE WITH THAT BUT... ARE YOU GONA MOVE!?
public void move(int x, int y, int bigX, int bigY) {
switch (player_number) {
case 1:
getDobryPrzycisk(x, y, bigX, bigY).setIcon(Const.GRACZ1);
setButtonPressed(getDobryTile(x, y, bigX, bigY));
resetColorBorder(getDobryPrzycisk(x, y, bigX, bigY));
// int[][] section
setSmallIntTabCell(x,y,bigX,bigY,player_number);
printIntTab(getSmallIntTab(bigX,bigY));
int end1 = state.resultIntTab(getSmallIntTab(bigX,bigY));
System.out.println("move result: " + end1);
if (end1!=0) {
setTileBord(getGoodTileTab(bigX,bigY),end1);
setIntTab(getDobraBoardTablica(bigX,bigY).getIntBoard(),end1);
setBigIntTabCell(bigX,bigY,end1);
printIntTab(getBigIntTab());
}
endGame(end1);
// NEXT MOVE
player_number = 2;
nextStep(x,y);
TicTacToaStyleMove();
break;
case 2:
getDobryPrzycisk(x, y, bigX, bigY).setIcon(Const.GRACZ2);
setButtonPressed(getDobryTile(x, y, bigX, bigY));
resetColorBorder(getDobryPrzycisk(x, y, bigX, bigY));
// int[][] section
setSmallIntTabCell(x,y,bigX,bigY,player_number);
printIntTab(getSmallIntTab(bigX,bigY));
int end2 = state.resultIntTab(getSmallIntTab(bigX,bigY));
System.out.println("result: " + end2);
if (end2!=0) {
setTileBord(getGoodTileTab(bigX,bigY),end2);
setIntTab(getDobraBoardTablica(bigX,bigY).getIntBoard(),end2);
setBigIntTabCell(bigX,bigY,end2);
printIntTab(getBigIntTab());
}
endGame(end2);
// NEXT MOVE
player_number = 1;
nextStep(x,y);
TicTacToaStyleMove();
break;
}
System.out.println("gameContorler says: moved");
}
//SUPPORT METHODS
public void setIntTab(int[][] tab, int value) {
for (int i = 2; i>= 0;i--) {
for (int j = 0; j < 3; j++) {
if (tab[j][i] == 0) {
tab[j][i]=value;
}
}
}
}
public void endGame(int winner){
if(finalResult()!=0) {
endGame=true;
gameResult = finalResult();
String win;
if(winner==1) {
win="X";
}
else {
win="O";
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
EndScreen endScreen = new EndScreen(win);}
});
}
}
public int finalResult() {
int result = 0;
if((state.resultIntTab(getBigIntTab())==1)) {
result = 1;
} else if((state.resultIntTab(getBigIntTab())==2)) {
result = 2;
} else if((state.resultIntTab(getBigIntTab())==3)) {
result = 3;
} else {
result =0;
}
System.out.println("final resault: " + result);
return result;
}
public Tile[][] getGoodTileTab(int bigX, int bigY){
return this.mainBoard.getMainBoardTab()[bigX][bigY].getTileBoard();
}
public JButton getDobryPrzycisk(int x, int y, int bigX, int bigY) {
return this.mainBoard.getMainBoardTab()[bigX][bigY].getTileBoard()[x][y].getButton();
}
public Tile getDobryTile(int x, int y, int bigX, int bigY) {
return this.mainBoard.getMainBoardTab()[bigX][bigY].getTileBoard()[x][y];
}
public void setButtonPressed(Tile tile) {
tile.setPressed(true);
}
public void setBasicIcon(JButton button) {
button.setIcon(Const.BASIC2);
}
public void setIntCell(int xX, int yY, int[][] tab, int value) {
tab[xX][yY] = value;
}
public int returnIntCell() {
return 0;
}
public int[][] getBigIntTab() {
return this.mainBoard.getMainIntBoard();
}
public int[][] getSmallIntTab(int bigX, int bigY) {
return this.mainBoard.getMainBoardTab()[bigX][bigY].getIntBoard();
}
public void setBigIntTabCell(int bigX, int bigY, int value) {
this.mainBoard.getMainIntBoard()[bigX][bigY]=value;
}
public void setSmallIntTabCell(int x, int y, int bigX, int bigY, int value) {
this.mainBoard.getMainBoardTab()[bigX][bigY].getIntBoard()[x][y] = value;
}
// switchActiveButton()
// WINLOSECONDIDONS METHODS
public void setTileBord(Tile[][] tab, int player_number) {
// ANIMACJA!!!!!
int delay = 20;
Timer timer = new Timer(delay, null);
timer.addActionListener(new ActionListener() {
int k = tab.length - 1;
int l = 0;
@Override
public void actionPerformed(ActionEvent e) {
if (k >= 0) {
setButtonPressed(tab[l][k]);
if (player_number == 1) {
setColorBorder(tab[l][k].getButton(), GameColors.BLUE);
tab[l][k].getButton().setIcon(Const.GRACZ1);
} else if (player_number == 2) {
setColorBorder(tab[l][k].getButton(), GameColors.RED);
tab[l][k].getButton().setIcon(Const.GRACZ2);
} else {
setColorBorder(tab[l][k].getButton(), GameColors.GRAY);
tab[l][k].getButton().setIcon(Const.BASIC2);
}
l++;
if (l >= tab[k].length) {
l = 0;
k--;
}
if (k < 0) {
timer.stop();
}
}
}
});
// TU CISNIEMY Z WĄTKIEM DLA INSTANCJI TIMERA
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
timer.setInitialDelay(40);
timer.start();
}
});
// timer.setInitialDelay(100);
// timer.start();
}
public void setColorBorder (JButton button, GameColors value) {
Color borderColor;
switch (value) {
case RED:
borderColor = Color.RED;
break;
case BLUE:
borderColor = Color.BLUE;
break;
case GREEN:
borderColor = Color.GREEN;
break;
case GRAY:
borderColor = Color.GRAY;
break;
case YELLOW:
borderColor = Color.YELLOW;
break;
default:
borderColor = Color.BLACK;
break;
}
int borderWidth = 4;
Border lineBorder = BorderFactory.createLineBorder(borderColor, borderWidth);
button.setBorder(lineBorder);
}
//KASOWANIE RAMKI
public static void resetColorBorder(JButton button) {
button.setBorder(null);
// button.setBorder(BorderFactory.createEtchedBorder());
}
// TEST METHODS
public void testPrint(int x, int y, int bigX, int bigY) {
System.out.println("GameControlerSpeaks:");
System.out.println("x:"+x + "y:" + y);
System.out.println("bigX:"+bigX + "bigY:" + bigY);
}
public void printIntTab(int[][] tab){
System.out.println("wywyłana tablica: ");
for(int i = tab.length-1;i >=0; i--) {
for (int j = 0; j<tab.length;j++) {
System.out.print(tab[j][i]);
}
System.out.println();
}
}
//BOILER PLATE
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public MainBoard getMainBoard() {
return mainBoard;
}
public void setMainBoard(MainBoard mainBoard) {
this.mainBoard = mainBoard;
}
public int getPlayer_number() {
return player_number;
}
public void setPlayer_number(int player_number) {
this.player_number = player_number;
}
public boolean isEndGame() {
return endGame;
}
public void setEndGame(boolean endGame) {
this.endGame = endGame;
}
public int getGameResult() {
return gameResult;
}
public void setGameResult(int gameResult) {
this.gameResult = gameResult;
}
public static int getBigX() {
return bigX;
}
public static void setBigX(int bigX) {
GameControler.bigX = bigX;
}
public static int getBigY() {
return bigY;
}
public static void setBigY(int bigY) {
GameControler.bigY = bigY;
}
public static int getX() {
return x;
}
public static void setX(int x) {
GameControler.x = x;
}
public static int getY() {
return y;
}
public static void setY(int y) {
GameControler.y = y;
}
}
| null |
5693_1 | PatrykZdz/Bazy_g1_PZ | 1,548 | Java 04.01.24 kogos.java | public class Main {
public static void main(String[] args) {
Box<Integer> box = new Box<>(3);
//zad2();
//zad3();
}
public static void zad2() {
Counter<String> counter = new Counter<>();
counter.add("Test");
counter.add("Kolejny");
counter.add("Nastepny");
System.out.println(counter.getCount());
}
public static void zad3(){
Triple<Integer, Double, String> triple = new Triple<>(1, 2.2, "Tekst");
System.out.println(triple.getFirst());
System.out.println(triple.getSecond());
System.out.println(triple.getThird());
}
//public static <T extends Animal> T;
//TODO: Stwórz klasę generyczną Pair<T>, która przechowuje dwa obiekty tego samego typu. Następnie utwórz dwie klasy: Plant i Tree, gdzie Tree dziedziczy po Plant. Klasa Tree powinna posiadać prywatne pole height, którego nie posiada klasa Plant. Następnie napisz statyczną metodę generyczną findMinMaxHeight, która przyjmuje jako argument tablicę obiektów typu Tree oraz Pair<? super Tree> result. Metoda powinna zapisać (jako obiekty typu Tree) najniższe i najwyższe (pod kątem wysokości) drzewo z tablicy w drugim argumencie metody. Wykorzystaj też generyczny interfejs Comparable.
public static <T> void findMinMaxHeight(Tree[], Pair<? super Tree>){
}
}
public class Plant {
}
class Tree extends Plant{
private int height;
}
public class Pair <T>{
T obj1;
T obj2;
}
//TODO: Utwórz dwie klasy: Animal (Zwierzę) i Dog (Pies), gdzie Dog dziedziczy po Animal. Następnie napisz statyczną metodę generyczną findMax, która przyjmuje dwa argumenty: element1 i element2 typu extends Animal. Metoda powinna zwracać element większy według własnie zdefiniowanego kryterium porównania. W implementacji porównaj elementy bazując na wybranym przez siebie atrybucie, na przykład wieku.
public class Animal {
}
class Dog extends Animal{
}
//TODO: Napisz statyczną metodę generyczną minValue, która przyjmuje tablicę elementów typu generycznego T, gdzie T rozszerza Comparable<T>. Metoda powinna zwracać najmniejszy element z tablicy. Przetestuj tę metodę na tablicach zawierających różne typy porównywalnych obiektów, takie jak Integer, Double, czy String. Zabezpiecz metodę tak, aby nie można było jej wywołać z tablicą o zerowej liczbie elementów. Dodaj klasę ’Personz polaminameiagei przetestuj metodęminValuena tablicy obiektówPerson`.
public class Value {
public static <T extends Comparable<T>> T minValue(T[] a) {
if(a.length == 0 ) throw new IllegalArgumentException();
T min = a[0];
for(int i = 1; i < a.length; ++i){
if(min.compareTo(a[i]) > 0) {
min = a[i];
}
}
return min;
}
}
import java.util.Arrays;
//TODO: Zabezpiecz metodę tak, aby nie można było wywołać błędu związanego z przekroczeniem zakresu tablicy.
public class Swap {
public static <T> void swap(T[] array, int a, int b) {
T tmp1 = array[a];
T tmp2 = array[b];
array[a] = tmp2;
array[b] = tmp1;
}
public static void main(String[] args) {
Integer[] myArray = {0, 1, 2, 3, 4, 5, 6};
swap(myArray, 0, 4);
System.out.println(Arrays.toString(myArray));
}
}
public class Equals{
public static <T> boolean isEqual(T value1, T value2){
return value1.equals(value2);
}
public static void main(String[] args){
int a = 5;
int b = 4;
String s1 = "test";
String s2 = "test";
System.out.println(isEqual(a, b));
System.out.println(isEqual(s1, s2));
}
}
import java.util.ArrayList;
import java.util.List;
public class Counter <T>{
public T element;
List<T> list = new ArrayList<>();
public void add(T element) {
list.add(element);
}
public int getCount(){
return list.size();
}
}
public class Triple <T, U, V>{
public T first;
public U second;
public V third;
public Triple(T first, U second, V third) {
this.first = first;
this.second = second;
this.third = third;
}
public T getFirst() {
return first;
}
public U getSecond() {
return second;
}
public V getThird() {
return third;
}
}
public class Box <T>{
public T value;
public Box(T value){
this.value=value;
}
public T getValue(){
return value;
}
public void setValue(T value){
this.value = value;
}
}
| //TODO: Stwórz klasę generyczną Pair<T>, która przechowuje dwa obiekty tego samego typu. Następnie utwórz dwie klasy: Plant i Tree, gdzie Tree dziedziczy po Plant. Klasa Tree powinna posiadać prywatne pole height, którego nie posiada klasa Plant. Następnie napisz statyczną metodę generyczną findMinMaxHeight, która przyjmuje jako argument tablicę obiektów typu Tree oraz Pair<? super Tree> result. Metoda powinna zapisać (jako obiekty typu Tree) najniższe i najwyższe (pod kątem wysokości) drzewo z tablicy w drugim argumencie metody. Wykorzystaj też generyczny interfejs Comparable. | public class Main {
public static void main(String[] args) {
Box<Integer> box = new Box<>(3);
//zad2();
//zad3();
}
public static void zad2() {
Counter<String> counter = new Counter<>();
counter.add("Test");
counter.add("Kolejny");
counter.add("Nastepny");
System.out.println(counter.getCount());
}
public static void zad3(){
Triple<Integer, Double, String> triple = new Triple<>(1, 2.2, "Tekst");
System.out.println(triple.getFirst());
System.out.println(triple.getSecond());
System.out.println(triple.getThird());
}
//public static <T extends Animal> T;
//TODO: Stwórz <SUF>
public static <T> void findMinMaxHeight(Tree[], Pair<? super Tree>){
}
}
public class Plant {
}
class Tree extends Plant{
private int height;
}
public class Pair <T>{
T obj1;
T obj2;
}
//TODO: Utwórz dwie klasy: Animal (Zwierzę) i Dog (Pies), gdzie Dog dziedziczy po Animal. Następnie napisz statyczną metodę generyczną findMax, która przyjmuje dwa argumenty: element1 i element2 typu extends Animal. Metoda powinna zwracać element większy według własnie zdefiniowanego kryterium porównania. W implementacji porównaj elementy bazując na wybranym przez siebie atrybucie, na przykład wieku.
public class Animal {
}
class Dog extends Animal{
}
//TODO: Napisz statyczną metodę generyczną minValue, która przyjmuje tablicę elementów typu generycznego T, gdzie T rozszerza Comparable<T>. Metoda powinna zwracać najmniejszy element z tablicy. Przetestuj tę metodę na tablicach zawierających różne typy porównywalnych obiektów, takie jak Integer, Double, czy String. Zabezpiecz metodę tak, aby nie można było jej wywołać z tablicą o zerowej liczbie elementów. Dodaj klasę ’Personz polaminameiagei przetestuj metodęminValuena tablicy obiektówPerson`.
public class Value {
public static <T extends Comparable<T>> T minValue(T[] a) {
if(a.length == 0 ) throw new IllegalArgumentException();
T min = a[0];
for(int i = 1; i < a.length; ++i){
if(min.compareTo(a[i]) > 0) {
min = a[i];
}
}
return min;
}
}
import java.util.Arrays;
//TODO: Zabezpiecz metodę tak, aby nie można było wywołać błędu związanego z przekroczeniem zakresu tablicy.
public class Swap {
public static <T> void swap(T[] array, int a, int b) {
T tmp1 = array[a];
T tmp2 = array[b];
array[a] = tmp2;
array[b] = tmp1;
}
public static void main(String[] args) {
Integer[] myArray = {0, 1, 2, 3, 4, 5, 6};
swap(myArray, 0, 4);
System.out.println(Arrays.toString(myArray));
}
}
public class Equals{
public static <T> boolean isEqual(T value1, T value2){
return value1.equals(value2);
}
public static void main(String[] args){
int a = 5;
int b = 4;
String s1 = "test";
String s2 = "test";
System.out.println(isEqual(a, b));
System.out.println(isEqual(s1, s2));
}
}
import java.util.ArrayList;
import java.util.List;
public class Counter <T>{
public T element;
List<T> list = new ArrayList<>();
public void add(T element) {
list.add(element);
}
public int getCount(){
return list.size();
}
}
public class Triple <T, U, V>{
public T first;
public U second;
public V third;
public Triple(T first, U second, V third) {
this.first = first;
this.second = second;
this.third = third;
}
public T getFirst() {
return first;
}
public U getSecond() {
return second;
}
public V getThird() {
return third;
}
}
public class Box <T>{
public T value;
public Box(T value){
this.value=value;
}
public T getValue(){
return value;
}
public void setValue(T value){
this.value = value;
}
}
| null |
3759_0 | Pawlo77/Object-Oriented-Programming | 400 | Terminal/src/BramkaBezpieczenstwa.java | import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
public class BramkaBezpieczenstwa implements SkanujBagazInterface {
private final HashMap<Pasazer, List<PrzedmiotNielegalny>> nielegalnePrzedmioty;
public BramkaBezpieczenstwa() {
this.nielegalnePrzedmioty = new HashMap<>();
}
public boolean skanujBagaz(Pasazer pasazer, BagazPorderczny bagaz) throws KielbasaException {
List<PrzedmiotNielegalny> nielegalne = new LinkedList<>();
for (Przedmiot p : bagaz.pobierzPrzedmiotyZBagazu())
if (p.getStopienNielegalnosci() > 0) {
nielegalne.add((PrzedmiotNielegalny) p);
if (p instanceof Kielbasa) throw new KielbasaException();
break; // nie wiem mamy przerywac jak znajdziemy jeden a reszte olac
}
if (!nielegalne.isEmpty()) {
if (nielegalnePrzedmioty.containsKey(pasazer)) {
List<PrzedmiotNielegalny> old = this.nielegalnePrzedmioty.get(pasazer);
old.addAll(nielegalne);
} else {
this.nielegalnePrzedmioty.put(pasazer, nielegalne);
}
return false;
}
return true;
}
}
| // nie wiem mamy przerywac jak znajdziemy jeden a reszte olac | import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
public class BramkaBezpieczenstwa implements SkanujBagazInterface {
private final HashMap<Pasazer, List<PrzedmiotNielegalny>> nielegalnePrzedmioty;
public BramkaBezpieczenstwa() {
this.nielegalnePrzedmioty = new HashMap<>();
}
public boolean skanujBagaz(Pasazer pasazer, BagazPorderczny bagaz) throws KielbasaException {
List<PrzedmiotNielegalny> nielegalne = new LinkedList<>();
for (Przedmiot p : bagaz.pobierzPrzedmiotyZBagazu())
if (p.getStopienNielegalnosci() > 0) {
nielegalne.add((PrzedmiotNielegalny) p);
if (p instanceof Kielbasa) throw new KielbasaException();
break; // nie wiem <SUF>
}
if (!nielegalne.isEmpty()) {
if (nielegalnePrzedmioty.containsKey(pasazer)) {
List<PrzedmiotNielegalny> old = this.nielegalnePrzedmioty.get(pasazer);
old.addAll(nielegalne);
} else {
this.nielegalnePrzedmioty.put(pasazer, nielegalne);
}
return false;
}
return true;
}
}
| null |
6829_0 | PiotrSmola/Studies---Object-oriented-programming-2 | 944 | JAVA GUI/Lab04/src/Login.java | import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
public class Login extends JDialog {
private JPanel JPanelLogin;
private JTextField textFieldEmail;
private JPasswordField passwordField;
private JButton loginButton;
private JButton cancelButton;
private JLabel JLabelWelcome;
private JLabel JLabelLogin;
private JPanel JPanel1;
private JPanel JPanel2;
private JLabel JLabelIcon;
private JLabel JLabelEmail;
private JLabel JLabelPassword;
public Login(JFrame parent) {
super(parent); //skąd to parent
this.setContentPane(JPanelLogin);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.pack();
setLocationRelativeTo(parent); //to samo skąd to
setVisible(true);
loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String email = textFieldEmail.getText();
String password = String.valueOf(passwordField.getPassword());
user = getAuthUser(email, password);
if (user != null) {
dispose();
Dashboard dashboard = new Dashboard();
dashboard.setVisible(true);
} else {
JOptionPane.showMessageDialog(null, "Niepoprawne dane logowania!");
}
}
});
setVisible(true);
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
}
public User user;
private User getAuthUser(String email, String password) {
User user = null;
final String DB_URL = "jdbc:mysql://localhost:3306/mystore";
final String USERNAME = "root";
final String PASSWORD = "";
try {
Connection conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
Statement stmt = conn.createStatement();
String sql = "SELECT * FROM users WHERE email = ? AND password = ?";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, email);
preparedStatement.setString(2, password);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
user = new User();
user.name = resultSet.getString("name");
user.email = resultSet.getString("email");
user.phone = resultSet.getString("phone");
user.address = resultSet.getString("address");
user.password = resultSet.getString("password");
}
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
public static void main(String[] args) {
Login login = new Login(null); //dlaczego null
User user = login.user;
if (user != null) {
System.out.println("Zalogowano użytkownika: " + user.name);
System.out.println("Email: " + user.email);
System.out.println("Telefon: " + user.phone);
System.out.println("Adres: " + user.address);
} else {
System.out.println("Niepoprawne dane logowania!");
}
//NIE DZIAŁA POPRAWNIE
}
}
| //skąd to parent
| import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
public class Login extends JDialog {
private JPanel JPanelLogin;
private JTextField textFieldEmail;
private JPasswordField passwordField;
private JButton loginButton;
private JButton cancelButton;
private JLabel JLabelWelcome;
private JLabel JLabelLogin;
private JPanel JPanel1;
private JPanel JPanel2;
private JLabel JLabelIcon;
private JLabel JLabelEmail;
private JLabel JLabelPassword;
public Login(JFrame parent) {
super(parent); //skąd to <SUF>
this.setContentPane(JPanelLogin);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.pack();
setLocationRelativeTo(parent); //to samo skąd to
setVisible(true);
loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String email = textFieldEmail.getText();
String password = String.valueOf(passwordField.getPassword());
user = getAuthUser(email, password);
if (user != null) {
dispose();
Dashboard dashboard = new Dashboard();
dashboard.setVisible(true);
} else {
JOptionPane.showMessageDialog(null, "Niepoprawne dane logowania!");
}
}
});
setVisible(true);
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
}
public User user;
private User getAuthUser(String email, String password) {
User user = null;
final String DB_URL = "jdbc:mysql://localhost:3306/mystore";
final String USERNAME = "root";
final String PASSWORD = "";
try {
Connection conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
Statement stmt = conn.createStatement();
String sql = "SELECT * FROM users WHERE email = ? AND password = ?";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, email);
preparedStatement.setString(2, password);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
user = new User();
user.name = resultSet.getString("name");
user.email = resultSet.getString("email");
user.phone = resultSet.getString("phone");
user.address = resultSet.getString("address");
user.password = resultSet.getString("password");
}
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
public static void main(String[] args) {
Login login = new Login(null); //dlaczego null
User user = login.user;
if (user != null) {
System.out.println("Zalogowano użytkownika: " + user.name);
System.out.println("Email: " + user.email);
System.out.println("Telefon: " + user.phone);
System.out.println("Adres: " + user.address);
} else {
System.out.println("Niepoprawne dane logowania!");
}
//NIE DZIAŁA POPRAWNIE
}
}
| null |
9594_2 | PolanieOnLine/PolanieOnLine | 4,040 | src/games/stendhal/server/maps/quests/CzekoladaNikodema.java | /***************************************************************************
* (C) Copyright 2003-2021 - Stendhal *
***************************************************************************
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
package games.stendhal.server.maps.quests;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import games.stendhal.server.entity.npc.ChatAction;
import games.stendhal.server.entity.npc.ConversationPhrases;
import games.stendhal.server.entity.npc.ConversationStates;
import games.stendhal.server.entity.npc.SpeakerNPC;
import games.stendhal.server.entity.npc.action.DecreaseKarmaAction;
import games.stendhal.server.entity.npc.action.DropItemAction;
import games.stendhal.server.entity.npc.action.IncreaseKarmaAction;
import games.stendhal.server.entity.npc.action.IncreaseXPAction;
import games.stendhal.server.entity.npc.action.InflictStatusOnNPCAction;
import games.stendhal.server.entity.npc.action.MultipleActions;
import games.stendhal.server.entity.npc.action.SetQuestAction;
import games.stendhal.server.entity.npc.action.SetQuestAndModifyKarmaAction;
import games.stendhal.server.entity.npc.action.SetQuestToTimeStampAction;
import games.stendhal.server.entity.npc.condition.AndCondition;
import games.stendhal.server.entity.npc.condition.GreetingMatchesNameCondition;
import games.stendhal.server.entity.npc.condition.NotCondition;
import games.stendhal.server.entity.npc.condition.PlayerHasItemWithHimCondition;
import games.stendhal.server.entity.npc.condition.QuestActiveCondition;
import games.stendhal.server.entity.npc.condition.QuestCompletedCondition;
import games.stendhal.server.entity.npc.condition.QuestInStateCondition;
import games.stendhal.server.entity.npc.condition.QuestNotInStateCondition;
import games.stendhal.server.entity.npc.condition.QuestNotStartedCondition;
import games.stendhal.server.entity.npc.condition.QuestStartedCondition;
import games.stendhal.server.entity.npc.condition.QuestStateStartsWithCondition;
import games.stendhal.server.entity.npc.condition.TimePassedCondition;
import games.stendhal.server.entity.player.Player;
import games.stendhal.server.maps.Region;
public class CzekoladaNikodema extends AbstractQuest {
private static final String QUEST_SLOT = "czekolada_nikodema";
private final SpeakerNPC npc = npcs.get("Nikodem");
/** The delay between repeating quests. */
private static final int REQUIRED_MINUTES = 90; // 1 godzina i 30 minut
private void chocolateStep() {
npc.add(ConversationStates.IDLE,
ConversationPhrases.GREETING_MESSAGES,
new AndCondition(new GreetingMatchesNameCondition(npc.getName()),
new QuestNotStartedCondition(QUEST_SLOT), new QuestNotInStateCondition(QUEST_SLOT, "rejected")),
ConversationStates.ATTENDING,
"Mam ochotę na trochę #'czekolady'.",
null);
npc.addReply(Arrays.asList("chocolate", "czekolada", "czekolady"), "Słyszałem, że czekolade można kupić w zakopiańskiej tawernie, ale jestem jeszcze za młody i to strasznie daleko jest...");
npc.add(ConversationStates.IDLE,
ConversationPhrases.GREETING_MESSAGES,
new AndCondition(new GreetingMatchesNameCondition(npc.getName()),
new QuestInStateCondition(QUEST_SLOT, "start"), new PlayerHasItemWithHimCondition("tabliczka czekolady")),
ConversationStates.QUESTION_1,
"Wspaniale! Ta tabliczka czekolady jest dla mnie?",
null);
npc.add(ConversationStates.IDLE,
ConversationPhrases.GREETING_MESSAGES,
new AndCondition(new GreetingMatchesNameCondition(npc.getName()),
new QuestInStateCondition(QUEST_SLOT, "start"), new NotCondition(new PlayerHasItemWithHimCondition("tabliczka czekolady"))),
ConversationStates.ATTENDING,
"Mam nadzieje, że ktoś mi przyniesie tabliczkę czekolady... :(",
null);
// player is in another state like eating
npc.add(ConversationStates.IDLE,
ConversationPhrases.GREETING_MESSAGES,
new AndCondition(new GreetingMatchesNameCondition(npc.getName()),
new QuestStartedCondition(QUEST_SLOT), new QuestNotInStateCondition(QUEST_SLOT, "start")),
ConversationStates.ATTENDING,
"Cześć.",
null);
// player rejected quest
npc.add(ConversationStates.IDLE,
ConversationPhrases.GREETING_MESSAGES,
new AndCondition(new GreetingMatchesNameCondition(npc.getName()),
new QuestInStateCondition(QUEST_SLOT, "rejected")),
ConversationStates.ATTENDING,
"Cześć.",
null);
// player asks about quest for first time (or rejected)
npc.add(ConversationStates.ATTENDING,
ConversationPhrases.QUEST_MESSAGES,
new QuestNotStartedCondition(QUEST_SLOT),
ConversationStates.QUEST_OFFERED,
"Chciałabym dostać tabliczkę czekolady. Chociaż jedną. Ciemno brązową lub słodką białą lub z posypką. Zdobędziesz jedną dla mnie?",
null);
// shouldn't happen
npc.add(ConversationStates.ATTENDING,
ConversationPhrases.QUEST_MESSAGES,
new QuestCompletedCondition(QUEST_SLOT),
ConversationStates.ATTENDING,
"Został mi jeszcze kawałek czekolady, którą mi przyniosłeś, dziękuję!",
null);
// player can repeat quest
npc.add(ConversationStates.ATTENDING,
ConversationPhrases.QUEST_MESSAGES,
new AndCondition(new QuestStateStartsWithCondition(QUEST_SLOT, "eating;"), new TimePassedCondition(QUEST_SLOT, 1, REQUIRED_MINUTES)),
ConversationStates.QUEST_OFFERED,
"Mam nadzieję, że jeżeli poproszę o następną tabliczkę czekolady to nie będę zbyt zachłanny. Czy mógłbyś zdobyć następną?",
null);
// player can't repeat quest
npc.add(ConversationStates.ATTENDING,
ConversationPhrases.QUEST_MESSAGES,
new AndCondition(new QuestStateStartsWithCondition(QUEST_SLOT, "eating;"), new NotCondition(new TimePassedCondition(QUEST_SLOT, 1, REQUIRED_MINUTES))),
ConversationStates.ATTENDING,
"Zjadłem za dużo czekolady. Nie czuję się dobrze.",
null);
// player should be bringing chocolate not asking about the quest
npc.add(ConversationStates.ATTENDING,
ConversationPhrases.QUEST_MESSAGES,
new AndCondition(new QuestActiveCondition(QUEST_SLOT), new NotCondition(new QuestStateStartsWithCondition(QUEST_SLOT, "eating;"))),
ConversationStates.ATTENDING,
"Łaaaaaaaa! Gdzie jest moja czekolada ...",
null);
// Player agrees to get the chocolate
npc.add(ConversationStates.QUEST_OFFERED,
ConversationPhrases.YES_MESSAGES,
null,
ConversationStates.ATTENDING,
"Dziękuję!",
new SetQuestAndModifyKarmaAction(QUEST_SLOT, "start", 10.0));
// Player says no, they've lost karma
npc.add(ConversationStates.QUEST_OFFERED,
ConversationPhrases.NO_MESSAGES,
null,
ConversationStates.IDLE,
"Dobrze, może poproszę mame, aby mi kupiła tabliczkę czekolady...",
new SetQuestAndModifyKarmaAction(QUEST_SLOT, "rejected", -5.0));
// Player has got chocolate bar and spoken to mummy
final List<ChatAction> reward = new LinkedList<ChatAction>();
reward.add(new DropItemAction("tabliczka czekolady"));
reward.add(new IncreaseXPAction(500));
reward.add(new SetQuestAction(QUEST_SLOT, "eating;"));
reward.add(new SetQuestToTimeStampAction(QUEST_SLOT,1));
reward.add(new IncreaseKarmaAction(10.0));
reward.add(new InflictStatusOnNPCAction("tabliczka czekolady"));
npc.add(ConversationStates.QUESTION_1,
ConversationPhrases.YES_MESSAGES,
new PlayerHasItemWithHimCondition("tabliczka czekolady"),
ConversationStates.ATTENDING,
"Dziękuję BARDZO! Jesteś świetny.",
new MultipleActions(reward));
// player did have chocolate but put it on ground after question?
npc.add(ConversationStates.QUESTION_1,
ConversationPhrases.YES_MESSAGES,
new NotCondition(new PlayerHasItemWithHimCondition("tabliczka czekolady")),
ConversationStates.ATTENDING,
"Hej gdzie jest moja czekolada?!",
null);
// Player says no, they've lost karma
npc.add(ConversationStates.QUESTION_1,
ConversationPhrases.NO_MESSAGES,
null,
ConversationStates.IDLE,
"Łaaaaaa! Jesteś wielkim tłuściochem.",
new DecreaseKarmaAction(5.0));
}
@Override
public void addToWorld() {
fillQuestInfo(
"Czekolada dla Nikodema",
"Słodka, słodka czekolada! Nikt nie może bez niej żyć! A Nikodem chciałby ją mieć...",
true);
chocolateStep();
}
@Override
public List<String> getHistory(final Player player) {
final List<String> res = new ArrayList<String>();
if (!player.hasQuest(QUEST_SLOT)) {
return res;
}
res.add("Nikodem jest dobrym chłopcem, który bawi się z przyjaciółmi.");
final String questState = player.getQuest(QUEST_SLOT);
if ("rejected".equals(questState)) {
res.add("Nie będę przynosił mu czekolady.");
}
if (player.isQuestInState(QUEST_SLOT, "start") || isCompleted(player)) {
res.add("Nikodem chce dostać tabliczkę czekolady.");
}
if (player.isQuestInState(QUEST_SLOT, "start") && player.isEquipped("tabliczka czekolady") || isCompleted(player)) {
res.add(player.getGenderVerb("Znalazłem") + " pyszną tabliczkę czekolady dla Nikodema.");
}
if (isCompleted(player)) {
if (isRepeatable(player)) {
res.add(player.getGenderVerb("Przyniosłem") + " trochę czekolady dla Nikodema. Może chciałby więcej czekolady.");
} else {
res.add("Nikodem je czekoladę, którą mu dałem.");
}
}
return res;
}
@Override
public String getName() {
return "Czekolada Nikodema";
}
@Override
public String getRegion() {
return Region.KRAKOW_CITY;
}
@Override
public String getNPCName() {
return npc.getName();
}
@Override
public String getSlotName() {
return QUEST_SLOT;
}
@Override
public boolean isRepeatable(final Player player) {
return new AndCondition(new QuestStateStartsWithCondition(QUEST_SLOT,"eating;"),
new TimePassedCondition(QUEST_SLOT, 1, REQUIRED_MINUTES)).fire(player,null, null);
}
@Override
public boolean isCompleted(final Player player) {
return new QuestStateStartsWithCondition(QUEST_SLOT,"eating;").fire(player, null, null);
}
}
| // 1 godzina i 30 minut | /***************************************************************************
* (C) Copyright 2003-2021 - Stendhal *
***************************************************************************
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
package games.stendhal.server.maps.quests;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import games.stendhal.server.entity.npc.ChatAction;
import games.stendhal.server.entity.npc.ConversationPhrases;
import games.stendhal.server.entity.npc.ConversationStates;
import games.stendhal.server.entity.npc.SpeakerNPC;
import games.stendhal.server.entity.npc.action.DecreaseKarmaAction;
import games.stendhal.server.entity.npc.action.DropItemAction;
import games.stendhal.server.entity.npc.action.IncreaseKarmaAction;
import games.stendhal.server.entity.npc.action.IncreaseXPAction;
import games.stendhal.server.entity.npc.action.InflictStatusOnNPCAction;
import games.stendhal.server.entity.npc.action.MultipleActions;
import games.stendhal.server.entity.npc.action.SetQuestAction;
import games.stendhal.server.entity.npc.action.SetQuestAndModifyKarmaAction;
import games.stendhal.server.entity.npc.action.SetQuestToTimeStampAction;
import games.stendhal.server.entity.npc.condition.AndCondition;
import games.stendhal.server.entity.npc.condition.GreetingMatchesNameCondition;
import games.stendhal.server.entity.npc.condition.NotCondition;
import games.stendhal.server.entity.npc.condition.PlayerHasItemWithHimCondition;
import games.stendhal.server.entity.npc.condition.QuestActiveCondition;
import games.stendhal.server.entity.npc.condition.QuestCompletedCondition;
import games.stendhal.server.entity.npc.condition.QuestInStateCondition;
import games.stendhal.server.entity.npc.condition.QuestNotInStateCondition;
import games.stendhal.server.entity.npc.condition.QuestNotStartedCondition;
import games.stendhal.server.entity.npc.condition.QuestStartedCondition;
import games.stendhal.server.entity.npc.condition.QuestStateStartsWithCondition;
import games.stendhal.server.entity.npc.condition.TimePassedCondition;
import games.stendhal.server.entity.player.Player;
import games.stendhal.server.maps.Region;
public class CzekoladaNikodema extends AbstractQuest {
private static final String QUEST_SLOT = "czekolada_nikodema";
private final SpeakerNPC npc = npcs.get("Nikodem");
/** The delay between repeating quests. */
private static final int REQUIRED_MINUTES = 90; // 1 godzina <SUF>
private void chocolateStep() {
npc.add(ConversationStates.IDLE,
ConversationPhrases.GREETING_MESSAGES,
new AndCondition(new GreetingMatchesNameCondition(npc.getName()),
new QuestNotStartedCondition(QUEST_SLOT), new QuestNotInStateCondition(QUEST_SLOT, "rejected")),
ConversationStates.ATTENDING,
"Mam ochotę na trochę #'czekolady'.",
null);
npc.addReply(Arrays.asList("chocolate", "czekolada", "czekolady"), "Słyszałem, że czekolade można kupić w zakopiańskiej tawernie, ale jestem jeszcze za młody i to strasznie daleko jest...");
npc.add(ConversationStates.IDLE,
ConversationPhrases.GREETING_MESSAGES,
new AndCondition(new GreetingMatchesNameCondition(npc.getName()),
new QuestInStateCondition(QUEST_SLOT, "start"), new PlayerHasItemWithHimCondition("tabliczka czekolady")),
ConversationStates.QUESTION_1,
"Wspaniale! Ta tabliczka czekolady jest dla mnie?",
null);
npc.add(ConversationStates.IDLE,
ConversationPhrases.GREETING_MESSAGES,
new AndCondition(new GreetingMatchesNameCondition(npc.getName()),
new QuestInStateCondition(QUEST_SLOT, "start"), new NotCondition(new PlayerHasItemWithHimCondition("tabliczka czekolady"))),
ConversationStates.ATTENDING,
"Mam nadzieje, że ktoś mi przyniesie tabliczkę czekolady... :(",
null);
// player is in another state like eating
npc.add(ConversationStates.IDLE,
ConversationPhrases.GREETING_MESSAGES,
new AndCondition(new GreetingMatchesNameCondition(npc.getName()),
new QuestStartedCondition(QUEST_SLOT), new QuestNotInStateCondition(QUEST_SLOT, "start")),
ConversationStates.ATTENDING,
"Cześć.",
null);
// player rejected quest
npc.add(ConversationStates.IDLE,
ConversationPhrases.GREETING_MESSAGES,
new AndCondition(new GreetingMatchesNameCondition(npc.getName()),
new QuestInStateCondition(QUEST_SLOT, "rejected")),
ConversationStates.ATTENDING,
"Cześć.",
null);
// player asks about quest for first time (or rejected)
npc.add(ConversationStates.ATTENDING,
ConversationPhrases.QUEST_MESSAGES,
new QuestNotStartedCondition(QUEST_SLOT),
ConversationStates.QUEST_OFFERED,
"Chciałabym dostać tabliczkę czekolady. Chociaż jedną. Ciemno brązową lub słodką białą lub z posypką. Zdobędziesz jedną dla mnie?",
null);
// shouldn't happen
npc.add(ConversationStates.ATTENDING,
ConversationPhrases.QUEST_MESSAGES,
new QuestCompletedCondition(QUEST_SLOT),
ConversationStates.ATTENDING,
"Został mi jeszcze kawałek czekolady, którą mi przyniosłeś, dziękuję!",
null);
// player can repeat quest
npc.add(ConversationStates.ATTENDING,
ConversationPhrases.QUEST_MESSAGES,
new AndCondition(new QuestStateStartsWithCondition(QUEST_SLOT, "eating;"), new TimePassedCondition(QUEST_SLOT, 1, REQUIRED_MINUTES)),
ConversationStates.QUEST_OFFERED,
"Mam nadzieję, że jeżeli poproszę o następną tabliczkę czekolady to nie będę zbyt zachłanny. Czy mógłbyś zdobyć następną?",
null);
// player can't repeat quest
npc.add(ConversationStates.ATTENDING,
ConversationPhrases.QUEST_MESSAGES,
new AndCondition(new QuestStateStartsWithCondition(QUEST_SLOT, "eating;"), new NotCondition(new TimePassedCondition(QUEST_SLOT, 1, REQUIRED_MINUTES))),
ConversationStates.ATTENDING,
"Zjadłem za dużo czekolady. Nie czuję się dobrze.",
null);
// player should be bringing chocolate not asking about the quest
npc.add(ConversationStates.ATTENDING,
ConversationPhrases.QUEST_MESSAGES,
new AndCondition(new QuestActiveCondition(QUEST_SLOT), new NotCondition(new QuestStateStartsWithCondition(QUEST_SLOT, "eating;"))),
ConversationStates.ATTENDING,
"Łaaaaaaaa! Gdzie jest moja czekolada ...",
null);
// Player agrees to get the chocolate
npc.add(ConversationStates.QUEST_OFFERED,
ConversationPhrases.YES_MESSAGES,
null,
ConversationStates.ATTENDING,
"Dziękuję!",
new SetQuestAndModifyKarmaAction(QUEST_SLOT, "start", 10.0));
// Player says no, they've lost karma
npc.add(ConversationStates.QUEST_OFFERED,
ConversationPhrases.NO_MESSAGES,
null,
ConversationStates.IDLE,
"Dobrze, może poproszę mame, aby mi kupiła tabliczkę czekolady...",
new SetQuestAndModifyKarmaAction(QUEST_SLOT, "rejected", -5.0));
// Player has got chocolate bar and spoken to mummy
final List<ChatAction> reward = new LinkedList<ChatAction>();
reward.add(new DropItemAction("tabliczka czekolady"));
reward.add(new IncreaseXPAction(500));
reward.add(new SetQuestAction(QUEST_SLOT, "eating;"));
reward.add(new SetQuestToTimeStampAction(QUEST_SLOT,1));
reward.add(new IncreaseKarmaAction(10.0));
reward.add(new InflictStatusOnNPCAction("tabliczka czekolady"));
npc.add(ConversationStates.QUESTION_1,
ConversationPhrases.YES_MESSAGES,
new PlayerHasItemWithHimCondition("tabliczka czekolady"),
ConversationStates.ATTENDING,
"Dziękuję BARDZO! Jesteś świetny.",
new MultipleActions(reward));
// player did have chocolate but put it on ground after question?
npc.add(ConversationStates.QUESTION_1,
ConversationPhrases.YES_MESSAGES,
new NotCondition(new PlayerHasItemWithHimCondition("tabliczka czekolady")),
ConversationStates.ATTENDING,
"Hej gdzie jest moja czekolada?!",
null);
// Player says no, they've lost karma
npc.add(ConversationStates.QUESTION_1,
ConversationPhrases.NO_MESSAGES,
null,
ConversationStates.IDLE,
"Łaaaaaa! Jesteś wielkim tłuściochem.",
new DecreaseKarmaAction(5.0));
}
@Override
public void addToWorld() {
fillQuestInfo(
"Czekolada dla Nikodema",
"Słodka, słodka czekolada! Nikt nie może bez niej żyć! A Nikodem chciałby ją mieć...",
true);
chocolateStep();
}
@Override
public List<String> getHistory(final Player player) {
final List<String> res = new ArrayList<String>();
if (!player.hasQuest(QUEST_SLOT)) {
return res;
}
res.add("Nikodem jest dobrym chłopcem, który bawi się z przyjaciółmi.");
final String questState = player.getQuest(QUEST_SLOT);
if ("rejected".equals(questState)) {
res.add("Nie będę przynosił mu czekolady.");
}
if (player.isQuestInState(QUEST_SLOT, "start") || isCompleted(player)) {
res.add("Nikodem chce dostać tabliczkę czekolady.");
}
if (player.isQuestInState(QUEST_SLOT, "start") && player.isEquipped("tabliczka czekolady") || isCompleted(player)) {
res.add(player.getGenderVerb("Znalazłem") + " pyszną tabliczkę czekolady dla Nikodema.");
}
if (isCompleted(player)) {
if (isRepeatable(player)) {
res.add(player.getGenderVerb("Przyniosłem") + " trochę czekolady dla Nikodema. Może chciałby więcej czekolady.");
} else {
res.add("Nikodem je czekoladę, którą mu dałem.");
}
}
return res;
}
@Override
public String getName() {
return "Czekolada Nikodema";
}
@Override
public String getRegion() {
return Region.KRAKOW_CITY;
}
@Override
public String getNPCName() {
return npc.getName();
}
@Override
public String getSlotName() {
return QUEST_SLOT;
}
@Override
public boolean isRepeatable(final Player player) {
return new AndCondition(new QuestStateStartsWithCondition(QUEST_SLOT,"eating;"),
new TimePassedCondition(QUEST_SLOT, 1, REQUIRED_MINUTES)).fire(player,null, null);
}
@Override
public boolean isCompleted(final Player player) {
return new QuestStateStartsWithCondition(QUEST_SLOT,"eating;").fire(player, null, null);
}
}
| null |
10259_35 | PrzemekBarczyk/swing-kalkulator | 6,663 | src/CalculatorModel.java | import java.awt.Color;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import javax.swing.JButton;
public class CalculatorModel {
private String operationLabelText; // zawartość JLabel z zapisem przeprowadzonych operacji
private String resultLabelText; // zawartość JLabel z aktualnie wprowadzoną wartością/wynikiem
private double previousNumber; // poprzednio podana wartość
private double lastNumber; // ostatnio podana wartość
private String lastOperationSign; // znak ostatniej operacji
private String stringBuff; // zmienna do przechowywania ciągów znakowych
private boolean choseNumber; // wpisano liczbę do resultLabelText
private boolean choseDot; // we wpisanej liczbie użytko przecinka
private boolean choseDyadicOperation; // wybrano jedną z operacji dwuargumentowych
private boolean chosePowOrSqlt; // wybrano operację potęgowania lub pierwiastkowania
private boolean chosePercent; // wybrano oprarację liczenia procentu
private boolean choseFraction; // wybrano operację liczenia ułamka z podanej liczby
private boolean choseEqualSign; // wybrano operację wyświetlenia wyniku
private boolean dividedByZero; // doszło do dzielenia przez 0
private DecimalFormat formatForResultLabelText; // do usunięcia powtarzających się zer z przodu i końca oraz dodania odstępów
private DecimalFormat formatForOperationLabelText; // do usunięcia powtarzających się zer z przodu i z końca
private final int MAX_NUMBERS = 13; // maksymalna liczba cyfr jakie może mieć wpisywana liczba
/**
* Ustawia zmienne
*/
public CalculatorModel() {
previousNumber = 0;
lastNumber = 0;
operationLabelText = "";
resultLabelText = "0";
lastOperationSign = "";
choseNumber = false;
choseDot = false;
choseDyadicOperation = false;
chosePowOrSqlt = false;
chosePercent = false;
choseFraction = false;
choseEqualSign = false;
dividedByZero = false;
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
symbols.setGroupingSeparator(' ');
formatForResultLabelText = new DecimalFormat();
formatForResultLabelText.setDecimalFormatSymbols(symbols);
formatForResultLabelText.setGroupingUsed(true);
formatForResultLabelText.setMaximumIntegerDigits(MAX_NUMBERS);
formatForResultLabelText.setMaximumFractionDigits(MAX_NUMBERS);
formatForOperationLabelText = new DecimalFormat();
formatForOperationLabelText.setDecimalFormatSymbols(symbols);
formatForOperationLabelText.setGroupingUsed(false);
formatForOperationLabelText.setMaximumIntegerDigits(MAX_NUMBERS);
formatForOperationLabelText.setMaximumFractionDigits(MAX_NUMBERS);
}
/**
* Obsługuje zdarzenie wywołane wyborem dowolnej z cyfr lub przecinka
*
* Zmienia wartość resultLabelText w przypadku podania cyfry lub przecinka. Może również wyczyścić
* operationLabelText w przypadku gdy użyto equalsButton.
*
* Metoda posiada zabezpieczenia przed sytuacjami takimi jak gdy nastąpiło dzielenie przez 0, użycie przycisku
* equalsButton, podanie pierwszej cyfry oraz podanie za dużej ilości cyfr.
*
* Następnie w zależności czy wybrano dowolną z cyfr czy przecinek wykonywane są instrukcję modyfikujące
* resultLabelText.
*/
public void handleNumbers(String number) {
// zabezpieczenia przed różnymi sytuacjami
if (!number.equals(".") && dividedByZero) { // dzielenie przez 0 i wybrano cyfrę
handleClear();
dividedByZero = false;
}
else if (number.equals(".") && dividedByZero) { // dzielenie przez 0 i wybrano przecinek
return;
}
if (!choseNumber && !choseDot && !choseDyadicOperation && !choseEqualSign) { // wybrano pierwszą cyfrę lub przecinek []||[2+]||[2-3+]||[2=]
resultLabelText = "0";
}
else if (!choseNumber && !choseDot) { // użyto equalsButton i wybrano pierwszą cyfrę lub przecinek [2+3=]||[2+3-4=]
resultLabelText = "0";
operationLabelText = "";
}
else if (resultLabelText.length() > MAX_NUMBERS) { // blokada przed wpisaniem bardzo dużej liczby
return;
}
// modyfikacja resultLabelText i flag
if (!number.equals(".")) { // cyfra
resultLabelText = resultLabelText + number;
resultLabelText = formatWithSpacing(resultLabelText);
choseNumber = true;
}
else if (!choseDot) { // przecinek (wybrany po raz pierwszy)
resultLabelText = resultLabelText + number;
choseDot = true;
}
}
/**
* Obsługuje zdarzenie wywołane wyborem operacji dwuargumentowej
*
* Zapisuje podaną wartość wraz z wybranym znakiem operacji w operationLabelText. W przypadku wybrania drugiej i
* każdej kolejnej operacji bez wybrania equalsButton zapisuje wynik w resultLabelText.
*
* Metoda posiada zabezpieczenia przed sytuacjami takimi jak gdy nastąpiło dzielenie przez 0, wybór znaku operacji
* kilka razy pod rząd, użycie przycisku equalsButton i nie podanie nowej wartości przed wyborem znaku. użycie
* nie typowej operacji lub zwykłej.
*
* Następnie w zależności czy wybrano operację jednoargumentową czy dwuargumentową modyfikowane jest
* operationLabelText. Ponadto, jeśli wybrana operacja jest drugą lub kolejną wybraną bez wybrania equalsButton
* wyznaczany jest nowy wynik.
*/
public void handleDyadicOperation(String sign) {
lastOperationSign = sign;
// zabezpieczenie przed różnymi sytuacjami
if (dividedByZero) { // zablokowanie operacji po dzieleniu przez zero
return;
}
if (choseDyadicOperation && !choseNumber && !choseEqualSign && !chosePowOrSqlt) { // wybrano kolejny znak pod rząd [2+][2+3-]
swapSignNumber(lastOperationSign); // nadpisuje poprzedni znak nowym
return; // nie trzeba ustawiać flag, bo zostały już ustawione dla poprzedniego znaku
}
if (choseEqualSign && !choseNumber) { // użyto equalsButton i nie podano liczby [=]||[2=]||[2+3=]
operationLabelText = "";
}
// modyfikacja operationLabelText
if (chosePowOrSqlt || chosePercent || choseFraction) { // wybrano operację jednoargumentową [sqrt(2)][2+sqrt(3)]
operationLabelText = operationLabelText + " " + lastOperationSign + " ";
}
else { // wybrano operację dwuargumentową
operationLabelText = operationLabelText + formatWithoutSpacing(resultLabelText) + " " + lastOperationSign + " ";
}
// modyfikacja resultLabelText
if (choseDyadicOperation && (choseNumber || chosePowOrSqlt || chosePercent || choseFraction) && !choseEqualSign) { // wybrano operację dwuargumentową kolejny raz bez wyboru = [2+3]
lastNumber = deleteSpacesAndConvertToDouble(resultLabelText);
executeDyadicOperation(); // wyznacza nowy resultLabelText
}
if (!dividedByZero)
resultLabelText = formatWithSpacing(resultLabelText); // nowa wartość
previousNumber = deleteSpacesAndConvertToDouble(resultLabelText);
choseNumber = false;
choseDot = false;
choseDyadicOperation = true;
chosePowOrSqlt = false;
chosePercent = false;
choseFraction = false;
choseEqualSign = false;
}
/**
* Wykonuje operację dwuargumentową na podstawie ostatnio użytego znaku
*
* Modyfikuję wartość resultLabelText przy użyciu zmiennych previousNumber i lastNumber.
*/
private void executeDyadicOperation() {
switch (lastOperationSign) {
case "+":
resultLabelText = convertToString(previousNumber + lastNumber);
break;
case "-":
resultLabelText = convertToString(previousNumber - lastNumber);
break;
case "×":
resultLabelText = convertToString(previousNumber * lastNumber);
break;
case "÷":
if (lastNumber != 0) { // zabezpieczenie przed dzieleniem przez 0
resultLabelText = convertToString(previousNumber / lastNumber);
}
else {
resultLabelText = "Cannot divide by zero";
dividedByZero = true;
}
break;
default:
System.out.println("Nieznana operacja!");
}
}
/**
* Obsługuje zdarzenie wywołane wyborem operacji potęgowania lub pierwiastkowania
*
* Modyfikuję operationLabelText w różny sposób w zależności od tego czy operacja była wywołana pierwszy czy kolejny
* raz pod rząd.
*
* Metoda posiada zabezpieczenie przed sytuacją gdy nastąpiło dzielenie przez 0.
*/
public void handlePowerAndSqrt(String sign) {
if (dividedByZero) { // zablokowanie operacji po dzieleniu przez zero
return;
}
// modyfikacja operationLabelText
if (!chosePowOrSqlt) { // pierwszy pod rząd wybór tej operacji
stringBuff = sign + "(" + formatWithoutSpacing(resultLabelText) + ")";
operationLabelText = operationLabelText + stringBuff;
}
else { // kolejny
String reversedBuff = new StringBuilder(stringBuff).reverse().toString();
reversedBuff = reversedBuff.replace(")", "\\)");
reversedBuff = reversedBuff.replace("(", "\\(");
stringBuff = sign + "(" + stringBuff + ")";
operationLabelText = new StringBuilder(operationLabelText).reverse().toString().replaceFirst(reversedBuff, ")" + reversedBuff + "(" + new StringBuilder(sign).reverse().toString());
operationLabelText = new StringBuilder(operationLabelText).reverse().toString();
}
// modyfikacja resultLabelText
executeUnaryOperation(sign);
if (!dividedByZero)
resultLabelText = formatWithSpacing(resultLabelText);
choseNumber = false;
choseDot = false;
chosePowOrSqlt = true;
}
/**
* Obsługuje zdarzenie wywołane wyborem operacji wyznaczania procentu
*
* Modyfikuję operationLabelText w różny sposób w zależności od tego czy operacja była wywołana pierwszy czy kolejny
* raz pod rząd.
*
* Metoda posiada zabezpieczenie przed sytuacją gdy nastąpiło dzielenie przez 0.
*/
public void handlePercent() {
if (dividedByZero) { // zablokowanie operacji po dzieleniu przez zero
return;
}
// modyfikacja operationLabelText i resultLabelText
if (!chosePercent) { // pierwszy pod rząd wybór tej operacji
executeUnaryOperation("%");
operationLabelText = operationLabelText + formatWithoutSpacing(resultLabelText);
}
else { // kolejny
String oldResult = formatWithoutSpacing(resultLabelText);
executeUnaryOperation("%");
String reversedOldResult = new StringBuilder(oldResult).reverse().toString();
operationLabelText = new StringBuilder(operationLabelText).reverse().toString().replaceFirst(reversedOldResult, new StringBuilder(resultLabelText).reverse().toString());
operationLabelText = new StringBuilder(operationLabelText).reverse().toString();
}
if (!dividedByZero)
resultLabelText = formatWithSpacing(resultLabelText);
choseNumber = false;
choseDot = false;
chosePercent = true;
}
/**
* Obsługuje zdarzenie wywołane wyborem operacji wyznaczania ułamka
*
* Modyfikuję operationLabelText w różny sposób w zależności od tego czy operacja była wywołana pierwszy czy kolejny
* raz pod rząd.
*
* Metoda posiada zabezpieczenie przed sytuacją gdy nastąpiło dzielenie przez 0.
*/
public void handleFraction() {
if (dividedByZero) { // zablokowanie operacji po dzieleniu przez zero
return;
}
// modyfikacja operationLabelText
if (!choseFraction) { // pierwszy pod rząd wybór tej operacji
stringBuff = "1/( " + formatWithoutSpacing(resultLabelText) + " )";
operationLabelText = operationLabelText + stringBuff;
}
else { // kolejny
String reversedBuff = new StringBuilder(stringBuff).reverse().toString();
reversedBuff = reversedBuff.replace(")", "\\)");
reversedBuff = reversedBuff.replace("(", "\\(");
stringBuff = "1/" + "( " + stringBuff + " )";
operationLabelText = new StringBuilder(operationLabelText).reverse().toString().replaceFirst(reversedBuff, ") " + reversedBuff + " (" + new StringBuilder("1/").reverse().toString());
operationLabelText = new StringBuilder(operationLabelText).reverse().toString();
}
// modyfikacja resultLabelText
executeUnaryOperation("1/");
if (!dividedByZero)
resultLabelText = formatWithSpacing(resultLabelText);
choseNumber = false;
choseDot = false;
choseFraction = true;
}
/**
* Wykonuje operację jednoargumentową na podstawie otrzymanego znaku
*
* Modyfikuję wartość resultLabelText przy użyciu odpowiedniego działania na resultLabelText.
*/
private void executeUnaryOperation(String sign) {
switch(sign) {
case "sqrt":
resultLabelText = convertToString(convertToDouble(resultLabelText) * convertToDouble(resultLabelText));
break;
case "√":
resultLabelText = convertToString(Math.sqrt(convertToDouble(resultLabelText)));
break;
case "1/":
if (deleteSpacesAndConvertToDouble(resultLabelText) != 0) { // zabezpieczenie przed dzieleniem przez 0
resultLabelText = convertToString(1 / convertToDouble(resultLabelText));
}
else {
resultLabelText = "Cannot divide by zero";
dividedByZero = true;
}
break;
case "%":
resultLabelText = convertToString(convertToDouble(resultLabelText) / 100 * previousNumber);
break;
default:
System.out.println("Nieznana operacja!");
}
}
/**
* Obsługuje zdarzenie wywołane wyborem znaku =
*
* Modyfikuje operationLabelText oraz wyznacza nową wartość resultLabelText przy użyciu wartości zmiennych
* previousNumber i lastNumber.
*
* Metoda posiada zabezpieczenie przed sytuacją gdy nastąpiło dzielenie przez 0.
*
* Następnie podejmowane są kroki w przypadku gdy metoda została wywołana bez wyboru operacji dwuargumentowej.
* Polegają one na modyfikacji operationLabelText i zakończeniu wykonywania metody ponieważ resultLabelText nie
* może być w takiej sytuacji modyfikowany. W przypadku gdy metoda została wywołana z wybraną operacją
* dwuargumentową modyfikowany jest operationLabelText, wykonywana jest wybrana operacja oraz wyświetlana jest
* nowa wartość resultLabelText.
*/
public void handleEqualSign() {
// zabezpieczenie przed różnymi sytuacjami
if (dividedByZero) { // zablokowanie operacji po dzieleniu przez zero
handleClear();
return;
}
// modyfikacja operationLabelText przy braku wyboru operacji dwuargumentowej
if (!choseDyadicOperation && !chosePowOrSqlt && !chosePercent && !choseFraction) { // nie wybrano znaku i operacji jednoargumentowej []||[=]||[2]||[2=]
operationLabelText = formatWithoutSpacing(resultLabelText) + " = ";
choseNumber = false;
choseDot = false;
choseEqualSign = true;
return;
}
if (!choseDyadicOperation) { // nie wybrano znaku i wybrano operację jednoargumentową
operationLabelText = operationLabelText + " = ";
choseNumber = false;
choseDot = false;
choseEqualSign = true;
chosePowOrSqlt = false;
chosePercent = false;
choseFraction = false;
return;
}
// modyfikacja operationLabelText po wyborze operacji dwuargumentowej
// choseOperationSign == True zawsze w tym miejscu
if (choseEqualSign) { // wybrano znak i = kolejny raz pod rząd [2+=]||[2+3=]||[2+3==]
previousNumber = deleteSpacesAndConvertToDouble(resultLabelText);
operationLabelText = formatWithoutSpacing(resultLabelText) + " " + lastOperationSign + " " + formatWithoutSpacing(convertToString(lastNumber)) + " = ";
}
else if (!choseNumber && !chosePowOrSqlt && !chosePercent && !choseFraction) { // wybrano znak i nie wybrano drugiej liczby [+]||[2+]
lastNumber = deleteSpacesAndConvertToDouble(resultLabelText);
operationLabelText = operationLabelText + formatWithoutSpacing(resultLabelText) + " = ";
}
else if (chosePowOrSqlt || chosePercent || choseFraction) { // wybrano znak i operację jednoargumentową [2+sqrt(3)]
lastNumber = deleteSpacesAndConvertToDouble(resultLabelText);
operationLabelText = operationLabelText + " = ";
}
else { // wybrano znak i cyfre [2+3]
lastNumber = deleteSpacesAndConvertToDouble(resultLabelText);
operationLabelText = operationLabelText + formatWithoutSpacing(convertToString(lastNumber)) + " = ";
}
// modyfikacja resultLabelText
executeDyadicOperation();
if (!dividedByZero)
resultLabelText = formatWithSpacing(resultLabelText);
choseNumber = false;
choseDot = false;
choseEqualSign = true;
chosePowOrSqlt = false;
chosePercent = false;
choseFraction = false;
}
/**
* Usuwa ostatni znak z resultLabelText
*
* Posiada trzy możliwe przebiegi w zależności czy ostatni znak to przecinek, cyfra oraz ostatnia cyfra.
*
* Metoda posiada zabezpieczenie przed sytuacją gdy nastąpiło dzielenie przez 0.
*/
public void handleBackspace() {
if (dividedByZero) { // zablokowanie operacji po dzieleniu przez zero
handleClear();
return;
}
if (resultLabelText.length() == 1) { // ostatnia cyfra
resultLabelText = "0";
}
else if (!resultLabelText.endsWith(".")) { // zwykła cyfra
resultLabelText = resultLabelText.substring(0, resultLabelText.length() - 1);
}
else { // przecinek
resultLabelText = resultLabelText.substring(0, resultLabelText.length() - 1);
choseDot = false;
}
}
/**
* Usuwa zawartość resultLabelText
*
* W przypadku użycia znaku "=" działa tak samo jak clear().
*
* Metoda posiada zabezpieczenie przed sytuacją gdy nastąpiło dzielenie przez 0.
*/
public void handleClearEntry() {
if (dividedByZero) { // zablokowanie operacji po dzieleniu przez zero
handleClear();
return;
}
if (!choseEqualSign) {
resultLabelText = "0";
choseNumber = false;
choseDot = false;
chosePowOrSqlt = false;
chosePercent = false;
choseFraction = false;
}
else {
handleClear();
}
}
/**
* Usuwa wszystkie wprowadzone dane i przywraca je do wartości początkowych
*/
public void handleClear() {
previousNumber = 0;
lastNumber = 0;
operationLabelText = "";
resultLabelText = "0";
lastOperationSign = "";
choseNumber = false;
choseDot = false;
choseDyadicOperation = false;
chosePowOrSqlt = false;
chosePercent = false;
choseFraction = false;
choseEqualSign = false;
}
/**
* Obsługuje zdarzenie wywołane wyborem przycisku zmiany znaku
*
* Zmienia znak liczby przechowywanej w resultLabel na przeciwny mnożąc jej wartość przez -1.
*
* Metoda posiada zabezpieczenie przed sytuacją gdy nastąpiło dzielenie przez 0.
*/
public void handleSignNegation() {
if (dividedByZero) { // zablokowanie operacji po dzieleniu przez zero
return;
}
if (!resultLabelText.equals("0"))
resultLabelText = formatWithSpacing(convertToString(-1 * deleteSpacesAndConvertToDouble(resultLabelText)));
}
/**
* Usuwa ostatni znak z operationLabelText i zamienia go na otrzymany w argumencie
*/
private void swapSignNumber(String sign) {
if (operationLabelText.length() > 0) {
operationLabelText = operationLabelText.substring(0, operationLabelText.length()-2) + sign + " ";
}
}
/**
* Konwertuje otrzymanego doubla do Stringa
*/
private String convertToString(double number) {
return String.valueOf(number);
}
/**
* Konwertuje otrzymanego Stringa do doubla
*/
private double convertToDouble(String number) {
return Double.parseDouble(number);
}
/**
* Usuwa spację z otrzymanego Stringa i konwertuję go do doubla
*/
private double deleteSpacesAndConvertToDouble(String number) {
return Double.parseDouble(number.replace(" ", "")); // " " ma nietypowe kodowanie;
}
/**
* Formatuje otrzymanego Stringa dodając spację co 3 cyfry
*
* Używa w tym celu klasy DecimalFormat
*/
private String formatWithSpacing(String number) {
return resultLabelText = formatForResultLabelText.format(deleteSpacesAndConvertToDouble(number));
}
/**
* Formatuje otrzymanego Stringa bez dodawania spacji
*
* Używa w tym celu klasy DecimalFormat
*/
private String formatWithoutSpacing(String number) {
return resultLabelText = formatForOperationLabelText.format(deleteSpacesAndConvertToDouble(number));
}
/**
* Zwraca zawartość zmiennej operationLabelText
*/
public String getOperationLabelText() {
return operationLabelText;
}
/**
* Zwraca zawartość zmiennej resultLabelText
*/
public String getResultLabelText() {
return resultLabelText;
}
/**
* Zmienia na chwilę kolor tła przesłanego przycisku
*/
public void highlightButton(JButton button, Color color) {
Color selectButtonColor = new Color(70,70,70);
button.setBackground(selectButtonColor);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
button.setBackground(color);
}
}
| // wybrano operację dwuargumentową | import java.awt.Color;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import javax.swing.JButton;
public class CalculatorModel {
private String operationLabelText; // zawartość JLabel z zapisem przeprowadzonych operacji
private String resultLabelText; // zawartość JLabel z aktualnie wprowadzoną wartością/wynikiem
private double previousNumber; // poprzednio podana wartość
private double lastNumber; // ostatnio podana wartość
private String lastOperationSign; // znak ostatniej operacji
private String stringBuff; // zmienna do przechowywania ciągów znakowych
private boolean choseNumber; // wpisano liczbę do resultLabelText
private boolean choseDot; // we wpisanej liczbie użytko przecinka
private boolean choseDyadicOperation; // wybrano jedną z operacji dwuargumentowych
private boolean chosePowOrSqlt; // wybrano operację potęgowania lub pierwiastkowania
private boolean chosePercent; // wybrano oprarację liczenia procentu
private boolean choseFraction; // wybrano operację liczenia ułamka z podanej liczby
private boolean choseEqualSign; // wybrano operację wyświetlenia wyniku
private boolean dividedByZero; // doszło do dzielenia przez 0
private DecimalFormat formatForResultLabelText; // do usunięcia powtarzających się zer z przodu i końca oraz dodania odstępów
private DecimalFormat formatForOperationLabelText; // do usunięcia powtarzających się zer z przodu i z końca
private final int MAX_NUMBERS = 13; // maksymalna liczba cyfr jakie może mieć wpisywana liczba
/**
* Ustawia zmienne
*/
public CalculatorModel() {
previousNumber = 0;
lastNumber = 0;
operationLabelText = "";
resultLabelText = "0";
lastOperationSign = "";
choseNumber = false;
choseDot = false;
choseDyadicOperation = false;
chosePowOrSqlt = false;
chosePercent = false;
choseFraction = false;
choseEqualSign = false;
dividedByZero = false;
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
symbols.setGroupingSeparator(' ');
formatForResultLabelText = new DecimalFormat();
formatForResultLabelText.setDecimalFormatSymbols(symbols);
formatForResultLabelText.setGroupingUsed(true);
formatForResultLabelText.setMaximumIntegerDigits(MAX_NUMBERS);
formatForResultLabelText.setMaximumFractionDigits(MAX_NUMBERS);
formatForOperationLabelText = new DecimalFormat();
formatForOperationLabelText.setDecimalFormatSymbols(symbols);
formatForOperationLabelText.setGroupingUsed(false);
formatForOperationLabelText.setMaximumIntegerDigits(MAX_NUMBERS);
formatForOperationLabelText.setMaximumFractionDigits(MAX_NUMBERS);
}
/**
* Obsługuje zdarzenie wywołane wyborem dowolnej z cyfr lub przecinka
*
* Zmienia wartość resultLabelText w przypadku podania cyfry lub przecinka. Może również wyczyścić
* operationLabelText w przypadku gdy użyto equalsButton.
*
* Metoda posiada zabezpieczenia przed sytuacjami takimi jak gdy nastąpiło dzielenie przez 0, użycie przycisku
* equalsButton, podanie pierwszej cyfry oraz podanie za dużej ilości cyfr.
*
* Następnie w zależności czy wybrano dowolną z cyfr czy przecinek wykonywane są instrukcję modyfikujące
* resultLabelText.
*/
public void handleNumbers(String number) {
// zabezpieczenia przed różnymi sytuacjami
if (!number.equals(".") && dividedByZero) { // dzielenie przez 0 i wybrano cyfrę
handleClear();
dividedByZero = false;
}
else if (number.equals(".") && dividedByZero) { // dzielenie przez 0 i wybrano przecinek
return;
}
if (!choseNumber && !choseDot && !choseDyadicOperation && !choseEqualSign) { // wybrano pierwszą cyfrę lub przecinek []||[2+]||[2-3+]||[2=]
resultLabelText = "0";
}
else if (!choseNumber && !choseDot) { // użyto equalsButton i wybrano pierwszą cyfrę lub przecinek [2+3=]||[2+3-4=]
resultLabelText = "0";
operationLabelText = "";
}
else if (resultLabelText.length() > MAX_NUMBERS) { // blokada przed wpisaniem bardzo dużej liczby
return;
}
// modyfikacja resultLabelText i flag
if (!number.equals(".")) { // cyfra
resultLabelText = resultLabelText + number;
resultLabelText = formatWithSpacing(resultLabelText);
choseNumber = true;
}
else if (!choseDot) { // przecinek (wybrany po raz pierwszy)
resultLabelText = resultLabelText + number;
choseDot = true;
}
}
/**
* Obsługuje zdarzenie wywołane wyborem operacji dwuargumentowej
*
* Zapisuje podaną wartość wraz z wybranym znakiem operacji w operationLabelText. W przypadku wybrania drugiej i
* każdej kolejnej operacji bez wybrania equalsButton zapisuje wynik w resultLabelText.
*
* Metoda posiada zabezpieczenia przed sytuacjami takimi jak gdy nastąpiło dzielenie przez 0, wybór znaku operacji
* kilka razy pod rząd, użycie przycisku equalsButton i nie podanie nowej wartości przed wyborem znaku. użycie
* nie typowej operacji lub zwykłej.
*
* Następnie w zależności czy wybrano operację jednoargumentową czy dwuargumentową modyfikowane jest
* operationLabelText. Ponadto, jeśli wybrana operacja jest drugą lub kolejną wybraną bez wybrania equalsButton
* wyznaczany jest nowy wynik.
*/
public void handleDyadicOperation(String sign) {
lastOperationSign = sign;
// zabezpieczenie przed różnymi sytuacjami
if (dividedByZero) { // zablokowanie operacji po dzieleniu przez zero
return;
}
if (choseDyadicOperation && !choseNumber && !choseEqualSign && !chosePowOrSqlt) { // wybrano kolejny znak pod rząd [2+][2+3-]
swapSignNumber(lastOperationSign); // nadpisuje poprzedni znak nowym
return; // nie trzeba ustawiać flag, bo zostały już ustawione dla poprzedniego znaku
}
if (choseEqualSign && !choseNumber) { // użyto equalsButton i nie podano liczby [=]||[2=]||[2+3=]
operationLabelText = "";
}
// modyfikacja operationLabelText
if (chosePowOrSqlt || chosePercent || choseFraction) { // wybrano operację jednoargumentową [sqrt(2)][2+sqrt(3)]
operationLabelText = operationLabelText + " " + lastOperationSign + " ";
}
else { // wybrano operację <SUF>
operationLabelText = operationLabelText + formatWithoutSpacing(resultLabelText) + " " + lastOperationSign + " ";
}
// modyfikacja resultLabelText
if (choseDyadicOperation && (choseNumber || chosePowOrSqlt || chosePercent || choseFraction) && !choseEqualSign) { // wybrano operację dwuargumentową kolejny raz bez wyboru = [2+3]
lastNumber = deleteSpacesAndConvertToDouble(resultLabelText);
executeDyadicOperation(); // wyznacza nowy resultLabelText
}
if (!dividedByZero)
resultLabelText = formatWithSpacing(resultLabelText); // nowa wartość
previousNumber = deleteSpacesAndConvertToDouble(resultLabelText);
choseNumber = false;
choseDot = false;
choseDyadicOperation = true;
chosePowOrSqlt = false;
chosePercent = false;
choseFraction = false;
choseEqualSign = false;
}
/**
* Wykonuje operację dwuargumentową na podstawie ostatnio użytego znaku
*
* Modyfikuję wartość resultLabelText przy użyciu zmiennych previousNumber i lastNumber.
*/
private void executeDyadicOperation() {
switch (lastOperationSign) {
case "+":
resultLabelText = convertToString(previousNumber + lastNumber);
break;
case "-":
resultLabelText = convertToString(previousNumber - lastNumber);
break;
case "×":
resultLabelText = convertToString(previousNumber * lastNumber);
break;
case "÷":
if (lastNumber != 0) { // zabezpieczenie przed dzieleniem przez 0
resultLabelText = convertToString(previousNumber / lastNumber);
}
else {
resultLabelText = "Cannot divide by zero";
dividedByZero = true;
}
break;
default:
System.out.println("Nieznana operacja!");
}
}
/**
* Obsługuje zdarzenie wywołane wyborem operacji potęgowania lub pierwiastkowania
*
* Modyfikuję operationLabelText w różny sposób w zależności od tego czy operacja była wywołana pierwszy czy kolejny
* raz pod rząd.
*
* Metoda posiada zabezpieczenie przed sytuacją gdy nastąpiło dzielenie przez 0.
*/
public void handlePowerAndSqrt(String sign) {
if (dividedByZero) { // zablokowanie operacji po dzieleniu przez zero
return;
}
// modyfikacja operationLabelText
if (!chosePowOrSqlt) { // pierwszy pod rząd wybór tej operacji
stringBuff = sign + "(" + formatWithoutSpacing(resultLabelText) + ")";
operationLabelText = operationLabelText + stringBuff;
}
else { // kolejny
String reversedBuff = new StringBuilder(stringBuff).reverse().toString();
reversedBuff = reversedBuff.replace(")", "\\)");
reversedBuff = reversedBuff.replace("(", "\\(");
stringBuff = sign + "(" + stringBuff + ")";
operationLabelText = new StringBuilder(operationLabelText).reverse().toString().replaceFirst(reversedBuff, ")" + reversedBuff + "(" + new StringBuilder(sign).reverse().toString());
operationLabelText = new StringBuilder(operationLabelText).reverse().toString();
}
// modyfikacja resultLabelText
executeUnaryOperation(sign);
if (!dividedByZero)
resultLabelText = formatWithSpacing(resultLabelText);
choseNumber = false;
choseDot = false;
chosePowOrSqlt = true;
}
/**
* Obsługuje zdarzenie wywołane wyborem operacji wyznaczania procentu
*
* Modyfikuję operationLabelText w różny sposób w zależności od tego czy operacja była wywołana pierwszy czy kolejny
* raz pod rząd.
*
* Metoda posiada zabezpieczenie przed sytuacją gdy nastąpiło dzielenie przez 0.
*/
public void handlePercent() {
if (dividedByZero) { // zablokowanie operacji po dzieleniu przez zero
return;
}
// modyfikacja operationLabelText i resultLabelText
if (!chosePercent) { // pierwszy pod rząd wybór tej operacji
executeUnaryOperation("%");
operationLabelText = operationLabelText + formatWithoutSpacing(resultLabelText);
}
else { // kolejny
String oldResult = formatWithoutSpacing(resultLabelText);
executeUnaryOperation("%");
String reversedOldResult = new StringBuilder(oldResult).reverse().toString();
operationLabelText = new StringBuilder(operationLabelText).reverse().toString().replaceFirst(reversedOldResult, new StringBuilder(resultLabelText).reverse().toString());
operationLabelText = new StringBuilder(operationLabelText).reverse().toString();
}
if (!dividedByZero)
resultLabelText = formatWithSpacing(resultLabelText);
choseNumber = false;
choseDot = false;
chosePercent = true;
}
/**
* Obsługuje zdarzenie wywołane wyborem operacji wyznaczania ułamka
*
* Modyfikuję operationLabelText w różny sposób w zależności od tego czy operacja była wywołana pierwszy czy kolejny
* raz pod rząd.
*
* Metoda posiada zabezpieczenie przed sytuacją gdy nastąpiło dzielenie przez 0.
*/
public void handleFraction() {
if (dividedByZero) { // zablokowanie operacji po dzieleniu przez zero
return;
}
// modyfikacja operationLabelText
if (!choseFraction) { // pierwszy pod rząd wybór tej operacji
stringBuff = "1/( " + formatWithoutSpacing(resultLabelText) + " )";
operationLabelText = operationLabelText + stringBuff;
}
else { // kolejny
String reversedBuff = new StringBuilder(stringBuff).reverse().toString();
reversedBuff = reversedBuff.replace(")", "\\)");
reversedBuff = reversedBuff.replace("(", "\\(");
stringBuff = "1/" + "( " + stringBuff + " )";
operationLabelText = new StringBuilder(operationLabelText).reverse().toString().replaceFirst(reversedBuff, ") " + reversedBuff + " (" + new StringBuilder("1/").reverse().toString());
operationLabelText = new StringBuilder(operationLabelText).reverse().toString();
}
// modyfikacja resultLabelText
executeUnaryOperation("1/");
if (!dividedByZero)
resultLabelText = formatWithSpacing(resultLabelText);
choseNumber = false;
choseDot = false;
choseFraction = true;
}
/**
* Wykonuje operację jednoargumentową na podstawie otrzymanego znaku
*
* Modyfikuję wartość resultLabelText przy użyciu odpowiedniego działania na resultLabelText.
*/
private void executeUnaryOperation(String sign) {
switch(sign) {
case "sqrt":
resultLabelText = convertToString(convertToDouble(resultLabelText) * convertToDouble(resultLabelText));
break;
case "√":
resultLabelText = convertToString(Math.sqrt(convertToDouble(resultLabelText)));
break;
case "1/":
if (deleteSpacesAndConvertToDouble(resultLabelText) != 0) { // zabezpieczenie przed dzieleniem przez 0
resultLabelText = convertToString(1 / convertToDouble(resultLabelText));
}
else {
resultLabelText = "Cannot divide by zero";
dividedByZero = true;
}
break;
case "%":
resultLabelText = convertToString(convertToDouble(resultLabelText) / 100 * previousNumber);
break;
default:
System.out.println("Nieznana operacja!");
}
}
/**
* Obsługuje zdarzenie wywołane wyborem znaku =
*
* Modyfikuje operationLabelText oraz wyznacza nową wartość resultLabelText przy użyciu wartości zmiennych
* previousNumber i lastNumber.
*
* Metoda posiada zabezpieczenie przed sytuacją gdy nastąpiło dzielenie przez 0.
*
* Następnie podejmowane są kroki w przypadku gdy metoda została wywołana bez wyboru operacji dwuargumentowej.
* Polegają one na modyfikacji operationLabelText i zakończeniu wykonywania metody ponieważ resultLabelText nie
* może być w takiej sytuacji modyfikowany. W przypadku gdy metoda została wywołana z wybraną operacją
* dwuargumentową modyfikowany jest operationLabelText, wykonywana jest wybrana operacja oraz wyświetlana jest
* nowa wartość resultLabelText.
*/
public void handleEqualSign() {
// zabezpieczenie przed różnymi sytuacjami
if (dividedByZero) { // zablokowanie operacji po dzieleniu przez zero
handleClear();
return;
}
// modyfikacja operationLabelText przy braku wyboru operacji dwuargumentowej
if (!choseDyadicOperation && !chosePowOrSqlt && !chosePercent && !choseFraction) { // nie wybrano znaku i operacji jednoargumentowej []||[=]||[2]||[2=]
operationLabelText = formatWithoutSpacing(resultLabelText) + " = ";
choseNumber = false;
choseDot = false;
choseEqualSign = true;
return;
}
if (!choseDyadicOperation) { // nie wybrano znaku i wybrano operację jednoargumentową
operationLabelText = operationLabelText + " = ";
choseNumber = false;
choseDot = false;
choseEqualSign = true;
chosePowOrSqlt = false;
chosePercent = false;
choseFraction = false;
return;
}
// modyfikacja operationLabelText po wyborze operacji dwuargumentowej
// choseOperationSign == True zawsze w tym miejscu
if (choseEqualSign) { // wybrano znak i = kolejny raz pod rząd [2+=]||[2+3=]||[2+3==]
previousNumber = deleteSpacesAndConvertToDouble(resultLabelText);
operationLabelText = formatWithoutSpacing(resultLabelText) + " " + lastOperationSign + " " + formatWithoutSpacing(convertToString(lastNumber)) + " = ";
}
else if (!choseNumber && !chosePowOrSqlt && !chosePercent && !choseFraction) { // wybrano znak i nie wybrano drugiej liczby [+]||[2+]
lastNumber = deleteSpacesAndConvertToDouble(resultLabelText);
operationLabelText = operationLabelText + formatWithoutSpacing(resultLabelText) + " = ";
}
else if (chosePowOrSqlt || chosePercent || choseFraction) { // wybrano znak i operację jednoargumentową [2+sqrt(3)]
lastNumber = deleteSpacesAndConvertToDouble(resultLabelText);
operationLabelText = operationLabelText + " = ";
}
else { // wybrano znak i cyfre [2+3]
lastNumber = deleteSpacesAndConvertToDouble(resultLabelText);
operationLabelText = operationLabelText + formatWithoutSpacing(convertToString(lastNumber)) + " = ";
}
// modyfikacja resultLabelText
executeDyadicOperation();
if (!dividedByZero)
resultLabelText = formatWithSpacing(resultLabelText);
choseNumber = false;
choseDot = false;
choseEqualSign = true;
chosePowOrSqlt = false;
chosePercent = false;
choseFraction = false;
}
/**
* Usuwa ostatni znak z resultLabelText
*
* Posiada trzy możliwe przebiegi w zależności czy ostatni znak to przecinek, cyfra oraz ostatnia cyfra.
*
* Metoda posiada zabezpieczenie przed sytuacją gdy nastąpiło dzielenie przez 0.
*/
public void handleBackspace() {
if (dividedByZero) { // zablokowanie operacji po dzieleniu przez zero
handleClear();
return;
}
if (resultLabelText.length() == 1) { // ostatnia cyfra
resultLabelText = "0";
}
else if (!resultLabelText.endsWith(".")) { // zwykła cyfra
resultLabelText = resultLabelText.substring(0, resultLabelText.length() - 1);
}
else { // przecinek
resultLabelText = resultLabelText.substring(0, resultLabelText.length() - 1);
choseDot = false;
}
}
/**
* Usuwa zawartość resultLabelText
*
* W przypadku użycia znaku "=" działa tak samo jak clear().
*
* Metoda posiada zabezpieczenie przed sytuacją gdy nastąpiło dzielenie przez 0.
*/
public void handleClearEntry() {
if (dividedByZero) { // zablokowanie operacji po dzieleniu przez zero
handleClear();
return;
}
if (!choseEqualSign) {
resultLabelText = "0";
choseNumber = false;
choseDot = false;
chosePowOrSqlt = false;
chosePercent = false;
choseFraction = false;
}
else {
handleClear();
}
}
/**
* Usuwa wszystkie wprowadzone dane i przywraca je do wartości początkowych
*/
public void handleClear() {
previousNumber = 0;
lastNumber = 0;
operationLabelText = "";
resultLabelText = "0";
lastOperationSign = "";
choseNumber = false;
choseDot = false;
choseDyadicOperation = false;
chosePowOrSqlt = false;
chosePercent = false;
choseFraction = false;
choseEqualSign = false;
}
/**
* Obsługuje zdarzenie wywołane wyborem przycisku zmiany znaku
*
* Zmienia znak liczby przechowywanej w resultLabel na przeciwny mnożąc jej wartość przez -1.
*
* Metoda posiada zabezpieczenie przed sytuacją gdy nastąpiło dzielenie przez 0.
*/
public void handleSignNegation() {
if (dividedByZero) { // zablokowanie operacji po dzieleniu przez zero
return;
}
if (!resultLabelText.equals("0"))
resultLabelText = formatWithSpacing(convertToString(-1 * deleteSpacesAndConvertToDouble(resultLabelText)));
}
/**
* Usuwa ostatni znak z operationLabelText i zamienia go na otrzymany w argumencie
*/
private void swapSignNumber(String sign) {
if (operationLabelText.length() > 0) {
operationLabelText = operationLabelText.substring(0, operationLabelText.length()-2) + sign + " ";
}
}
/**
* Konwertuje otrzymanego doubla do Stringa
*/
private String convertToString(double number) {
return String.valueOf(number);
}
/**
* Konwertuje otrzymanego Stringa do doubla
*/
private double convertToDouble(String number) {
return Double.parseDouble(number);
}
/**
* Usuwa spację z otrzymanego Stringa i konwertuję go do doubla
*/
private double deleteSpacesAndConvertToDouble(String number) {
return Double.parseDouble(number.replace(" ", "")); // " " ma nietypowe kodowanie;
}
/**
* Formatuje otrzymanego Stringa dodając spację co 3 cyfry
*
* Używa w tym celu klasy DecimalFormat
*/
private String formatWithSpacing(String number) {
return resultLabelText = formatForResultLabelText.format(deleteSpacesAndConvertToDouble(number));
}
/**
* Formatuje otrzymanego Stringa bez dodawania spacji
*
* Używa w tym celu klasy DecimalFormat
*/
private String formatWithoutSpacing(String number) {
return resultLabelText = formatForOperationLabelText.format(deleteSpacesAndConvertToDouble(number));
}
/**
* Zwraca zawartość zmiennej operationLabelText
*/
public String getOperationLabelText() {
return operationLabelText;
}
/**
* Zwraca zawartość zmiennej resultLabelText
*/
public String getResultLabelText() {
return resultLabelText;
}
/**
* Zmienia na chwilę kolor tła przesłanego przycisku
*/
public void highlightButton(JButton button, Color color) {
Color selectButtonColor = new Color(70,70,70);
button.setBackground(selectButtonColor);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
button.setBackground(color);
}
}
| null |
6395_0 | Queue2Deanery/queue-backend | 113 | src/main/java/pl/ee/deanery/dto/QueueDTO.java | package pl.ee.deanery.dto;
import lombok.*;
import java.util.List;
@Data
@Builder
@RequiredArgsConstructor
@AllArgsConstructor
//@NoArgsConstructor
public class QueueDTO {
private Long id;
private String name;
private String shortName;
//private List<Long> issueIds; // przy dłuższym czasie działania może być bardzo długa
}
| //private List<Long> issueIds; // przy dłuższym czasie działania może być bardzo długa | package pl.ee.deanery.dto;
import lombok.*;
import java.util.List;
@Data
@Builder
@RequiredArgsConstructor
@AllArgsConstructor
//@NoArgsConstructor
public class QueueDTO {
private Long id;
private String name;
private String shortName;
//private List<Long> <SUF>
}
| null |
7264_10 | Ravaelles/Atlantis | 4,788 | src/atlantis/combat/micro/avoid/FightInsteadAvoid.java | package atlantis.combat.micro.avoid;
import atlantis.combat.micro.avoid.zerg.ShouldFightInsteadAvoidAsZerg;
import atlantis.combat.retreating.ShouldRetreat;
import atlantis.combat.targeting.ATargetingCrucial;
import atlantis.game.A;
import atlantis.units.AUnit;
import atlantis.units.AUnitType;
import atlantis.units.Units;
import atlantis.units.select.Select;
import atlantis.units.select.Selection;
import atlantis.util.We;
import atlantis.util.cache.Cache;
public class FightInsteadAvoid {
private Cache<Boolean> cache = new Cache<>();
protected final AUnit unit;
protected final Units enemies;
protected final Selection enemiesSelection;
/**
* Enemy units of different types that are dangerously close, extracted as variables for easier access
*/
protected final AUnit combatBuilding;
protected final AUnit invisibleDT;
protected final AUnit invisibleCombatUnit;
protected final AUnit lurker;
protected final AUnit tankSieged;
protected final AUnit tanks;
protected final AUnit reaver;
protected final AUnit vulture;
protected final AUnit ranged;
protected final AUnit melee;
private final TerranFightInsteadAvoid terranFightInsteadAvoid;
// =========================================================
public FightInsteadAvoid(AUnit unit, Units enemies) {
this.unit = unit;
this.enemies = enemies;
this.enemiesSelection = Select.from(enemies);
terranFightInsteadAvoid = new TerranFightInsteadAvoid(unit);
Selection selector = Select.from(enemies);
invisibleDT = selector.ofType(AUnitType.Protoss_Dark_Templar).effUndetected().first();
invisibleCombatUnit = selector.effUndetected().combatUnits().first();
lurker = selector.ofType(AUnitType.Zerg_Lurker).first();
tankSieged = selector.ofType(AUnitType.Terran_Siege_Tank_Siege_Mode).first();
tanks = selector.tanks().first();
vulture = selector.ofType(AUnitType.Terran_Vulture).first();
reaver = selector.ofType(AUnitType.Protoss_Reaver).first();
combatBuilding = selector.buildings().first();
ranged = selector.ranged().first();
melee = selector.melee().first();
}
// =========================================================
public boolean shouldFight() {
return cache.get(
"shouldFight:" + unit.idWithHash(),
3,
() -> {
if (!unit.hasAnyWeapon()) return false;
if (ShouldFightInsteadAvoidAsZerg.shouldFight(unit)) return true;
if (unit.isMelee() && unit.shouldRetreat()) return false;
if (enemies.isEmpty()) {
// System.err.println("NoEnemies? LooksBugged");
// unit.addLog("NoEnemiesReally?");
// return true;
return false;
}
if (unit.mission() != null && unit.mission().forcesUnitToFight(unit, enemies)) {
unit.addLog("ForcedFight");
return true;
}
// Workers
if (unit.isWorker()) {
return fightAsWorker(enemies);
}
// Combat units
else {
if (fightInImportantCases()) {
unit.addLog("FightImportant");
return true;
}
return fightAsCombatUnit();
}
}
);
}
// public boolean shouldFightCached() {
// String key = "shouldFight:" + unit.idWithHash();
// return cache.has(key) ? cache.get(key) : false;
// }
// =========================================================
protected boolean fightAsCombatUnit() {
if (fightBecauseWayTooManyUnitsNear()) {
unit.addLog("FightStacked");
return true;
}
if (ShouldRetreat.shouldRetreat(unit)) {
if (finishOffAlmostDeadTarget()) {
unit.addLog("FatalityTo" + unit.target().type());
return true;
}
if (
unit.isRanged()
&& ranged == null
&& unit.enemiesNear().ranged().isEmpty()
&& (unit.hp() >= 21 || unit.lastStartedAttackMoreThanAgo(30 * 7))
) {
unit.addLog("FightAsRanged");
return true;
}
else {
unit.setTooltip("Retreat", true);
unit.addLog("Retreat");
return false;
}
}
if (terranFightInsteadAvoid.fightForTerran()) {
return true;
}
// vs COMBAT BUILDINGS
if (
combatBuilding != null
&& unit.mission().allowsToAttackCombatBuildings(unit, combatBuilding)
&& unit.friendsInRadiusCount(2) >= 2
&& unit.friendsInRadiusCount(4) >= (unit.isAir() ? 14 : 6)
&& (!unit.isAir() || unit.woundPercentMax(15))
&& unit.combatEvalRelative() >= 3.2
&& (unit.hp() >= 23 || unit.isMelee())
) {
unit.addLog("FightBuilding");
return true;
}
// if (combatBuilding != null && fightBecauseWayTooManyUnitsNear()) {
// return true;
// }
// if (enemies.onlyRanged() && ACombatEvaluator.isSituationFavorable()) {
// if (enemies.onlyMelee() && ACombatEvaluator.isSituationFavorable()) {
// return true;
// }
if (
lurker != null && (!lurker.isBurrowed() || lurker.isDetected())
&& unit.noCooldown() && lurker.distToLessThan(unit, 4) && unit.friendsInRadiusCount(3) >= 3
) {
unit.addLog("FightLurker");
return true;
}
if (tankSieged != null && unit.distToLessThan(tankSieged, 3)) {
unit.addLog("FightSiegedTank");
return true;
}
if (unit.isMelee()) {
return fightAsMeleeUnit();
}
else {
return false;
// return fightAsRangedUnit();
}
}
protected boolean fightInImportantCases() {
if (unit.isWorker()) {
System.err.println("Worker in fightInImportantCases");
}
if (forDragoon()) {
return true;
}
if (terranFightInsteadAvoid.fightForTerran()) {
return true;
}
if (
unit.isMelee()
&& unit.friendsNear().ofType(AUnitType.Protoss_Photon_Cannon, AUnitType.Zerg_Sunken_Colony)
.inRadius(2.8, unit).notEmpty()
) {
unit.addLog("DefendCannon");
return true;
}
// Attacking critically important unit
if (ATargetingCrucial.isCrucialUnit(unit.target())) {
unit.setTooltipTactical("Crucial!");
return true;
}
if (forbidMeleeUnitsAbandoningCloseTargets()) {
unit.setTooltipTactical("DontLeave");
return true;
}
if (forbidAntiAirAbandoningCloseTargets()) {
unit.setTooltipTactical("DontAbandonCloseTargetz");
return true;
}
if (forWraith()) {
return true;
}
return false;
}
private boolean forWraith() {
if (!unit.isWraith()) {
return false;
}
if (unit.hp() <= 40 || (unit.cooldown() <= 3 && !unit.isTank())) {
return false;
}
if (
unit.enemiesNear().effVisible().inRadius(12, unit).ofType(
AUnitType.Protoss_Carrier,
AUnitType.Zerg_Guardian
).notEmpty()
) {
unit.setTooltip("AntiAirBravery");
return true;
}
if (
unit.enemiesNear().effVisible().inRadius(7, unit).ofType(
AUnitType.Protoss_Arbiter,
AUnitType.Terran_Battlecruiser,
AUnitType.Terran_Wraith,
AUnitType.Zerg_Mutalisk
).notEmpty()
) {
unit.setTooltip("AntiAirBravery");
return true;
}
return false;
}
private boolean forDragoon() {
if (!unit.isDragoon()) {
return false;
}
if (unit.cooldownRemaining() <= 3) {
int secondsWithoutAttack = (int) (2 + unit.woundPercent() / 13);
boolean haveNotAttackedInAWhile = unit.lastStartedAttackMoreThanAgo(30 * secondsWithoutAttack);
if (unit.shieldDamageAtMost(10) || haveNotAttackedInAWhile) {
if (unit.meleeEnemiesNearCount(2) <= 1 || haveNotAttackedInAWhile) {
unit.addLog("Aiur");
return true;
}
}
}
// oddal sie od contain focus pointu, bo na Destination stackują się na focusie
// trzymaj ładny krąg na focusie
// if (
// // Long didn't shoot
// unit.lastStartedAttackMoreThanAgo(30 * 5)
// || (
// // Relatively healthy
// ((unit.hp() >= 33 && unit.cooldownRemaining() <= 5) || unit.shieldDamageAtMost(13))
// // Should fire by now
// && (unit.lastStartedAttackMoreThanAgo(30 * 2) || unit.lastUnderAttackMoreThanAgo(30 * 6))
// )
// ) {
// unit.addLog("ForAiur");
// return true;
// }
return false;
}
// RANGED
protected boolean fightAsRangedUnit() {
if (ranged != null && ranged.isABuilding()) {
return false;
}
if (unit.isRanged() && melee != null && ranged == null) {
// if (unit.hp() >= 40 && unit.lastAttackFrameMoreThanAgo(30 * 5)) {
if (unit.hp() >= 40 && unit.lastAttackFrameMoreThanAgo(30 * 4) && unit.nearestEnemyDist() >= 2.9) {
unit.addLog("Courage");
return true;
}
}
if (melee != null && melee.hasPosition()) {
unit.addLog("RunMelee" + A.dist(unit, melee));
// unit.addLog("RunMelee");
return false;
}
if (vulture != null) {
unit.addLog("FightVulture");
return true;
}
if (ranged != null) {
if (unit.isTank() && !unit.isSieged() && unit.lastAttackFrameMoreThanAgo(30 * 4)) {
unit.addLog("TankShoot");
return true;
}
// // Dragoon faster than Marines, can outrun them
// if (unit.isQuickerOrSameSpeedAs(enemies) && unit.hasBiggerRangeThan(enemies)) {
// if (unit.woundPercent() <= 40 && unit.lastUnderAttackMoreThanAgo(30 * 8)) {
// unit.addLog("FightQuick");
// return true;
// }
// }
//
// // Dragoon slower than Vultures, cannot outrun them
// else {
// unit.addLog("FightTooSlow");
// return true;
// }
}
if (ranged != null && !ShouldRetreat.shouldRetreat(unit)) {
unit.addLog("CanFight");
return true;
}
unit.addLog("DontFight");
return false;
}
// MELEE
protected boolean fightAsMeleeUnit() {
if (invisibleDT != null || invisibleCombatUnit != null) {
unit.addLog("RunInvisible");
return false;
}
return !ShouldRetreat.shouldRetreat(unit);
// return true;
}
// =========================================================
private boolean finishOffAlmostDeadTarget() {
if (unit.cooldownRemaining() >= 5) {
return false;
}
AUnit target = unit.target();
if (target != null && target.type().totalCost() >= 70 && target.hp() <= (unit.damageAgainst(target) - 1)) {
return true;
}
return false;
}
// private boolean handleTerranInfantryShouldFight() {
// if (!unit.isTerranInfantry()) {
// return false;
// }
//
// int meleeEnemiesNear = unit.enemiesNear().melee().inRadius(1.5, unit).count();
// if (unit.hp() <= (Enemy.protoss() ? 18 : 11) * meleeEnemiesNear) {
// return false;
// }
//
//// return false;
// boolean medicNear = unit.medicInHealRange();
// return medicNear || (!unit.isWounded() && ranged == null && unit.friendsInRadiusCount(1) >= 4);
// }
protected boolean forbidMeleeUnitsAbandoningCloseTargets() {
return unit.isMelee()
// && (!unit.isFirebat() || TerranFirebat.shouldContinueMeleeFighting())
&& (
unit.isDT()
|| (unit.hp() <= 30 && unit.enemiesNear().ranged().inRadius(6, unit).notEmpty())
|| (unit.enemiesNear().ranged().inRadius(1, unit).isNotEmpty())
|| (unit.enemiesNear().combatBuildings(false).inRadius(3, unit).isNotEmpty())
|| (unit.enemiesNear().ofType(AUnitType.Protoss_Reaver).inRadius(3, unit).isNotEmpty())
);
}
protected boolean forbidAntiAirAbandoningCloseTargets() {
return unit.isAirUnitAntiAir()
&& unit.enemiesNear()
.canBeAttackedBy(unit, 3)
.isNotEmpty();
}
protected boolean fightBecauseWayTooManyUnitsNear() {
if (!We.terran() || unit.isAir()) {
return false;
}
Selection our = unit.friendsNear().combatUnits();
int allCount = unit.allUnitsNear().inRadius(0.8, unit).effVisible().count();
int ourCount = our.nonBuildings().inRadius(1, unit).count();
// if (unit.mission() != null && unit.mission().isMissionAttack()) {
boolean isStacked = false;
if (We.terran()) {
isStacked = allCount >= 7 || (invisibleDT != null && allCount >= 4)
|| our.inRadius(1.3, unit).atLeast(25);
}
else if (We.protoss()) {
isStacked = allCount >= 7 || (invisibleDT != null && allCount >= 4)
|| our.inRadius(1.3, unit).atLeast(7);
}
else if (We.zerg()) {
isStacked = allCount >= 6 || (invisibleDT != null && allCount >= 4)
|| our.inRadius(1.3, unit).atLeast(7);
}
// }
// if (combatBuilding != null) {
// if (unit.mission().isMissionAttack() || unit.combatEvalRelative() >= 3.0) {
// return true;
// }
//// && unit.friendsInRadiusCountSelect(6).atLeast(10)
//// && HeuristicCombatEvaluator.advantagePercent(unit, 50);
//// && A.printErrorAndReturnTrue("Fight DEF building cuz stacked " + unit.nameWithId());
// }
// boolean isStacked = ourCount >= 5 || allCount >= 6;
// boolean isStacked = ourCount >= 5 || allCount >= 6;
if (isStacked) {
unit.addLog("Stacked:" + ourCount + "/" + allCount);
}
return isStacked;
}
protected boolean fightAsWorker(Units enemies) {
if (enemies.size() >= 3) return false;
if (combatBuilding != null || lurker != null || reaver != null || tankSieged != null || melee != null || invisibleCombatUnit != null) {
return false;
}
return unit.hpPercent() > 75 && unit.distToLessThan(Select.main(), 12);
}
}
| // trzymaj ładny krąg na focusie | package atlantis.combat.micro.avoid;
import atlantis.combat.micro.avoid.zerg.ShouldFightInsteadAvoidAsZerg;
import atlantis.combat.retreating.ShouldRetreat;
import atlantis.combat.targeting.ATargetingCrucial;
import atlantis.game.A;
import atlantis.units.AUnit;
import atlantis.units.AUnitType;
import atlantis.units.Units;
import atlantis.units.select.Select;
import atlantis.units.select.Selection;
import atlantis.util.We;
import atlantis.util.cache.Cache;
public class FightInsteadAvoid {
private Cache<Boolean> cache = new Cache<>();
protected final AUnit unit;
protected final Units enemies;
protected final Selection enemiesSelection;
/**
* Enemy units of different types that are dangerously close, extracted as variables for easier access
*/
protected final AUnit combatBuilding;
protected final AUnit invisibleDT;
protected final AUnit invisibleCombatUnit;
protected final AUnit lurker;
protected final AUnit tankSieged;
protected final AUnit tanks;
protected final AUnit reaver;
protected final AUnit vulture;
protected final AUnit ranged;
protected final AUnit melee;
private final TerranFightInsteadAvoid terranFightInsteadAvoid;
// =========================================================
public FightInsteadAvoid(AUnit unit, Units enemies) {
this.unit = unit;
this.enemies = enemies;
this.enemiesSelection = Select.from(enemies);
terranFightInsteadAvoid = new TerranFightInsteadAvoid(unit);
Selection selector = Select.from(enemies);
invisibleDT = selector.ofType(AUnitType.Protoss_Dark_Templar).effUndetected().first();
invisibleCombatUnit = selector.effUndetected().combatUnits().first();
lurker = selector.ofType(AUnitType.Zerg_Lurker).first();
tankSieged = selector.ofType(AUnitType.Terran_Siege_Tank_Siege_Mode).first();
tanks = selector.tanks().first();
vulture = selector.ofType(AUnitType.Terran_Vulture).first();
reaver = selector.ofType(AUnitType.Protoss_Reaver).first();
combatBuilding = selector.buildings().first();
ranged = selector.ranged().first();
melee = selector.melee().first();
}
// =========================================================
public boolean shouldFight() {
return cache.get(
"shouldFight:" + unit.idWithHash(),
3,
() -> {
if (!unit.hasAnyWeapon()) return false;
if (ShouldFightInsteadAvoidAsZerg.shouldFight(unit)) return true;
if (unit.isMelee() && unit.shouldRetreat()) return false;
if (enemies.isEmpty()) {
// System.err.println("NoEnemies? LooksBugged");
// unit.addLog("NoEnemiesReally?");
// return true;
return false;
}
if (unit.mission() != null && unit.mission().forcesUnitToFight(unit, enemies)) {
unit.addLog("ForcedFight");
return true;
}
// Workers
if (unit.isWorker()) {
return fightAsWorker(enemies);
}
// Combat units
else {
if (fightInImportantCases()) {
unit.addLog("FightImportant");
return true;
}
return fightAsCombatUnit();
}
}
);
}
// public boolean shouldFightCached() {
// String key = "shouldFight:" + unit.idWithHash();
// return cache.has(key) ? cache.get(key) : false;
// }
// =========================================================
protected boolean fightAsCombatUnit() {
if (fightBecauseWayTooManyUnitsNear()) {
unit.addLog("FightStacked");
return true;
}
if (ShouldRetreat.shouldRetreat(unit)) {
if (finishOffAlmostDeadTarget()) {
unit.addLog("FatalityTo" + unit.target().type());
return true;
}
if (
unit.isRanged()
&& ranged == null
&& unit.enemiesNear().ranged().isEmpty()
&& (unit.hp() >= 21 || unit.lastStartedAttackMoreThanAgo(30 * 7))
) {
unit.addLog("FightAsRanged");
return true;
}
else {
unit.setTooltip("Retreat", true);
unit.addLog("Retreat");
return false;
}
}
if (terranFightInsteadAvoid.fightForTerran()) {
return true;
}
// vs COMBAT BUILDINGS
if (
combatBuilding != null
&& unit.mission().allowsToAttackCombatBuildings(unit, combatBuilding)
&& unit.friendsInRadiusCount(2) >= 2
&& unit.friendsInRadiusCount(4) >= (unit.isAir() ? 14 : 6)
&& (!unit.isAir() || unit.woundPercentMax(15))
&& unit.combatEvalRelative() >= 3.2
&& (unit.hp() >= 23 || unit.isMelee())
) {
unit.addLog("FightBuilding");
return true;
}
// if (combatBuilding != null && fightBecauseWayTooManyUnitsNear()) {
// return true;
// }
// if (enemies.onlyRanged() && ACombatEvaluator.isSituationFavorable()) {
// if (enemies.onlyMelee() && ACombatEvaluator.isSituationFavorable()) {
// return true;
// }
if (
lurker != null && (!lurker.isBurrowed() || lurker.isDetected())
&& unit.noCooldown() && lurker.distToLessThan(unit, 4) && unit.friendsInRadiusCount(3) >= 3
) {
unit.addLog("FightLurker");
return true;
}
if (tankSieged != null && unit.distToLessThan(tankSieged, 3)) {
unit.addLog("FightSiegedTank");
return true;
}
if (unit.isMelee()) {
return fightAsMeleeUnit();
}
else {
return false;
// return fightAsRangedUnit();
}
}
protected boolean fightInImportantCases() {
if (unit.isWorker()) {
System.err.println("Worker in fightInImportantCases");
}
if (forDragoon()) {
return true;
}
if (terranFightInsteadAvoid.fightForTerran()) {
return true;
}
if (
unit.isMelee()
&& unit.friendsNear().ofType(AUnitType.Protoss_Photon_Cannon, AUnitType.Zerg_Sunken_Colony)
.inRadius(2.8, unit).notEmpty()
) {
unit.addLog("DefendCannon");
return true;
}
// Attacking critically important unit
if (ATargetingCrucial.isCrucialUnit(unit.target())) {
unit.setTooltipTactical("Crucial!");
return true;
}
if (forbidMeleeUnitsAbandoningCloseTargets()) {
unit.setTooltipTactical("DontLeave");
return true;
}
if (forbidAntiAirAbandoningCloseTargets()) {
unit.setTooltipTactical("DontAbandonCloseTargetz");
return true;
}
if (forWraith()) {
return true;
}
return false;
}
private boolean forWraith() {
if (!unit.isWraith()) {
return false;
}
if (unit.hp() <= 40 || (unit.cooldown() <= 3 && !unit.isTank())) {
return false;
}
if (
unit.enemiesNear().effVisible().inRadius(12, unit).ofType(
AUnitType.Protoss_Carrier,
AUnitType.Zerg_Guardian
).notEmpty()
) {
unit.setTooltip("AntiAirBravery");
return true;
}
if (
unit.enemiesNear().effVisible().inRadius(7, unit).ofType(
AUnitType.Protoss_Arbiter,
AUnitType.Terran_Battlecruiser,
AUnitType.Terran_Wraith,
AUnitType.Zerg_Mutalisk
).notEmpty()
) {
unit.setTooltip("AntiAirBravery");
return true;
}
return false;
}
private boolean forDragoon() {
if (!unit.isDragoon()) {
return false;
}
if (unit.cooldownRemaining() <= 3) {
int secondsWithoutAttack = (int) (2 + unit.woundPercent() / 13);
boolean haveNotAttackedInAWhile = unit.lastStartedAttackMoreThanAgo(30 * secondsWithoutAttack);
if (unit.shieldDamageAtMost(10) || haveNotAttackedInAWhile) {
if (unit.meleeEnemiesNearCount(2) <= 1 || haveNotAttackedInAWhile) {
unit.addLog("Aiur");
return true;
}
}
}
// oddal sie od contain focus pointu, bo na Destination stackują się na focusie
// trzymaj ładny <SUF>
// if (
// // Long didn't shoot
// unit.lastStartedAttackMoreThanAgo(30 * 5)
// || (
// // Relatively healthy
// ((unit.hp() >= 33 && unit.cooldownRemaining() <= 5) || unit.shieldDamageAtMost(13))
// // Should fire by now
// && (unit.lastStartedAttackMoreThanAgo(30 * 2) || unit.lastUnderAttackMoreThanAgo(30 * 6))
// )
// ) {
// unit.addLog("ForAiur");
// return true;
// }
return false;
}
// RANGED
protected boolean fightAsRangedUnit() {
if (ranged != null && ranged.isABuilding()) {
return false;
}
if (unit.isRanged() && melee != null && ranged == null) {
// if (unit.hp() >= 40 && unit.lastAttackFrameMoreThanAgo(30 * 5)) {
if (unit.hp() >= 40 && unit.lastAttackFrameMoreThanAgo(30 * 4) && unit.nearestEnemyDist() >= 2.9) {
unit.addLog("Courage");
return true;
}
}
if (melee != null && melee.hasPosition()) {
unit.addLog("RunMelee" + A.dist(unit, melee));
// unit.addLog("RunMelee");
return false;
}
if (vulture != null) {
unit.addLog("FightVulture");
return true;
}
if (ranged != null) {
if (unit.isTank() && !unit.isSieged() && unit.lastAttackFrameMoreThanAgo(30 * 4)) {
unit.addLog("TankShoot");
return true;
}
// // Dragoon faster than Marines, can outrun them
// if (unit.isQuickerOrSameSpeedAs(enemies) && unit.hasBiggerRangeThan(enemies)) {
// if (unit.woundPercent() <= 40 && unit.lastUnderAttackMoreThanAgo(30 * 8)) {
// unit.addLog("FightQuick");
// return true;
// }
// }
//
// // Dragoon slower than Vultures, cannot outrun them
// else {
// unit.addLog("FightTooSlow");
// return true;
// }
}
if (ranged != null && !ShouldRetreat.shouldRetreat(unit)) {
unit.addLog("CanFight");
return true;
}
unit.addLog("DontFight");
return false;
}
// MELEE
protected boolean fightAsMeleeUnit() {
if (invisibleDT != null || invisibleCombatUnit != null) {
unit.addLog("RunInvisible");
return false;
}
return !ShouldRetreat.shouldRetreat(unit);
// return true;
}
// =========================================================
private boolean finishOffAlmostDeadTarget() {
if (unit.cooldownRemaining() >= 5) {
return false;
}
AUnit target = unit.target();
if (target != null && target.type().totalCost() >= 70 && target.hp() <= (unit.damageAgainst(target) - 1)) {
return true;
}
return false;
}
// private boolean handleTerranInfantryShouldFight() {
// if (!unit.isTerranInfantry()) {
// return false;
// }
//
// int meleeEnemiesNear = unit.enemiesNear().melee().inRadius(1.5, unit).count();
// if (unit.hp() <= (Enemy.protoss() ? 18 : 11) * meleeEnemiesNear) {
// return false;
// }
//
//// return false;
// boolean medicNear = unit.medicInHealRange();
// return medicNear || (!unit.isWounded() && ranged == null && unit.friendsInRadiusCount(1) >= 4);
// }
protected boolean forbidMeleeUnitsAbandoningCloseTargets() {
return unit.isMelee()
// && (!unit.isFirebat() || TerranFirebat.shouldContinueMeleeFighting())
&& (
unit.isDT()
|| (unit.hp() <= 30 && unit.enemiesNear().ranged().inRadius(6, unit).notEmpty())
|| (unit.enemiesNear().ranged().inRadius(1, unit).isNotEmpty())
|| (unit.enemiesNear().combatBuildings(false).inRadius(3, unit).isNotEmpty())
|| (unit.enemiesNear().ofType(AUnitType.Protoss_Reaver).inRadius(3, unit).isNotEmpty())
);
}
protected boolean forbidAntiAirAbandoningCloseTargets() {
return unit.isAirUnitAntiAir()
&& unit.enemiesNear()
.canBeAttackedBy(unit, 3)
.isNotEmpty();
}
protected boolean fightBecauseWayTooManyUnitsNear() {
if (!We.terran() || unit.isAir()) {
return false;
}
Selection our = unit.friendsNear().combatUnits();
int allCount = unit.allUnitsNear().inRadius(0.8, unit).effVisible().count();
int ourCount = our.nonBuildings().inRadius(1, unit).count();
// if (unit.mission() != null && unit.mission().isMissionAttack()) {
boolean isStacked = false;
if (We.terran()) {
isStacked = allCount >= 7 || (invisibleDT != null && allCount >= 4)
|| our.inRadius(1.3, unit).atLeast(25);
}
else if (We.protoss()) {
isStacked = allCount >= 7 || (invisibleDT != null && allCount >= 4)
|| our.inRadius(1.3, unit).atLeast(7);
}
else if (We.zerg()) {
isStacked = allCount >= 6 || (invisibleDT != null && allCount >= 4)
|| our.inRadius(1.3, unit).atLeast(7);
}
// }
// if (combatBuilding != null) {
// if (unit.mission().isMissionAttack() || unit.combatEvalRelative() >= 3.0) {
// return true;
// }
//// && unit.friendsInRadiusCountSelect(6).atLeast(10)
//// && HeuristicCombatEvaluator.advantagePercent(unit, 50);
//// && A.printErrorAndReturnTrue("Fight DEF building cuz stacked " + unit.nameWithId());
// }
// boolean isStacked = ourCount >= 5 || allCount >= 6;
// boolean isStacked = ourCount >= 5 || allCount >= 6;
if (isStacked) {
unit.addLog("Stacked:" + ourCount + "/" + allCount);
}
return isStacked;
}
protected boolean fightAsWorker(Units enemies) {
if (enemies.size() >= 3) return false;
if (combatBuilding != null || lurker != null || reaver != null || tankSieged != null || melee != null || invisibleCombatUnit != null) {
return false;
}
return unit.hpPercent() > 75 && unit.distToLessThan(Select.main(), 12);
}
}
| null |
3790_1 | Rellikeht/darwin-world | 697 | src/main/java/world/SimulationSettings.java | package world;
import java.util.HashMap;
import java.util.Map;
public class SimulationSettings {
// Enum byłby ładniejszy :(
private static String inputName(String name) { return name.toLowerCase(); }
private static final Map<String, Integer> defaultSettings = new HashMap<>();
private final Map<String, Integer> settings;
private static void addSetting(String name, int defaultValue) {
defaultSettings.put(inputName(name), defaultValue);
}
static {
addSetting("mapHeight", 30); // 10
addSetting("mapWidth", 30); // 10
addSetting("initialGrassAmount", 40); // 3
addSetting("dailyGrassAmount", 20);
addSetting("jungleSize", 9); // 5
addSetting("initialAnimalAmount", 20); // 15
addSetting("initialAnimalEnergy", 120); // 5
addSetting("grassEnergy", 40); // 20
addSetting("energyTakenByProcreation", 40); // 30
addSetting("energyNeededForProcreation", 60); // 500
addSetting("energyTakenByMovement", 5);
addSetting("genomeLength", 20); // 10
addSetting("minAmountOfMutations", 0);
addSetting("maxAmountOfMutations", 16); // 100
addSetting("isMutationRandom", 0);
addSetting("isMapBasic", 1);
addSetting("portalEnergy", 10);
addSetting("tickTime", 200);
addSetting("energyColorStep", 80);
}
public int get(String name) {
return settings.get(inputName(name));
}
void set(String name, int value) {
String transformedName = inputName(name);
if (settings.containsKey(transformedName)) {
settings.put(transformedName, value);
}
}
public SimulationSettings(SimulationSettings settings) {
this.settings = new HashMap<>(settings.settings);
}
public SimulationSettings() {
settings = new HashMap<>(defaultSettings);
}
// To pod testy, nie wiem, czy potrzebujemy
public SimulationSettings(
int mapWidth, int mapHeight,
int initialGrassAmount, int jungleSize
) {
this();
set("mapWidth", mapWidth);
set("mapHeight", mapHeight);
set("initialGrassAmount", initialGrassAmount);
set("jungleSize", jungleSize);
}
} | // To pod testy, nie wiem, czy potrzebujemy | package world;
import java.util.HashMap;
import java.util.Map;
public class SimulationSettings {
// Enum byłby ładniejszy :(
private static String inputName(String name) { return name.toLowerCase(); }
private static final Map<String, Integer> defaultSettings = new HashMap<>();
private final Map<String, Integer> settings;
private static void addSetting(String name, int defaultValue) {
defaultSettings.put(inputName(name), defaultValue);
}
static {
addSetting("mapHeight", 30); // 10
addSetting("mapWidth", 30); // 10
addSetting("initialGrassAmount", 40); // 3
addSetting("dailyGrassAmount", 20);
addSetting("jungleSize", 9); // 5
addSetting("initialAnimalAmount", 20); // 15
addSetting("initialAnimalEnergy", 120); // 5
addSetting("grassEnergy", 40); // 20
addSetting("energyTakenByProcreation", 40); // 30
addSetting("energyNeededForProcreation", 60); // 500
addSetting("energyTakenByMovement", 5);
addSetting("genomeLength", 20); // 10
addSetting("minAmountOfMutations", 0);
addSetting("maxAmountOfMutations", 16); // 100
addSetting("isMutationRandom", 0);
addSetting("isMapBasic", 1);
addSetting("portalEnergy", 10);
addSetting("tickTime", 200);
addSetting("energyColorStep", 80);
}
public int get(String name) {
return settings.get(inputName(name));
}
void set(String name, int value) {
String transformedName = inputName(name);
if (settings.containsKey(transformedName)) {
settings.put(transformedName, value);
}
}
public SimulationSettings(SimulationSettings settings) {
this.settings = new HashMap<>(settings.settings);
}
public SimulationSettings() {
settings = new HashMap<>(defaultSettings);
}
// To pod <SUF>
public SimulationSettings(
int mapWidth, int mapHeight,
int initialGrassAmount, int jungleSize
) {
this();
set("mapWidth", mapWidth);
set("mapHeight", mapHeight);
set("initialGrassAmount", initialGrassAmount);
set("jungleSize", jungleSize);
}
} | null |
Subsets and Splits