file_id
stringlengths 4
8
| content
stringlengths 302
35.8k
| repo
stringlengths 9
109
| path
stringlengths 9
163
| token_length
int64 88
7.79k
| original_comment
stringlengths 11
3.46k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | prompt
stringlengths 259
35.6k
|
|---|---|---|---|---|---|---|---|---|
43601_0
|
package com.example.touristguide;
import android.os.Bundle;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import androidx.appcompat.app.AppCompatActivity;
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapView);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// ορισμός τοποθεσίας και λοιπές ρυθμίσεις χάρτη
}
}
|
texnologia-logismikou2023/TouristGuide
|
TouristGuide/app/src/main/java/com/example/touristguide/MapActivity.java
| 243
|
// ορισμός τοποθεσίας και λοιπές ρυθμίσεις χάρτη
|
line_comment
|
el
|
package com.example.touristguide;
import android.os.Bundle;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import androidx.appcompat.app.AppCompatActivity;
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapView);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// ορισμός τοποθεσίας<SUF>
}
}
|
6666_0
|
package gr.aueb.cf.ch2;
import java.util.Scanner;
/**
* Μετατρέπει euros σε δολάρια ΗΠΑ
* Λαμβάνει από τον χρήστη (stdin) ένα ακέραιο
* που συμβολίζει το ποσό σε euros και μετατρέπει
* σε δολάρια ΗΠΑ και εμφανίζει το τελικό αποτέλεσμα
*/
public class EuroToUsdConverterApp {
public static void main(String[] args) {
//Δήλωση και αρχικοποίηση
Scanner scanner = new Scanner(System.in);
int inputEuros = 0;
int totalUsaCents = 0;
int usaDollars = 0;
int usaCents = 0;
final int PARITY = 99;
//Εντολές
System.out.println("Please insert an amount (in Euros)");
inputEuros = scanner.nextInt();
totalUsaCents = inputEuros * PARITY;
usaDollars = totalUsaCents / 100;
usaCents = totalUsaCents % 100;
//Εκτύπωση αποτελεσμάτων
System.out.printf("%d Euros = %d USA dollars and %d cents");
}
}
|
th-am/codingfactory23
|
src/gr/aueb/cf/ch2/EuroToUsdConverterApp.java
| 412
|
/**
* Μετατρέπει euros σε δολάρια ΗΠΑ
* Λαμβάνει από τον χρήστη (stdin) ένα ακέραιο
* που συμβολίζει το ποσό σε euros και μετατρέπει
* σε δολάρια ΗΠΑ και εμφανίζει το τελικό αποτέλεσμα
*/
|
block_comment
|
el
|
package gr.aueb.cf.ch2;
import java.util.Scanner;
/**
* Μετατρέπει euros σε<SUF>*/
public class EuroToUsdConverterApp {
public static void main(String[] args) {
//Δήλωση και αρχικοποίηση
Scanner scanner = new Scanner(System.in);
int inputEuros = 0;
int totalUsaCents = 0;
int usaDollars = 0;
int usaCents = 0;
final int PARITY = 99;
//Εντολές
System.out.println("Please insert an amount (in Euros)");
inputEuros = scanner.nextInt();
totalUsaCents = inputEuros * PARITY;
usaDollars = totalUsaCents / 100;
usaCents = totalUsaCents % 100;
//Εκτύπωση αποτελεσμάτων
System.out.printf("%d Euros = %d USA dollars and %d cents");
}
}
|
369_12
|
package com.example.forgetit;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
/**
* recycle view ου περιεχει καρτες του χρηστη και εμφανιζεται στην δραστηριοτητα
* account.
*/
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.ViewHolder> {
/**
* κενος κατασκευαστης (duh)
*/
public RecycleAdapter(){
}
static Context c;
static String appUser;
Map<String,ArrayList<String>> data;//λεξικα
ArrayList<String> keys;//λιστα με τα κλειδια του λεξικου
boolean dataNullFlag;//true αν το recycleView εχει δεδομενα να παρουσιασει, false δεν εχει.
/**
* Αν το data ειναι null αυτο σημαινει πως ο χρηστης δεν εχει δεδομενα αποθηκευμενα και χρειαζεται ειδικη μεταχειριση. Το dataNullFlag λαμβανει την τιμη false.
*
* Διαφορετικα δεχομαστε ενα γεματο λεξικο, απο αυτο αποθηκευουμε ολα τα κλειδια σε μια προσπελασιμη δομη
* @param data ειναι ενα hashMap που εχει τα δεδομενα ενος χρηστη (εχει ολες τις τριπλετες (ετικετα-ονομα_χρηστη-συνθηματικο)
* το κλειδι του λεξικου ειναι το ονομα_χρηστη και καθε κλειδι δειχνει σε μια λιστα συμβολοσειρων [συνθηματικο, ετικετα]
* @param appUser το ονομα του χρηστη που εχει εισελθει στην δραστηριοτητα account
* @param c αφορα τη δραστηριοτητα που καλεσε το recycleView στην οποια εμφανιζει τα αντιστοιχα μηνυματα προς την οθονη .
*/
public RecycleAdapter(Map<String, ArrayList<String>> data, Context c,String appUser) {
this.c=c;
this.appUser=appUser;
if (data != null)
{
dataNullFlag=false;
keys=new ArrayList<>();
Set<String> AllKeys = data.keySet();//ενα συνολο με ολα τα κλειδια
if (AllKeys.size() != 0)
{
this.data = data;
for (String name : AllKeys)
{
if (name != null)
keys.add(name);//αποθηκευω τα κλειδια σε μια προσπελασιμη δομη
}
}
}
else {
dataNullFlag=true;
}
}
@NonNull
@Override
public RecycleAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout,parent,false);//συνδεση με το περιεχομενο του RecycleView(τις καρτες)
return new ViewHolder(v);
}
/**
* καθε καρτα στην λιστα αναφερεται με αυτη την μεθοδο.
* holder ειναι ενα στοιχειο της λιστας και position η θεση του
* αναλογα με τα δεδομενα που εχουν ερθει στον κονστρακτορα γεμιζω με δεδομενα καθε στοιχειο(holder).
*
* @param holder The ViewHolder which should be updated to represent the contents of the
* item at the given position in the data set.
* @param position The position of the item within the adapter's data set.
*/
@Override
public void onBindViewHolder(@NonNull RecycleAdapter.ViewHolder holder, int position) {
if(dataNullFlag){
holder.cardTitle.setText(R.string.ADDRECORDSMESS);
holder.imageView.setVisibility(View.GONE);
holder.password.setVisibility(View.GONE);
holder.delete.setVisibility(View.INVISIBLE);
holder.edit.setVisibility(View.INVISIBLE);
holder.username.setVisibility(View.GONE);
holder.passwordCopyPaste.setVisibility(View.GONE);
holder.usernameCopyPaste.setVisibility(View.GONE);
}else{
String username= keys.get(position);
ArrayList<String> temp;
temp= data.get(username);
final int positionOfPassword=0,positionOfLabel=1;//το κλειδι του λεξικου ειναι το ονομα_χρηστη και καθε κλειδι δειχνει σε μια λιστα συμβολοσειρων [συνθηματικο,ετικετα]
if(keys.size()!=0)
{
holder.username.setText(username);
holder.password.setText(temp.get(positionOfPassword));
holder.cardTitle.setText(temp.get(positionOfLabel));
holder.imageView.performClick();
}
}
}
/**
* @return τον αριθμο των στοιχειων στην λιστα
*/
@Override
public int getItemCount() {
if( dataNullFlag) {
return 1;
}
else
return keys.size();
}
/**
* μια κλαση που αναπαριστα ενα στοιχειο της λιστας ως μια ενοτητα που αποτελειται απο
* 3 κουμπια και 3 λεζαντες(γινεται συνδεση με τα στοιχεια της καρτας)
*/
static class ViewHolder extends RecyclerView.ViewHolder{
ImageButton edit,delete;//2 κουμπια-εικονες για την λειτουργια της επεξεργασιας μιας καρτας και διαγραφη της.
ImageView imageView;
Boolean PasswordVisibilityflag;
Button usernameCopyPaste,passwordCopyPaste;//κουμπια που αντιγραφουν τα text των textView στα clipboard του κινητου.
TextView username,password,cardTitle;//λεζαντες της καρτας με το ονομα ,το συνθηματικο και τον τιτλο της καρτας.
String passwordText;//διατηρει την πραγματικη τιμη του κωδικου οταν το password textView ειναι μη ορατο.(δλδ εχει ως text "**..**"
/**
* κονστρακτορας
* @param itemView αναπαριστα ενα στοιχειο της λιστας ως μια ενοτητα
* δινονται τιμες σε καθε view που αναφερθηκε παραπανω και περιεχεται στο itemView
*/
public ViewHolder(@NonNull View itemView) {
super(itemView);
//συνδεση των στοιχειων με τα αντικειμενα της καρτας
PasswordVisibilityflag =true;
imageView=itemView.findViewById(R.id.imageView);
edit=itemView.findViewById(R.id.imageButton2);
delete=itemView.findViewById(R.id.imageButton);
username=itemView.findViewById(R.id.username);
password=itemView.findViewById(R.id.password);
cardTitle=itemView.findViewById(R.id.cardLabel);
usernameCopyPaste=itemView.findViewById(R.id.button8);
passwordCopyPaste=itemView.findViewById(R.id.button9);
/**
* action listener του κουμπιου usernameCopyPaste για την αντιγραφη του κειμενου στο username TextView στο προχειρο της συσκευης
*/
usernameCopyPaste.setOnClickListener(v->{
String textToCopy = username.getText().toString();
ClipboardManager clipboardManager = (ClipboardManager) v.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = ClipData.newPlainText("Copied Text", textToCopy);
clipboardManager.setPrimaryClip(clipData);
});
/**
* action listener του κουμπιου passwordCopyPaste για την αντιγραφη του κειμενου στο passwordText TextView στο clipboard της συσκευης
*/
passwordCopyPaste.setOnClickListener(v->{
String textToCopy = passwordText;
ClipboardManager clipboardManager = (ClipboardManager) v.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = ClipData.newPlainText("Copied Text", textToCopy);
clipboardManager.setPrimaryClip(clipData);
});
/**
* action listener του edit για την εναρξη της δραστηριοτητας επεξεργασιας (addActivity) με βαση τα δεδομενα που υπαρχουν πανω στο cardView.
* Πριν ξεκινησει η διαδικασια, διαγραφω την εγγραφη απο την βαση και κραταω τα στοιχεια προσωρινα στη νεα δραστηριοτητα.
*/
edit.setOnClickListener(v -> {
DataBase db=DataBase.getInstance(c);
Intent edit=new Intent(c, AddActivity.class);
edit.putExtra("AppUser",appUser);
edit.putExtra("Title",cardTitle.getText());
edit.putExtra("Username",username.getText());
edit.putExtra("Password",passwordText);
db.deleteUserContext(appUser,cardTitle.getText().toString());
edit.putExtra("flag",false);//ενα φλαγκ που μου επιτρεπει οταν ξεκινησει το activity addActivity να διαχωρισω αν ειναι εντιντ ή απλη προσθηκη
c.startActivity(edit);
});
/**
* action listener του delete για την διαγραφη των στοιχειων της καρτας απο την βαση και στην συνεχεια ανανέωση του RecycleView.
*/
delete.setOnClickListener(v -> {
DataBase db=DataBase.getInstance(c);
db.deleteUserContext(appUser,cardTitle.getText().toString());
db.close();
AccountActivity activity= (AccountActivity) c;
activity.onResume();
});
/**
* action listener του imageView για την εμφανιση ή την αποκρυψη του περιεχομενου του textView password.
*/
imageView.setOnClickListener(v -> {
if(PasswordVisibilityflag){
passwordText=password.getText().toString();
imageView.setImageResource(R.drawable.closed);
password.setText("*********");
}
else {
imageView.setImageResource(R.drawable.open);
password.setText(passwordText);
}
PasswordVisibilityflag =!PasswordVisibilityflag;
});
}
}
}
|
thanoskiver/ForgetIt
|
app/src/main/java/com/example/forgetit/RecycleAdapter.java
| 3,643
|
//2 κουμπια-εικονες για την λειτουργια της επεξεργασιας μιας καρτας και διαγραφη της.
|
line_comment
|
el
|
package com.example.forgetit;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
/**
* recycle view ου περιεχει καρτες του χρηστη και εμφανιζεται στην δραστηριοτητα
* account.
*/
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.ViewHolder> {
/**
* κενος κατασκευαστης (duh)
*/
public RecycleAdapter(){
}
static Context c;
static String appUser;
Map<String,ArrayList<String>> data;//λεξικα
ArrayList<String> keys;//λιστα με τα κλειδια του λεξικου
boolean dataNullFlag;//true αν το recycleView εχει δεδομενα να παρουσιασει, false δεν εχει.
/**
* Αν το data ειναι null αυτο σημαινει πως ο χρηστης δεν εχει δεδομενα αποθηκευμενα και χρειαζεται ειδικη μεταχειριση. Το dataNullFlag λαμβανει την τιμη false.
*
* Διαφορετικα δεχομαστε ενα γεματο λεξικο, απο αυτο αποθηκευουμε ολα τα κλειδια σε μια προσπελασιμη δομη
* @param data ειναι ενα hashMap που εχει τα δεδομενα ενος χρηστη (εχει ολες τις τριπλετες (ετικετα-ονομα_χρηστη-συνθηματικο)
* το κλειδι του λεξικου ειναι το ονομα_χρηστη και καθε κλειδι δειχνει σε μια λιστα συμβολοσειρων [συνθηματικο, ετικετα]
* @param appUser το ονομα του χρηστη που εχει εισελθει στην δραστηριοτητα account
* @param c αφορα τη δραστηριοτητα που καλεσε το recycleView στην οποια εμφανιζει τα αντιστοιχα μηνυματα προς την οθονη .
*/
public RecycleAdapter(Map<String, ArrayList<String>> data, Context c,String appUser) {
this.c=c;
this.appUser=appUser;
if (data != null)
{
dataNullFlag=false;
keys=new ArrayList<>();
Set<String> AllKeys = data.keySet();//ενα συνολο με ολα τα κλειδια
if (AllKeys.size() != 0)
{
this.data = data;
for (String name : AllKeys)
{
if (name != null)
keys.add(name);//αποθηκευω τα κλειδια σε μια προσπελασιμη δομη
}
}
}
else {
dataNullFlag=true;
}
}
@NonNull
@Override
public RecycleAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout,parent,false);//συνδεση με το περιεχομενο του RecycleView(τις καρτες)
return new ViewHolder(v);
}
/**
* καθε καρτα στην λιστα αναφερεται με αυτη την μεθοδο.
* holder ειναι ενα στοιχειο της λιστας και position η θεση του
* αναλογα με τα δεδομενα που εχουν ερθει στον κονστρακτορα γεμιζω με δεδομενα καθε στοιχειο(holder).
*
* @param holder The ViewHolder which should be updated to represent the contents of the
* item at the given position in the data set.
* @param position The position of the item within the adapter's data set.
*/
@Override
public void onBindViewHolder(@NonNull RecycleAdapter.ViewHolder holder, int position) {
if(dataNullFlag){
holder.cardTitle.setText(R.string.ADDRECORDSMESS);
holder.imageView.setVisibility(View.GONE);
holder.password.setVisibility(View.GONE);
holder.delete.setVisibility(View.INVISIBLE);
holder.edit.setVisibility(View.INVISIBLE);
holder.username.setVisibility(View.GONE);
holder.passwordCopyPaste.setVisibility(View.GONE);
holder.usernameCopyPaste.setVisibility(View.GONE);
}else{
String username= keys.get(position);
ArrayList<String> temp;
temp= data.get(username);
final int positionOfPassword=0,positionOfLabel=1;//το κλειδι του λεξικου ειναι το ονομα_χρηστη και καθε κλειδι δειχνει σε μια λιστα συμβολοσειρων [συνθηματικο,ετικετα]
if(keys.size()!=0)
{
holder.username.setText(username);
holder.password.setText(temp.get(positionOfPassword));
holder.cardTitle.setText(temp.get(positionOfLabel));
holder.imageView.performClick();
}
}
}
/**
* @return τον αριθμο των στοιχειων στην λιστα
*/
@Override
public int getItemCount() {
if( dataNullFlag) {
return 1;
}
else
return keys.size();
}
/**
* μια κλαση που αναπαριστα ενα στοιχειο της λιστας ως μια ενοτητα που αποτελειται απο
* 3 κουμπια και 3 λεζαντες(γινεται συνδεση με τα στοιχεια της καρτας)
*/
static class ViewHolder extends RecyclerView.ViewHolder{
ImageButton edit,delete;//2 κουμπια-εικονες<SUF>
ImageView imageView;
Boolean PasswordVisibilityflag;
Button usernameCopyPaste,passwordCopyPaste;//κουμπια που αντιγραφουν τα text των textView στα clipboard του κινητου.
TextView username,password,cardTitle;//λεζαντες της καρτας με το ονομα ,το συνθηματικο και τον τιτλο της καρτας.
String passwordText;//διατηρει την πραγματικη τιμη του κωδικου οταν το password textView ειναι μη ορατο.(δλδ εχει ως text "**..**"
/**
* κονστρακτορας
* @param itemView αναπαριστα ενα στοιχειο της λιστας ως μια ενοτητα
* δινονται τιμες σε καθε view που αναφερθηκε παραπανω και περιεχεται στο itemView
*/
public ViewHolder(@NonNull View itemView) {
super(itemView);
//συνδεση των στοιχειων με τα αντικειμενα της καρτας
PasswordVisibilityflag =true;
imageView=itemView.findViewById(R.id.imageView);
edit=itemView.findViewById(R.id.imageButton2);
delete=itemView.findViewById(R.id.imageButton);
username=itemView.findViewById(R.id.username);
password=itemView.findViewById(R.id.password);
cardTitle=itemView.findViewById(R.id.cardLabel);
usernameCopyPaste=itemView.findViewById(R.id.button8);
passwordCopyPaste=itemView.findViewById(R.id.button9);
/**
* action listener του κουμπιου usernameCopyPaste για την αντιγραφη του κειμενου στο username TextView στο προχειρο της συσκευης
*/
usernameCopyPaste.setOnClickListener(v->{
String textToCopy = username.getText().toString();
ClipboardManager clipboardManager = (ClipboardManager) v.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = ClipData.newPlainText("Copied Text", textToCopy);
clipboardManager.setPrimaryClip(clipData);
});
/**
* action listener του κουμπιου passwordCopyPaste για την αντιγραφη του κειμενου στο passwordText TextView στο clipboard της συσκευης
*/
passwordCopyPaste.setOnClickListener(v->{
String textToCopy = passwordText;
ClipboardManager clipboardManager = (ClipboardManager) v.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = ClipData.newPlainText("Copied Text", textToCopy);
clipboardManager.setPrimaryClip(clipData);
});
/**
* action listener του edit για την εναρξη της δραστηριοτητας επεξεργασιας (addActivity) με βαση τα δεδομενα που υπαρχουν πανω στο cardView.
* Πριν ξεκινησει η διαδικασια, διαγραφω την εγγραφη απο την βαση και κραταω τα στοιχεια προσωρινα στη νεα δραστηριοτητα.
*/
edit.setOnClickListener(v -> {
DataBase db=DataBase.getInstance(c);
Intent edit=new Intent(c, AddActivity.class);
edit.putExtra("AppUser",appUser);
edit.putExtra("Title",cardTitle.getText());
edit.putExtra("Username",username.getText());
edit.putExtra("Password",passwordText);
db.deleteUserContext(appUser,cardTitle.getText().toString());
edit.putExtra("flag",false);//ενα φλαγκ που μου επιτρεπει οταν ξεκινησει το activity addActivity να διαχωρισω αν ειναι εντιντ ή απλη προσθηκη
c.startActivity(edit);
});
/**
* action listener του delete για την διαγραφη των στοιχειων της καρτας απο την βαση και στην συνεχεια ανανέωση του RecycleView.
*/
delete.setOnClickListener(v -> {
DataBase db=DataBase.getInstance(c);
db.deleteUserContext(appUser,cardTitle.getText().toString());
db.close();
AccountActivity activity= (AccountActivity) c;
activity.onResume();
});
/**
* action listener του imageView για την εμφανιση ή την αποκρυψη του περιεχομενου του textView password.
*/
imageView.setOnClickListener(v -> {
if(PasswordVisibilityflag){
passwordText=password.getText().toString();
imageView.setImageResource(R.drawable.closed);
password.setText("*********");
}
else {
imageView.setImageResource(R.drawable.open);
password.setText(passwordText);
}
PasswordVisibilityflag =!PasswordVisibilityflag;
});
}
}
}
|
135_20
|
package gr.auth.ee.dsproject.crush.node82008561;
import gr.auth.ee.dsproject.crush.board.CrushUtilities;
import gr.auth.ee.dsproject.crush.board.Board;
import java.util.ArrayList;
public class Node82008561
{
// TODO Rename and fill the code
private Node82008561 parent; //Ο κόμβος πατέρας του κόμβου
private ArrayList<Node82008561> children; //Τα παιδιά του κόμβου
private int nodeDepth; //Το βάθος του κόμβου στο δέντρο
private int[] nodeMove; //Η κίνηση που αντιπροσωπεύει το Node
private Board nodeBoard; //Το ταμπλό του παιχνιδιού για αυτό τον κόμβο-κίνηση
private double nodeEvaluation; //Η τιμή της συνάρτησης αξιολόγησης
private int flag=0;
//----Constructors-----
//Απλός χωρίς ορίσματα
public Node82008561()
{
this.children=new ArrayList<Node82008561>();
this.nodeDepth=-1;
this.nodeMove=new int[3];
this.nodeBoard=new Board();
this.nodeEvaluation=0;
this.flag=0;
}
//Ενας constructor για την περίπτωση της ρίζας
//Η ρίζα αντιστοιχεί στην τωρινή κατάσταση,δεν έχει
//πατέρα(parent) ούτε αντιστοιχεί σε κάποια κίνηση(nodeMove)
public Node82008561(Board nodeBoard)
{
this.children=new ArrayList<Node82008561>();
this.nodeDepth=0;
this.nodeBoard=nodeBoard;
this.nodeEvaluation=0;
this.flag=0;
}
//Constructor με άμεσο καθοριζμό παραραμέτρων
public Node82008561(Node82008561 parent,int nodeDepth,int[] nodeMove,Board nodeBoard,double nodeEvaluation)
{
this.parent=parent;
this.children=new ArrayList<Node82008561>();
this.nodeDepth=nodeDepth;
this.nodeMove=nodeMove;
this.nodeBoard=nodeBoard;
this.nodeEvaluation=nodeEvaluation;
this.flag=0;
}
//Συναρτήσεις Set
public void setParent(Node82008561 parent)
{
this.parent=parent;
}
public void setChildren(Node82008561 children)
{
this.children.add(children);
}
public void setΝodeDepth(int nodeDepth)
{
this.nodeDepth=nodeDepth;
}
public void setNodeMove(int[] nodeMove)
{
this.nodeMove=nodeMove;
}
public void setNodeBoard(Board nodeBoard)
{
this.nodeBoard=nodeBoard;
}
public void setNodeEvaluation(double nodeEvaluation)
{
this.nodeEvaluation=nodeEvaluation;
}
//Συναρτήσεις Get
public Node82008561 getParent()
{
return (this.parent);
}
//Επιστροφή ενός απο τα παιδιά κόμβου
public Node82008561 getChildren(int index)
{
return (this.children.get(index));
}
//Επιστροφή ολόκληρης της λίστας των παιδιών
public ArrayList<Node82008561> getChildren()
{
return (this.children);
}
public int getNodeDepth()
{
return (this.nodeDepth);
}
public int[] getNodeMove()
{
return (this.nodeMove);
}
public Board getNodeBoard()
{
return (this.nodeBoard);
}
public double getNodeEvaluation()
{
return (this.nodeEvaluation);
}
//Συνάρτηση αξιολόγησης
public double moveEvaluation (int PlayerId){
this.flag++;
int numOfComb=0;
int earnedPoints=0;
int pointsFromRepeat=0;
boolean playAgainFlag=false;
int[] move=this.nodeMove;
int maxDepthRows=CrushUtilities.NUMBER_OF_PLAYABLE_ROWS;
int neighborX=0;
int neighborY=0;
int neighborDir=0;
int x=move[0];
int y=move[1];
//Η θέση και η κίνηση που θα κάνει το γειτονικό πλακίδιο με το οποίο θα αλλάξω θέση
if(move[2]==CrushUtilities.RIGHT) {neighborX=x+1; neighborY=y; neighborDir=CrushUtilities.LEFT;}
if(move[2]==CrushUtilities.LEFT) {neighborX=x-1; neighborY=y; neighborDir=CrushUtilities.RIGHT;}
if(move[2]==CrushUtilities.UP) {neighborX=x; neighborY=y+1; neighborDir=CrushUtilities.DOWN;}
if(move[2]==CrushUtilities.DOWN) {neighborX=x; neighborY=y-1; neighborDir=CrushUtilities.UP;}
do{//Αν βρώ πεντάρι ξανα παίζω και συνυπολογίζω και τους νέους πόντους
playAgainFlag=false;
if(earnedPoints==0)//Αν παίζω μία φορά(δηλαδή δεν έχω βρεί ακόμα πεντάρι)
{
//Πόντοι απο την μετακίνηση του δικού μου πλακιδίου
if(5==(pointsFromRepeat=numOfTilesWithSameColorWithMe(move[0],move[1],move[2],this.nodeBoard)))
{
playAgainFlag=true;
}
earnedPoints+=pointsFromRepeat;
//Πόντοι απο το γειτονικό πλακίδιο με το οποίο θα αλλάξω θέση
earnedPoints+= numOfTilesWithSameColorWithMe(neighborX,neighborY,neighborDir,this.nodeBoard);
}else{//Αν ξανα παίξω,δηλαδή βρώ πεντάρι
//Βρες τις επιτρεπτές κοινήσεις απο το board
ArrayList<int[]> availableMoves=CrushUtilities.getAvailableMoves(this.nodeBoard);
//-----Υπολόγισε την καλύτερη μου κίνηση και πρόσθεσε την ----
//----------στους πόντους της κίνησης του κόμβου--------------
int[] mv=this.nodeMove;
double[] bestMove=new double[availableMoves.size()];
for(int i=0;i<availableMoves.size();i++){
this.nodeMove=availableMoves.get(i);
bestMove[i]=moveEvaluation(PlayerId);
}
this.nodeMove=mv;
double Max=0;
for(int i=0;i<availableMoves.size();i++){
if(Max<bestMove[i]){
Max=bestMove[i];
}
}
earnedPoints+=Max;
break;
//------------------------------------------------------------
}
//Ένα αντίγραφο απο το στιγμιότυπο του ταμπλό
Board cloneBoard=CrushUtilities.boardAfterFirstCrush(this.nodeBoard,move,maxDepthRows); //<-------
//Συντελεστής πολλαπλασιασμού των αλυσιδωτών κινήσεων
double multFactor=0.5;
do
{
multFactor+=0.5;
//Υπολογίζουμε τους πόντους των αλυσιδωτών κινήσεων
if(5==(numOfComb=earnedTilesFromCombine(cloneBoard,maxDepthRows)))
{
playAgainFlag=true;
}
earnedPoints+=multFactor*numOfComb;
cloneBoard=CrushUtilities.boardAfterDeletingNples(cloneBoard,maxDepthRows);//Σπάσε τους συνδιασμόυς <--------
}while(numOfComb!=0); //Έπανάληψη μέχρι να μην έχουμε αλλους συνδιασμούς
if(flag==1){
//Ο κόμβος θα πάρει την τελική μορφή του ταμπλό μετά την κίνηση αυτή
this.nodeBoard=CrushUtilities.boardAfterFullMove(this.nodeBoard,move);
}else{
if(this.flag>1){
break;
}
}
}while(playAgainFlag);
//----Αν με την κίνηση ξεπεράσει τους 500 πόντους----
//----------ο αντίστοιχος παίκτης κερδίζει-----------
int MyScore=CrushUtilities.getOpponentsScore(PlayerId+1);
int OpponentsScore=CrushUtilities.getOpponentsScore(PlayerId);
if(((MyScore+earnedPoints)>=500)&&((this.nodeDepth&1) != 0))
{
earnedPoints=1000;
}
if(((OpponentsScore+earnedPoints)>=500)&&((this.nodeDepth&1) == 0))
{
earnedPoints=1000;
}
//---------------------------------------------------
//Ανάλογα με το αν είναι δικιά μου η κίνηση ή του αντιπάλου
//θα προσθέσουμε το αποτέλεσμα στην τιμή evaluation του πατέρα
//ή θα την αφαιρέσουμε αντίστοιχα και θα εισαγουμε το αποτέλεσμα
//στην τιμή evaluation του τρέχοντως κόμβου
//========================================================
if(flag==1){
if((this.nodeDepth&1) != 0)//Οταν βρίσκομαι σε επίπεδο δικό μου(περιττος)
{
this.nodeEvaluation+=earnedPoints;
}
else{//Αντίπαλος
this.nodeEvaluation-=earnedPoints;
}
}
//========================================================
this.flag--;
return ((double) earnedPoints);
}
//Συνάρτηση που μετράει τον αριθμό των πλακιδίων με το ίδιο χρώμα
//γύρο απο την νέα θέση ανάλογα την κατεύθυνση κίνησης
int numOfTilesWithSameColorWithMe(int x,int y,int direction,Board board)
{
int tilesWithSameColor=0;
int neighborX=0;
int neighborY=0;
//Κατεύθυνση αριστερά-δεξιά
if(direction==CrushUtilities.RIGHT||direction==CrushUtilities.LEFT)
{
if(direction==CrushUtilities.RIGHT){
neighborX=x+1;
neighborY=y;
if( ((x+3)<CrushUtilities.NUMBER_OF_COLUMNS)&&
(board.giveTileAt(x+3,neighborY).getColor()==board.giveTileAt(x, y).getColor())&&
(board.giveTileAt(x+2,neighborY).getColor()==board.giveTileAt(x, y).getColor()) )
{
tilesWithSameColor+=2;
}
}
else{
neighborX=x-1;
neighborY=y;
if( ((x-3)>=0)&&
(board.giveTileAt(x-3,neighborY).getColor()==board.giveTileAt(x, y).getColor())&&
(board.giveTileAt(x-2,neighborY).getColor()==board.giveTileAt(x, y).getColor()) )
{
tilesWithSameColor+=2;
}
}
//Ελέγχουμε το χρώμα των δύο απο -ΠΑΝΩ- πλακιδίων
if((y+1)<CrushUtilities.NUMBER_OF_PLAYABLE_ROWS)
{
if(board.giveTileAt(neighborX, y+1).getColor()==board.giveTileAt(x, y).getColor())
{
tilesWithSameColor++;
if(((y+2)<CrushUtilities.NUMBER_OF_PLAYABLE_ROWS)&& //Αν δεν έχουμε βγει απο τα όρια και
(board.giveTileAt(neighborX, y+2).getColor()==board.giveTileAt(x, y).getColor()) //εχουμε το ίδιο χρώμα πλακιδίων
){
tilesWithSameColor++;
}else if((y-1<0)||(board.giveTileAt(neighborX, y-1).getColor()!=board.giveTileAt(x, y).getColor())){
tilesWithSameColor--;
}
}
}
//Ελέγχουμε το χρώμα των δύο απο -ΚAΤΩ- πλακιδίων
if((y-1)>=0)
{
if(board.giveTileAt(neighborX, y-1).getColor()==board.giveTileAt(x, y).getColor())
{
tilesWithSameColor++;
if(((y-2)>=0)&& //Αν δεν έχουμε βγει απο τα όρια και
(board.giveTileAt(neighborX, y-2).getColor()==board.giveTileAt(x, y).getColor()) //εχουμε το ίδιο χρώμα πλακιδίων
){
tilesWithSameColor++;
}else if((y+1>=CrushUtilities.NUMBER_OF_PLAYABLE_ROWS)||(board.giveTileAt(neighborX, y+1).getColor()!=board.giveTileAt(x, y).getColor())){
tilesWithSameColor--;
}
}
}
if(tilesWithSameColor==0) return (tilesWithSameColor); //Αν ειναι το γειτονικό μπορεί να μην εχει συνδιασμο
return (tilesWithSameColor+1);
}
//Κατεύθυνση πάνω-κάτω
if(direction==CrushUtilities.UP||direction==CrushUtilities.DOWN)
{
if(direction==CrushUtilities.UP){
neighborY=y+1;
neighborX=x;
if( ((y+3)<CrushUtilities.NUMBER_OF_PLAYABLE_ROWS)&&
((y+2)<CrushUtilities.NUMBER_OF_PLAYABLE_ROWS)&&
(board.giveTileAt(neighborX, y+3).getColor()==board.giveTileAt(x, y).getColor())&&
(board.giveTileAt(neighborX, y+2).getColor()==board.giveTileAt(x, y).getColor()) ) tilesWithSameColor+=2;
}
else{
neighborY=y-1;
neighborX=x;
if( ((y-3)>=0)&&
((y-2)>0)&&
(board.giveTileAt(neighborX, y-3).getColor()==board.giveTileAt(x, y).getColor())&&
(board.giveTileAt(neighborX, y-2).getColor()==board.giveTileAt(x, y).getColor()) ) tilesWithSameColor+=2;
}
//Ελέγχουμε το χρώμα των δύο απο -ΤΑ ΔΕΞΙΑ- πλακιδίων
if((x+1)<CrushUtilities.NUMBER_OF_COLUMNS)
{
if(board.giveTileAt(x+1,neighborY).getColor()==board.giveTileAt(x, y).getColor())
{
tilesWithSameColor++;
if(((x+2)<CrushUtilities.NUMBER_OF_COLUMNS)&& //Αν δεν έχουμε βγει απο τα όρια και
(board.giveTileAt(x+2,neighborY).getColor()==board.giveTileAt(x, y).getColor()) //εχουμε το ίδιο χρώμα πλακιδίων
){
tilesWithSameColor++;
}else if((x-1<0)||board.giveTileAt(x-1,neighborY).getColor()!=board.giveTileAt(x, y).getColor()){
tilesWithSameColor--;
}
}
}
//Ελέγχουμε το χρώμα των δύο απο -ΤΑ ΑΡΙΣΤΕΡΑ- πλακιδίων
if((x-1)>=0)
{
if(board.giveTileAt(x-1,neighborY).getColor()==board.giveTileAt(x, y).getColor())
{
tilesWithSameColor++;
if(((x-2)>=0)&& //Αν δεν έχουμε βγει απο τα όρια και
(board.giveTileAt(x-2,neighborY).getColor()==board.giveTileAt(x, y).getColor()) //εχουμε το ίδιο χρώμα πλακιδίων
){
tilesWithSameColor++;
}else if((x+1>=CrushUtilities.NUMBER_OF_COLUMNS)||board.giveTileAt(x+1,neighborY).getColor()!=board.giveTileAt(x, y).getColor()){
tilesWithSameColor--;
}
}
}
if(tilesWithSameColor==0)return (tilesWithSameColor); //Αν ειναι το γειτονικό μπορεί να μην εχει συνδιασμο
return (tilesWithSameColor+1);
}
return(0);
}
//Συνάρτηση που μετράει τον αριθμό των συνδιασμός που υπάρχουν στο ταμπλό
int earnedTilesFromCombine(Board board,int nuOfRows){
int earnedPoints=0;
//Κάνουμε έλεγχο για συνδιασμούς κατα σειρές
for(int y=0;y<nuOfRows;y++) //Σειρές
{
int previousColor=board.giveTileAt(0,y).getColor();//To πρώτο στοιχείο κάθε σειράς
int count=0;
for(int x=1;x<CrushUtilities.NUMBER_OF_COLUMNS;x++) //Στήλες
{
if(previousColor==board.giveTileAt(x,y).getColor()) {
count++;
}
else{
previousColor=board.giveTileAt(x,y).getColor();
count=0;
}
if(count==2){
board.giveTileAt(x-2,y).setMark(true);
board.giveTileAt(x-1,y).setMark(true);
board.giveTileAt(x,y).setMark(true);
}
if(count>2){
board.giveTileAt(x,y).setMark(true);
}
}
}
//Κάνουμε έλεγχο για συνδιασμούς κατα στήλες
for(int x=0;x<CrushUtilities.NUMBER_OF_COLUMNS;x++) //Στήλες
{
int previousColor=board.giveTileAt(x,0).getColor();//To πρώτο στοιχείο κάθε σειράς
int count=0;
for(int y=1;y<nuOfRows;y++) //Σειρές
{
if(previousColor==board.giveTileAt(x,y).getColor()) {
count++;
}
else{
previousColor=board.giveTileAt(x,y).getColor();
count=0;
}
if(count==2){
board.giveTileAt(x,y-2).setMark(true);
board.giveTileAt(x,y-1).setMark(true);
board.giveTileAt(x,y).setMark(true);
}
if(count>2){
board.giveTileAt(x,y).setMark(true);
}
}
}
for(int x=0;x<CrushUtilities.NUMBER_OF_COLUMNS;x++) //Στήλες
{
for(int y=0;y<nuOfRows;y++) //Σειρές
{
if((board.giveTileAt(x,y).getMark()==true)&&(board.giveTileAt(x,y).getColor()!=(-1)))
{
board.giveTileAt(x,y).setMark(false);
earnedPoints++;
}
}
}
return(earnedPoints);
}
public void printBoard(int[] move,Board board)
{
System.out.println("================New Boar===============");
System.out.println();
for(int y=CrushUtilities.NUMBER_OF_PLAYABLE_ROWS-1;y>=0;y--) //Σειρές
{
for(int x=0;x<CrushUtilities.NUMBER_OF_COLUMNS;x++) //Στήλες
{
if((x==move[0])&&(y==move[1]))
{
System.out.print("(");
}else{
System.out.print(" ");
}
System.out.print(board.giveTileAt(x, y).getColor());
if((x==move[0])&&(y==move[1])){
if(move[2]==CrushUtilities.RIGHT) System.out.print("->");
if(move[2]==CrushUtilities.LEFT) System.out.print("<-");
if(move[2]==CrushUtilities.DOWN) System.out.print("__");
if(move[2]==CrushUtilities.UP) System.out.print("^^");
}else{
System.out.print(" ");
}
if((x==move[0])&&(y==move[1]))
{
System.out.print(")");
}else{
System.out.print(" ");
}
}
System.out.println();
}
System.out.println("=======================================");
System.out.println();
System.out.println();
System.out.println();
}
}
|
theompek/Candy-Crush_game
|
src/Competition/Node82008561.java
| 6,624
|
//Αν ξανα παίξω,δηλαδή βρώ πεντάρι
|
line_comment
|
el
|
package gr.auth.ee.dsproject.crush.node82008561;
import gr.auth.ee.dsproject.crush.board.CrushUtilities;
import gr.auth.ee.dsproject.crush.board.Board;
import java.util.ArrayList;
public class Node82008561
{
// TODO Rename and fill the code
private Node82008561 parent; //Ο κόμβος πατέρας του κόμβου
private ArrayList<Node82008561> children; //Τα παιδιά του κόμβου
private int nodeDepth; //Το βάθος του κόμβου στο δέντρο
private int[] nodeMove; //Η κίνηση που αντιπροσωπεύει το Node
private Board nodeBoard; //Το ταμπλό του παιχνιδιού για αυτό τον κόμβο-κίνηση
private double nodeEvaluation; //Η τιμή της συνάρτησης αξιολόγησης
private int flag=0;
//----Constructors-----
//Απλός χωρίς ορίσματα
public Node82008561()
{
this.children=new ArrayList<Node82008561>();
this.nodeDepth=-1;
this.nodeMove=new int[3];
this.nodeBoard=new Board();
this.nodeEvaluation=0;
this.flag=0;
}
//Ενας constructor για την περίπτωση της ρίζας
//Η ρίζα αντιστοιχεί στην τωρινή κατάσταση,δεν έχει
//πατέρα(parent) ούτε αντιστοιχεί σε κάποια κίνηση(nodeMove)
public Node82008561(Board nodeBoard)
{
this.children=new ArrayList<Node82008561>();
this.nodeDepth=0;
this.nodeBoard=nodeBoard;
this.nodeEvaluation=0;
this.flag=0;
}
//Constructor με άμεσο καθοριζμό παραραμέτρων
public Node82008561(Node82008561 parent,int nodeDepth,int[] nodeMove,Board nodeBoard,double nodeEvaluation)
{
this.parent=parent;
this.children=new ArrayList<Node82008561>();
this.nodeDepth=nodeDepth;
this.nodeMove=nodeMove;
this.nodeBoard=nodeBoard;
this.nodeEvaluation=nodeEvaluation;
this.flag=0;
}
//Συναρτήσεις Set
public void setParent(Node82008561 parent)
{
this.parent=parent;
}
public void setChildren(Node82008561 children)
{
this.children.add(children);
}
public void setΝodeDepth(int nodeDepth)
{
this.nodeDepth=nodeDepth;
}
public void setNodeMove(int[] nodeMove)
{
this.nodeMove=nodeMove;
}
public void setNodeBoard(Board nodeBoard)
{
this.nodeBoard=nodeBoard;
}
public void setNodeEvaluation(double nodeEvaluation)
{
this.nodeEvaluation=nodeEvaluation;
}
//Συναρτήσεις Get
public Node82008561 getParent()
{
return (this.parent);
}
//Επιστροφή ενός απο τα παιδιά κόμβου
public Node82008561 getChildren(int index)
{
return (this.children.get(index));
}
//Επιστροφή ολόκληρης της λίστας των παιδιών
public ArrayList<Node82008561> getChildren()
{
return (this.children);
}
public int getNodeDepth()
{
return (this.nodeDepth);
}
public int[] getNodeMove()
{
return (this.nodeMove);
}
public Board getNodeBoard()
{
return (this.nodeBoard);
}
public double getNodeEvaluation()
{
return (this.nodeEvaluation);
}
//Συνάρτηση αξιολόγησης
public double moveEvaluation (int PlayerId){
this.flag++;
int numOfComb=0;
int earnedPoints=0;
int pointsFromRepeat=0;
boolean playAgainFlag=false;
int[] move=this.nodeMove;
int maxDepthRows=CrushUtilities.NUMBER_OF_PLAYABLE_ROWS;
int neighborX=0;
int neighborY=0;
int neighborDir=0;
int x=move[0];
int y=move[1];
//Η θέση και η κίνηση που θα κάνει το γειτονικό πλακίδιο με το οποίο θα αλλάξω θέση
if(move[2]==CrushUtilities.RIGHT) {neighborX=x+1; neighborY=y; neighborDir=CrushUtilities.LEFT;}
if(move[2]==CrushUtilities.LEFT) {neighborX=x-1; neighborY=y; neighborDir=CrushUtilities.RIGHT;}
if(move[2]==CrushUtilities.UP) {neighborX=x; neighborY=y+1; neighborDir=CrushUtilities.DOWN;}
if(move[2]==CrushUtilities.DOWN) {neighborX=x; neighborY=y-1; neighborDir=CrushUtilities.UP;}
do{//Αν βρώ πεντάρι ξανα παίζω και συνυπολογίζω και τους νέους πόντους
playAgainFlag=false;
if(earnedPoints==0)//Αν παίζω μία φορά(δηλαδή δεν έχω βρεί ακόμα πεντάρι)
{
//Πόντοι απο την μετακίνηση του δικού μου πλακιδίου
if(5==(pointsFromRepeat=numOfTilesWithSameColorWithMe(move[0],move[1],move[2],this.nodeBoard)))
{
playAgainFlag=true;
}
earnedPoints+=pointsFromRepeat;
//Πόντοι απο το γειτονικό πλακίδιο με το οποίο θα αλλάξω θέση
earnedPoints+= numOfTilesWithSameColorWithMe(neighborX,neighborY,neighborDir,this.nodeBoard);
}else{//Αν ξανα<SUF>
//Βρες τις επιτρεπτές κοινήσεις απο το board
ArrayList<int[]> availableMoves=CrushUtilities.getAvailableMoves(this.nodeBoard);
//-----Υπολόγισε την καλύτερη μου κίνηση και πρόσθεσε την ----
//----------στους πόντους της κίνησης του κόμβου--------------
int[] mv=this.nodeMove;
double[] bestMove=new double[availableMoves.size()];
for(int i=0;i<availableMoves.size();i++){
this.nodeMove=availableMoves.get(i);
bestMove[i]=moveEvaluation(PlayerId);
}
this.nodeMove=mv;
double Max=0;
for(int i=0;i<availableMoves.size();i++){
if(Max<bestMove[i]){
Max=bestMove[i];
}
}
earnedPoints+=Max;
break;
//------------------------------------------------------------
}
//Ένα αντίγραφο απο το στιγμιότυπο του ταμπλό
Board cloneBoard=CrushUtilities.boardAfterFirstCrush(this.nodeBoard,move,maxDepthRows); //<-------
//Συντελεστής πολλαπλασιασμού των αλυσιδωτών κινήσεων
double multFactor=0.5;
do
{
multFactor+=0.5;
//Υπολογίζουμε τους πόντους των αλυσιδωτών κινήσεων
if(5==(numOfComb=earnedTilesFromCombine(cloneBoard,maxDepthRows)))
{
playAgainFlag=true;
}
earnedPoints+=multFactor*numOfComb;
cloneBoard=CrushUtilities.boardAfterDeletingNples(cloneBoard,maxDepthRows);//Σπάσε τους συνδιασμόυς <--------
}while(numOfComb!=0); //Έπανάληψη μέχρι να μην έχουμε αλλους συνδιασμούς
if(flag==1){
//Ο κόμβος θα πάρει την τελική μορφή του ταμπλό μετά την κίνηση αυτή
this.nodeBoard=CrushUtilities.boardAfterFullMove(this.nodeBoard,move);
}else{
if(this.flag>1){
break;
}
}
}while(playAgainFlag);
//----Αν με την κίνηση ξεπεράσει τους 500 πόντους----
//----------ο αντίστοιχος παίκτης κερδίζει-----------
int MyScore=CrushUtilities.getOpponentsScore(PlayerId+1);
int OpponentsScore=CrushUtilities.getOpponentsScore(PlayerId);
if(((MyScore+earnedPoints)>=500)&&((this.nodeDepth&1) != 0))
{
earnedPoints=1000;
}
if(((OpponentsScore+earnedPoints)>=500)&&((this.nodeDepth&1) == 0))
{
earnedPoints=1000;
}
//---------------------------------------------------
//Ανάλογα με το αν είναι δικιά μου η κίνηση ή του αντιπάλου
//θα προσθέσουμε το αποτέλεσμα στην τιμή evaluation του πατέρα
//ή θα την αφαιρέσουμε αντίστοιχα και θα εισαγουμε το αποτέλεσμα
//στην τιμή evaluation του τρέχοντως κόμβου
//========================================================
if(flag==1){
if((this.nodeDepth&1) != 0)//Οταν βρίσκομαι σε επίπεδο δικό μου(περιττος)
{
this.nodeEvaluation+=earnedPoints;
}
else{//Αντίπαλος
this.nodeEvaluation-=earnedPoints;
}
}
//========================================================
this.flag--;
return ((double) earnedPoints);
}
//Συνάρτηση που μετράει τον αριθμό των πλακιδίων με το ίδιο χρώμα
//γύρο απο την νέα θέση ανάλογα την κατεύθυνση κίνησης
int numOfTilesWithSameColorWithMe(int x,int y,int direction,Board board)
{
int tilesWithSameColor=0;
int neighborX=0;
int neighborY=0;
//Κατεύθυνση αριστερά-δεξιά
if(direction==CrushUtilities.RIGHT||direction==CrushUtilities.LEFT)
{
if(direction==CrushUtilities.RIGHT){
neighborX=x+1;
neighborY=y;
if( ((x+3)<CrushUtilities.NUMBER_OF_COLUMNS)&&
(board.giveTileAt(x+3,neighborY).getColor()==board.giveTileAt(x, y).getColor())&&
(board.giveTileAt(x+2,neighborY).getColor()==board.giveTileAt(x, y).getColor()) )
{
tilesWithSameColor+=2;
}
}
else{
neighborX=x-1;
neighborY=y;
if( ((x-3)>=0)&&
(board.giveTileAt(x-3,neighborY).getColor()==board.giveTileAt(x, y).getColor())&&
(board.giveTileAt(x-2,neighborY).getColor()==board.giveTileAt(x, y).getColor()) )
{
tilesWithSameColor+=2;
}
}
//Ελέγχουμε το χρώμα των δύο απο -ΠΑΝΩ- πλακιδίων
if((y+1)<CrushUtilities.NUMBER_OF_PLAYABLE_ROWS)
{
if(board.giveTileAt(neighborX, y+1).getColor()==board.giveTileAt(x, y).getColor())
{
tilesWithSameColor++;
if(((y+2)<CrushUtilities.NUMBER_OF_PLAYABLE_ROWS)&& //Αν δεν έχουμε βγει απο τα όρια και
(board.giveTileAt(neighborX, y+2).getColor()==board.giveTileAt(x, y).getColor()) //εχουμε το ίδιο χρώμα πλακιδίων
){
tilesWithSameColor++;
}else if((y-1<0)||(board.giveTileAt(neighborX, y-1).getColor()!=board.giveTileAt(x, y).getColor())){
tilesWithSameColor--;
}
}
}
//Ελέγχουμε το χρώμα των δύο απο -ΚAΤΩ- πλακιδίων
if((y-1)>=0)
{
if(board.giveTileAt(neighborX, y-1).getColor()==board.giveTileAt(x, y).getColor())
{
tilesWithSameColor++;
if(((y-2)>=0)&& //Αν δεν έχουμε βγει απο τα όρια και
(board.giveTileAt(neighborX, y-2).getColor()==board.giveTileAt(x, y).getColor()) //εχουμε το ίδιο χρώμα πλακιδίων
){
tilesWithSameColor++;
}else if((y+1>=CrushUtilities.NUMBER_OF_PLAYABLE_ROWS)||(board.giveTileAt(neighborX, y+1).getColor()!=board.giveTileAt(x, y).getColor())){
tilesWithSameColor--;
}
}
}
if(tilesWithSameColor==0) return (tilesWithSameColor); //Αν ειναι το γειτονικό μπορεί να μην εχει συνδιασμο
return (tilesWithSameColor+1);
}
//Κατεύθυνση πάνω-κάτω
if(direction==CrushUtilities.UP||direction==CrushUtilities.DOWN)
{
if(direction==CrushUtilities.UP){
neighborY=y+1;
neighborX=x;
if( ((y+3)<CrushUtilities.NUMBER_OF_PLAYABLE_ROWS)&&
((y+2)<CrushUtilities.NUMBER_OF_PLAYABLE_ROWS)&&
(board.giveTileAt(neighborX, y+3).getColor()==board.giveTileAt(x, y).getColor())&&
(board.giveTileAt(neighborX, y+2).getColor()==board.giveTileAt(x, y).getColor()) ) tilesWithSameColor+=2;
}
else{
neighborY=y-1;
neighborX=x;
if( ((y-3)>=0)&&
((y-2)>0)&&
(board.giveTileAt(neighborX, y-3).getColor()==board.giveTileAt(x, y).getColor())&&
(board.giveTileAt(neighborX, y-2).getColor()==board.giveTileAt(x, y).getColor()) ) tilesWithSameColor+=2;
}
//Ελέγχουμε το χρώμα των δύο απο -ΤΑ ΔΕΞΙΑ- πλακιδίων
if((x+1)<CrushUtilities.NUMBER_OF_COLUMNS)
{
if(board.giveTileAt(x+1,neighborY).getColor()==board.giveTileAt(x, y).getColor())
{
tilesWithSameColor++;
if(((x+2)<CrushUtilities.NUMBER_OF_COLUMNS)&& //Αν δεν έχουμε βγει απο τα όρια και
(board.giveTileAt(x+2,neighborY).getColor()==board.giveTileAt(x, y).getColor()) //εχουμε το ίδιο χρώμα πλακιδίων
){
tilesWithSameColor++;
}else if((x-1<0)||board.giveTileAt(x-1,neighborY).getColor()!=board.giveTileAt(x, y).getColor()){
tilesWithSameColor--;
}
}
}
//Ελέγχουμε το χρώμα των δύο απο -ΤΑ ΑΡΙΣΤΕΡΑ- πλακιδίων
if((x-1)>=0)
{
if(board.giveTileAt(x-1,neighborY).getColor()==board.giveTileAt(x, y).getColor())
{
tilesWithSameColor++;
if(((x-2)>=0)&& //Αν δεν έχουμε βγει απο τα όρια και
(board.giveTileAt(x-2,neighborY).getColor()==board.giveTileAt(x, y).getColor()) //εχουμε το ίδιο χρώμα πλακιδίων
){
tilesWithSameColor++;
}else if((x+1>=CrushUtilities.NUMBER_OF_COLUMNS)||board.giveTileAt(x+1,neighborY).getColor()!=board.giveTileAt(x, y).getColor()){
tilesWithSameColor--;
}
}
}
if(tilesWithSameColor==0)return (tilesWithSameColor); //Αν ειναι το γειτονικό μπορεί να μην εχει συνδιασμο
return (tilesWithSameColor+1);
}
return(0);
}
//Συνάρτηση που μετράει τον αριθμό των συνδιασμός που υπάρχουν στο ταμπλό
int earnedTilesFromCombine(Board board,int nuOfRows){
int earnedPoints=0;
//Κάνουμε έλεγχο για συνδιασμούς κατα σειρές
for(int y=0;y<nuOfRows;y++) //Σειρές
{
int previousColor=board.giveTileAt(0,y).getColor();//To πρώτο στοιχείο κάθε σειράς
int count=0;
for(int x=1;x<CrushUtilities.NUMBER_OF_COLUMNS;x++) //Στήλες
{
if(previousColor==board.giveTileAt(x,y).getColor()) {
count++;
}
else{
previousColor=board.giveTileAt(x,y).getColor();
count=0;
}
if(count==2){
board.giveTileAt(x-2,y).setMark(true);
board.giveTileAt(x-1,y).setMark(true);
board.giveTileAt(x,y).setMark(true);
}
if(count>2){
board.giveTileAt(x,y).setMark(true);
}
}
}
//Κάνουμε έλεγχο για συνδιασμούς κατα στήλες
for(int x=0;x<CrushUtilities.NUMBER_OF_COLUMNS;x++) //Στήλες
{
int previousColor=board.giveTileAt(x,0).getColor();//To πρώτο στοιχείο κάθε σειράς
int count=0;
for(int y=1;y<nuOfRows;y++) //Σειρές
{
if(previousColor==board.giveTileAt(x,y).getColor()) {
count++;
}
else{
previousColor=board.giveTileAt(x,y).getColor();
count=0;
}
if(count==2){
board.giveTileAt(x,y-2).setMark(true);
board.giveTileAt(x,y-1).setMark(true);
board.giveTileAt(x,y).setMark(true);
}
if(count>2){
board.giveTileAt(x,y).setMark(true);
}
}
}
for(int x=0;x<CrushUtilities.NUMBER_OF_COLUMNS;x++) //Στήλες
{
for(int y=0;y<nuOfRows;y++) //Σειρές
{
if((board.giveTileAt(x,y).getMark()==true)&&(board.giveTileAt(x,y).getColor()!=(-1)))
{
board.giveTileAt(x,y).setMark(false);
earnedPoints++;
}
}
}
return(earnedPoints);
}
public void printBoard(int[] move,Board board)
{
System.out.println("================New Boar===============");
System.out.println();
for(int y=CrushUtilities.NUMBER_OF_PLAYABLE_ROWS-1;y>=0;y--) //Σειρές
{
for(int x=0;x<CrushUtilities.NUMBER_OF_COLUMNS;x++) //Στήλες
{
if((x==move[0])&&(y==move[1]))
{
System.out.print("(");
}else{
System.out.print(" ");
}
System.out.print(board.giveTileAt(x, y).getColor());
if((x==move[0])&&(y==move[1])){
if(move[2]==CrushUtilities.RIGHT) System.out.print("->");
if(move[2]==CrushUtilities.LEFT) System.out.print("<-");
if(move[2]==CrushUtilities.DOWN) System.out.print("__");
if(move[2]==CrushUtilities.UP) System.out.print("^^");
}else{
System.out.print(" ");
}
if((x==move[0])&&(y==move[1]))
{
System.out.print(")");
}else{
System.out.print(" ");
}
}
System.out.println();
}
System.out.println("=======================================");
System.out.println();
System.out.println();
System.out.println();
}
}
|
622_6
|
/*
* Copyright 2017
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.core.io.xces;
import static org.apache.commons.io.IOUtils.closeQuietly;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import org.apache.uima.collection.CollectionException;
import org.apache.uima.fit.descriptor.MimeTypeCapability;
import org.apache.uima.fit.descriptor.ResourceMetaData;
import org.apache.uima.fit.descriptor.TypeCapability;
import org.apache.uima.fit.factory.JCasBuilder;
import org.apache.uima.jcas.JCas;
import org.dkpro.core.io.xces.models.XcesBody;
import org.dkpro.core.io.xces.models.XcesPara;
import org.dkpro.core.io.xces.models.XcesSentence;
import org.dkpro.core.io.xces.models.XcesToken;
import de.tudarmstadt.ukp.dkpro.core.api.io.JCasResourceCollectionReader_ImplBase;
import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.POS;
import de.tudarmstadt.ukp.dkpro.core.api.parameter.MimeTypes;
import de.tudarmstadt.ukp.dkpro.core.api.resources.CompressionUtils;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Lemma;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token;
import eu.openminted.share.annotations.api.DocumentationResource;
/**
* Reader for the XCES XML format.
*/
@ResourceMetaData(name = "XCES XML Reader")
@DocumentationResource("${docbase}/format-reference.html#format-${command}")
@TypeCapability(
outputs = {
"de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph",
"de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Lemma",
"de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence",
"de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token" })
@MimeTypeCapability({MimeTypes.APPLICATION_X_XCES})
public class XcesXmlReader
extends JCasResourceCollectionReader_ImplBase
{
@Override
public void getNext(JCas aJCas)
throws IOException, CollectionException
{
Resource res = nextFile();
initCas(aJCas, res);
InputStream is = null;
try {
is = CompressionUtils.getInputStream(res.getLocation(), res.getInputStream());
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(is);
JAXBContext context = JAXBContext.newInstance(XcesBody.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setEventHandler(new ValidationEventHandler()
{
@Override
public boolean handleEvent(ValidationEvent event)
{
throw new RuntimeException(event.getMessage(), event.getLinkedException());
}
});
JCasBuilder jb = new JCasBuilder(aJCas);
XMLEvent e = null;
while ((e = xmlEventReader.peek()) != null) {
if (isStartElement(e, "body")) {
try {
XcesBody paras = (XcesBody) unmarshaller
.unmarshal(xmlEventReader, XcesBody.class).getValue();
readPara(jb, paras);
}
catch (RuntimeException ex) {
System.out.println("Unable to parse XCES format: " + ex);
}
}
else {
xmlEventReader.next();
}
}
jb.close();
}
catch (XMLStreamException ex1) {
throw new IOException(ex1);
}
catch (JAXBException e1) {
throw new IOException(e1);
}
finally {
closeQuietly(is);
}
}
private void readPara(JCasBuilder jb, Object bodyObj)
{
// Below is the sample paragraph format
// <p id="p1">
// <s id="s1">
// <t id="t1" word="Αυτή" tag="PnDmFe03SgNmXx" lemma="αυτός" />
// <t id="t2" word="είναι" tag="VbMnIdPr03SgXxIpPvXx" lemma="είμαι" />
// <t id="t3" word="η" tag="AtDfFeSgNm" lemma="ο" />
// <t id="t4" word="πρώτη" tag="NmOdFeSgNmAj" lemma="πρώτος" />
// <t id="t5" word="γραμμή" tag="NoCmFeSgNm" lemma="γραμμή" />
// <t id="t6" word="." tag="PTERM_P" lemma="." />
// </s>
// </p>
if (bodyObj instanceof XcesBody) {
for (XcesPara paras : ((XcesBody) bodyObj).p) {
int paraStart = jb.getPosition();
int paraEnd = jb.getPosition();
for (XcesSentence s : paras.s) {
int sentStart = jb.getPosition();
int sentEnd = jb.getPosition();
for (int i = 0; i < s.xcesTokens.size(); i++) {
XcesToken t = s.xcesTokens.get(i);
XcesToken tnext = i + 1 == s.xcesTokens.size() ? null
: s.xcesTokens.get(i + 1);
Token token = jb.add(t.word, Token.class);
if (t.lemma != null) {
Lemma lemma = new Lemma(jb.getJCas(), token.getBegin(), token.getEnd());
lemma.setValue(t.lemma);
lemma.addToIndexes();
token.setLemma(lemma);
}
if (t.tag != null) {
POS pos = new POS(jb.getJCas(), token.getBegin(), token.getEnd());
pos.setPosValue(t.tag);
pos.addToIndexes();
token.setPos(pos);
}
sentEnd = jb.getPosition();
if (tnext == null) {
jb.add("\n");
}
if (tnext != null) {
jb.add(" ");
}
}
Sentence sent = new Sentence(jb.getJCas(), sentStart, sentEnd);
sent.addToIndexes();
paraEnd = sent.getEnd();
}
Paragraph para = new Paragraph(jb.getJCas(), paraStart, paraEnd);
para.addToIndexes();
jb.add("\n");
}
}
}
public static boolean isStartElement(XMLEvent aEvent, String aElement)
{
return aEvent.isStartElement()
&& ((StartElement) aEvent).getName().getLocalPart().equals(aElement);
}
}
|
tilmanbeck/dkpro-core
|
dkpro-core-io-xces-asl/src/main/java/org/dkpro/core/io/xces/XcesXmlReader.java
| 2,041
|
// <t id="t4" word="πρώτη" tag="NmOdFeSgNmAj" lemma="πρώτος" />
|
line_comment
|
el
|
/*
* Copyright 2017
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dkpro.core.io.xces;
import static org.apache.commons.io.IOUtils.closeQuietly;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import org.apache.uima.collection.CollectionException;
import org.apache.uima.fit.descriptor.MimeTypeCapability;
import org.apache.uima.fit.descriptor.ResourceMetaData;
import org.apache.uima.fit.descriptor.TypeCapability;
import org.apache.uima.fit.factory.JCasBuilder;
import org.apache.uima.jcas.JCas;
import org.dkpro.core.io.xces.models.XcesBody;
import org.dkpro.core.io.xces.models.XcesPara;
import org.dkpro.core.io.xces.models.XcesSentence;
import org.dkpro.core.io.xces.models.XcesToken;
import de.tudarmstadt.ukp.dkpro.core.api.io.JCasResourceCollectionReader_ImplBase;
import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.POS;
import de.tudarmstadt.ukp.dkpro.core.api.parameter.MimeTypes;
import de.tudarmstadt.ukp.dkpro.core.api.resources.CompressionUtils;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Lemma;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token;
import eu.openminted.share.annotations.api.DocumentationResource;
/**
* Reader for the XCES XML format.
*/
@ResourceMetaData(name = "XCES XML Reader")
@DocumentationResource("${docbase}/format-reference.html#format-${command}")
@TypeCapability(
outputs = {
"de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Paragraph",
"de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Lemma",
"de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence",
"de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token" })
@MimeTypeCapability({MimeTypes.APPLICATION_X_XCES})
public class XcesXmlReader
extends JCasResourceCollectionReader_ImplBase
{
@Override
public void getNext(JCas aJCas)
throws IOException, CollectionException
{
Resource res = nextFile();
initCas(aJCas, res);
InputStream is = null;
try {
is = CompressionUtils.getInputStream(res.getLocation(), res.getInputStream());
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(is);
JAXBContext context = JAXBContext.newInstance(XcesBody.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setEventHandler(new ValidationEventHandler()
{
@Override
public boolean handleEvent(ValidationEvent event)
{
throw new RuntimeException(event.getMessage(), event.getLinkedException());
}
});
JCasBuilder jb = new JCasBuilder(aJCas);
XMLEvent e = null;
while ((e = xmlEventReader.peek()) != null) {
if (isStartElement(e, "body")) {
try {
XcesBody paras = (XcesBody) unmarshaller
.unmarshal(xmlEventReader, XcesBody.class).getValue();
readPara(jb, paras);
}
catch (RuntimeException ex) {
System.out.println("Unable to parse XCES format: " + ex);
}
}
else {
xmlEventReader.next();
}
}
jb.close();
}
catch (XMLStreamException ex1) {
throw new IOException(ex1);
}
catch (JAXBException e1) {
throw new IOException(e1);
}
finally {
closeQuietly(is);
}
}
private void readPara(JCasBuilder jb, Object bodyObj)
{
// Below is the sample paragraph format
// <p id="p1">
// <s id="s1">
// <t id="t1" word="Αυτή" tag="PnDmFe03SgNmXx" lemma="αυτός" />
// <t id="t2" word="είναι" tag="VbMnIdPr03SgXxIpPvXx" lemma="είμαι" />
// <t id="t3" word="η" tag="AtDfFeSgNm" lemma="ο" />
// <t id="t4"<SUF>
// <t id="t5" word="γραμμή" tag="NoCmFeSgNm" lemma="γραμμή" />
// <t id="t6" word="." tag="PTERM_P" lemma="." />
// </s>
// </p>
if (bodyObj instanceof XcesBody) {
for (XcesPara paras : ((XcesBody) bodyObj).p) {
int paraStart = jb.getPosition();
int paraEnd = jb.getPosition();
for (XcesSentence s : paras.s) {
int sentStart = jb.getPosition();
int sentEnd = jb.getPosition();
for (int i = 0; i < s.xcesTokens.size(); i++) {
XcesToken t = s.xcesTokens.get(i);
XcesToken tnext = i + 1 == s.xcesTokens.size() ? null
: s.xcesTokens.get(i + 1);
Token token = jb.add(t.word, Token.class);
if (t.lemma != null) {
Lemma lemma = new Lemma(jb.getJCas(), token.getBegin(), token.getEnd());
lemma.setValue(t.lemma);
lemma.addToIndexes();
token.setLemma(lemma);
}
if (t.tag != null) {
POS pos = new POS(jb.getJCas(), token.getBegin(), token.getEnd());
pos.setPosValue(t.tag);
pos.addToIndexes();
token.setPos(pos);
}
sentEnd = jb.getPosition();
if (tnext == null) {
jb.add("\n");
}
if (tnext != null) {
jb.add(" ");
}
}
Sentence sent = new Sentence(jb.getJCas(), sentStart, sentEnd);
sent.addToIndexes();
paraEnd = sent.getEnd();
}
Paragraph para = new Paragraph(jb.getJCas(), paraStart, paraEnd);
para.addToIndexes();
jb.add("\n");
}
}
}
public static boolean isStartElement(XMLEvent aEvent, String aElement)
{
return aEvent.isStartElement()
&& ((StartElement) aEvent).getName().getLocalPart().equals(aElement);
}
}
|
15248_20
|
package com.leon.lamti.cc.games_activities;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import com.getkeepsafe.taptargetview.TapTargetView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.leon.lamti.cc.CanvasView;
import com.leon.lamti.cc.R;
import com.leon.lamti.cc.decoration.DividerItemDecoration;
import com.squareup.picasso.Callback;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.util.Random;
public class ShapesCopyActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
// Views
private CanvasView customCanvas;
private ConstraintLayout cl;
private ImageView image;
private Button compareB;
private FloatingActionButton bsFAB, niFAB;
// Firebase
private FirebaseDatabase firebaseDatabase;
private DatabaseReference imagesDbReference;
// Others
private Bitmap toCompareBitmap;
private ProgressDialog mProgressDialog;
private Boolean compFlag;
private String randomDbUrl;
private String randomImageKey;
// Tap Target View
private TapTargetView tapTargetView;
private SharedPreferences sharedPreferences;
private AsyncTaskRunner runner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shapes_copy);
// toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/* getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);*/
// Drawer Final
final DrawerLayout drawerFinal = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerFinal, toolbar, R.string.app_name, R.string.app_name);
drawerFinal.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.drawer_final_nav_view);
navigationView.setNavigationItemSelectedListener(this);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
drawerFinal.openDrawer(Gravity.LEFT);
}
});
// Views
customCanvas = (CanvasView) findViewById(R.id.signature_canvas);
cl = (ConstraintLayout) findViewById(R.id.activity_shapes_copy);
image = (ImageView) findViewById(R.id.csI);
compareB = (Button) findViewById(R.id.compareB);
bsFAB = (FloatingActionButton) findViewById(R.id.showBsFab);
niFAB = (FloatingActionButton) findViewById(R.id.nextImageFab);
bsFAB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mProgressDialog = new ProgressDialog( ShapesCopyActivity.this );
mProgressDialog.setMessage("Υπολογισμός ομοιοτήτων...");
mProgressDialog.setCancelable(false);
mProgressDialog.show();
runner = new AsyncTaskRunner();
runner.execute();
}
});
// Divider
Drawable dividerDrawable = ContextCompat.getDrawable(this, R.drawable.line_divider);
RecyclerView.ItemDecoration dividerItemDecoration = new DividerItemDecoration(dividerDrawable);
// Firebase init
firebaseDatabase = FirebaseDatabase.getInstance();
imagesDbReference = firebaseDatabase.getReference().child("imagesUrls");
imagesDbReference.keepSynced(true);
Random rand = new Random();
int n = rand.nextInt(24) + 1;
randomImageKey = "image" + n;
imagesDbReference.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if ( dataSnapshot.getKey().equals(randomImageKey) ) {
randomDbUrl = dataSnapshot.getValue().toString();
getFireImage(randomDbUrl);
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
niFAB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Random rand = new Random();
int n = rand.nextInt(24) + 1;
randomImageKey = "image" + n;
imagesDbReference.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if ( dataSnapshot.getKey().equals(randomImageKey) ) {
randomDbUrl = dataSnapshot.getValue().toString();
getFireImage(randomDbUrl);
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
clearCanvas();
}
});
// TapTargetView
final TapTargetView.Listener ttvListener = new TapTargetView.Listener() {
@Override
public void onTargetClick(TapTargetView view) {
tapTargetView.dismiss(true);
}
@Override
public void onTargetLongClick(TapTargetView view) {
}
};
sharedPreferences = getSharedPreferences("infoPrefs", MODE_PRIVATE);
// Tap targets
if ( sharedPreferences.getBoolean("helper", true) ) {
tapTargetView = new TapTargetView.Builder(this)
.title("Έλεγχος Ομοιότητας")
.description("Ζωγράφισε το παραπάνω σχήμα και πάτα το κουμπί για να δεις αν τα κατάφερες.")
.listener(ttvListener)
.outerCircleColor(R.color.colorPrimary)
.targetCircleColor(R.color.colorAccent)
.textColor(R.color.white)
.textTypeface(Typeface.defaultFromStyle(Typeface.NORMAL))
.dimColor(R.color.colorBlack)
.tintTarget(false)
.drawShadow(true)
.cancelable(false)
.showFor(bsFAB);
}
}
@Override
protected void onStart() {
super.onStart();
Long tm = Runtime.getRuntime().totalMemory();
Long fm = Runtime.getRuntime().freeMemory();
Log.d("TAGARA", "tm: " + tm + " / fm: " + fm);
}
@Override
protected void onStop() {
super.onStop();
//Toast.makeText(this, "onStop", Toast.LENGTH_SHORT).show();
}
@Override
public void onBackPressed() {
super.onBackPressed();
//customCanvas.recycleBitmap();
}
@Override
public void onLowMemory() {
super.onLowMemory();
Toast.makeText(ShapesCopyActivity.this, "low memory", Toast.LENGTH_SHORT).show();
}
@Override
public void onDestroy() { // could be in onPause or onStop
Picasso.with(this).cancelRequest(target);
/*if ( toCompareBitmap != null ) {
toCompareBitmap.recycle();
}
if ( customCanvas != null ) {
customCanvas.clear();
}*/
/*if ( customCanvas != null ) {
int i = customCanvas.recycleBitmap();
Log.d("TAG", "i: " + i );
customCanvas.clearCanvas();
customCanvas.destroyDrawingCache();
customCanvas.clearPreviousCanvas();
System.gc();
}*/
super.onDestroy();
}
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
private String resp;
@Override
protected String doInBackground(String... params) {
compareImages();
//isImagesSimilar();
return "resp";
}
@Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
if ( compFlag ) {
Toast.makeText(ShapesCopyActivity.this, "Συγχαρητήρια, τα κατάφερες!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ShapesCopyActivity.this, "Λάθος!", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onPreExecute() {
// Things to be done before execution of long running operation. For
// example showing ProgessDialog
}
@Override
protected void onProgressUpdate(String... text) {
// Things to be done while execution of long running operation is in
// progress. For example updating ProgessDialog
}
}
private void getFireImage( String stringUrl ) {
final Uri uri = Uri.parse(stringUrl);
Picasso.with(ShapesCopyActivity.this).load(uri).networkPolicy(NetworkPolicy.OFFLINE).fit().centerInside().into(image, new Callback() {
//Picasso.with(ShapesCopyActivity.this).load(uri).fit().centerInside().into(image, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
Picasso.with(ShapesCopyActivity.this).load(uri).fit().centerCrop().into(image);
}
});
}
public void clearCanvas() {
customCanvas.clearCanvas();
customCanvas.destroyDrawingCache();
}
public void compareImages() {
ImageView imageView = (ImageView) findViewById(R.id.csI);
imageView.buildDrawingCache();
Bitmap bmapImage = imageView.getDrawingCache();
Bitmap bmapCanvas = customCanvas.getBitmap();
compareImagesPixelToPixel(bmapImage, bmapCanvas);
}
public boolean compareImagesPixelToPixel(Bitmap i1, Bitmap i2) {
compFlag = false;
//if (i1.getHeight() != i2.getHeight()) return false;
//if (i1.getWidth() != i2.getWidth()) return false;
int pixelsMatch = 0;
int pixelsNotMatch = 0;
mainLoop:
for (int y = 0; y < i1.getHeight(); ++y) {
for (int x = 0; x < i1.getWidth(); ++x) {
//Log.d("AAA", "i1 width: " + i1.getWidth() + " / i2 width: " + i2.getWidth() + " / x: " + x );
if (i1.getPixel(x, y) != i2.getPixel(x, y)) {
//return false;
pixelsNotMatch++;
} else {
//Log.d("PIXEL", "I1 pixels: " + i1.getPixel(x,y) + " / I2 pixels: " + i2.getPixel(x,y));
//Log.d("PIXEL", "match: " + pixelsMatch + " not : " + pixelsNotMatch);
pixelsMatch++;
if ( pixelsMatch >= 5000 ) {
compFlag = true;
break mainLoop;
}
}
}
}
Log.d("PIXEL", "height: " + i1.getHeight() + " width : " + i1.getWidth());
Log.d("PIXEL", "height2: " + i2.getHeight() + " width2 : " + i2.getWidth());
Log.d("PIXEL", "final match: " + pixelsMatch + " not : " + pixelsNotMatch);
mProgressDialog.dismiss();
return true;
}
private Target target = new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
toCompareBitmap = bitmap;
//Toast.makeText(ShapesCopyActivity.this, "Bitmap loaded: " + toCompareBitmap, Toast.LENGTH_SHORT).show();
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
// Drawer
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
//CanvasView cv = (CanvasView) findViewById(R.id.signature_canvas);
switch (id) {
case R.id.small: customCanvas.changeSize(0);
customCanvas.eraser(false);
break;
case R.id.medium: customCanvas.changeSize(1);
customCanvas.eraser(false);
break;
case R.id.large: customCanvas.changeSize(2);
customCanvas.eraser(false);
break;
case R.id.black: customCanvas.changeColor(4);
customCanvas.eraser(false);
break;
case R.id.red: customCanvas.changeColor(0);
customCanvas.eraser(false);
break;
case R.id.blue: customCanvas.changeColor(1);
customCanvas.eraser(false);
break;
case R.id.green: customCanvas.changeColor(2);
customCanvas.eraser(false);
break;
case R.id.paint: customCanvas.changeColor(4);
customCanvas.eraser(false);
break;
case R.id.eraser: customCanvas.changeColor(3);
customCanvas.eraser(true);
break;
case R.id.clearAll: customCanvas.clearPreviousCanvas();
customCanvas.eraser(false);
customCanvas.destroyDrawingCache();
break;
default: break;
}
DrawerLayout drawerFinal = (DrawerLayout)findViewById(R.id.drawer_layout);
drawerFinal.closeDrawer(GravityCompat.START);
return true;
}
// Not Used
public static Bitmap drawableToBitmap (Drawable drawable) {
Bitmap bitmap = null;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if(bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
private void isImagesSimilar() {
ImageView imageView = (ImageView) findViewById(R.id.csI);
imageView.buildDrawingCache();
Bitmap bmapImage = imageView.getDrawingCache();
Bitmap bmapCanvas = customCanvas.getBitmap();
int iw = bmapImage.getWidth();
int cw = bmapCanvas.getWidth();
mProgressDialog.dismiss();
if ( cw <= ( iw + 50) ) {
compFlag = true;
//Toast.makeText(ShapesCopyActivity.this, "Συγχαρητήρια, τα κατάφερες!", Toast.LENGTH_SHORT).show();
} else {
compFlag = false;
//Toast.makeText(ShapesCopyActivity.this, "Λάθος, ξαναπροσπάθησε.", Toast.LENGTH_SHORT).show();
}
Log.d("SIMILARITIES", "iw: " + iw + ", cw: " + cw);
}
private void unloadBackground() {
if (image != null)
image.setBackgroundDrawable(null);
if (toCompareBitmap!= null) {
toCompareBitmap.recycle();
}
toCompareBitmap = null;
}
}
|
timlam9/BrainMore
|
app/src/main/java/com/leon/lamti/cc/games_activities/ShapesCopyActivity.java
| 4,113
|
//Toast.makeText(ShapesCopyActivity.this, "Συγχαρητήρια, τα κατάφερες!", Toast.LENGTH_SHORT).show();
|
line_comment
|
el
|
package com.leon.lamti.cc.games_activities;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import com.getkeepsafe.taptargetview.TapTargetView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.leon.lamti.cc.CanvasView;
import com.leon.lamti.cc.R;
import com.leon.lamti.cc.decoration.DividerItemDecoration;
import com.squareup.picasso.Callback;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.util.Random;
public class ShapesCopyActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
// Views
private CanvasView customCanvas;
private ConstraintLayout cl;
private ImageView image;
private Button compareB;
private FloatingActionButton bsFAB, niFAB;
// Firebase
private FirebaseDatabase firebaseDatabase;
private DatabaseReference imagesDbReference;
// Others
private Bitmap toCompareBitmap;
private ProgressDialog mProgressDialog;
private Boolean compFlag;
private String randomDbUrl;
private String randomImageKey;
// Tap Target View
private TapTargetView tapTargetView;
private SharedPreferences sharedPreferences;
private AsyncTaskRunner runner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shapes_copy);
// toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/* getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);*/
// Drawer Final
final DrawerLayout drawerFinal = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerFinal, toolbar, R.string.app_name, R.string.app_name);
drawerFinal.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.drawer_final_nav_view);
navigationView.setNavigationItemSelectedListener(this);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
drawerFinal.openDrawer(Gravity.LEFT);
}
});
// Views
customCanvas = (CanvasView) findViewById(R.id.signature_canvas);
cl = (ConstraintLayout) findViewById(R.id.activity_shapes_copy);
image = (ImageView) findViewById(R.id.csI);
compareB = (Button) findViewById(R.id.compareB);
bsFAB = (FloatingActionButton) findViewById(R.id.showBsFab);
niFAB = (FloatingActionButton) findViewById(R.id.nextImageFab);
bsFAB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mProgressDialog = new ProgressDialog( ShapesCopyActivity.this );
mProgressDialog.setMessage("Υπολογισμός ομοιοτήτων...");
mProgressDialog.setCancelable(false);
mProgressDialog.show();
runner = new AsyncTaskRunner();
runner.execute();
}
});
// Divider
Drawable dividerDrawable = ContextCompat.getDrawable(this, R.drawable.line_divider);
RecyclerView.ItemDecoration dividerItemDecoration = new DividerItemDecoration(dividerDrawable);
// Firebase init
firebaseDatabase = FirebaseDatabase.getInstance();
imagesDbReference = firebaseDatabase.getReference().child("imagesUrls");
imagesDbReference.keepSynced(true);
Random rand = new Random();
int n = rand.nextInt(24) + 1;
randomImageKey = "image" + n;
imagesDbReference.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if ( dataSnapshot.getKey().equals(randomImageKey) ) {
randomDbUrl = dataSnapshot.getValue().toString();
getFireImage(randomDbUrl);
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
niFAB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Random rand = new Random();
int n = rand.nextInt(24) + 1;
randomImageKey = "image" + n;
imagesDbReference.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if ( dataSnapshot.getKey().equals(randomImageKey) ) {
randomDbUrl = dataSnapshot.getValue().toString();
getFireImage(randomDbUrl);
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
clearCanvas();
}
});
// TapTargetView
final TapTargetView.Listener ttvListener = new TapTargetView.Listener() {
@Override
public void onTargetClick(TapTargetView view) {
tapTargetView.dismiss(true);
}
@Override
public void onTargetLongClick(TapTargetView view) {
}
};
sharedPreferences = getSharedPreferences("infoPrefs", MODE_PRIVATE);
// Tap targets
if ( sharedPreferences.getBoolean("helper", true) ) {
tapTargetView = new TapTargetView.Builder(this)
.title("Έλεγχος Ομοιότητας")
.description("Ζωγράφισε το παραπάνω σχήμα και πάτα το κουμπί για να δεις αν τα κατάφερες.")
.listener(ttvListener)
.outerCircleColor(R.color.colorPrimary)
.targetCircleColor(R.color.colorAccent)
.textColor(R.color.white)
.textTypeface(Typeface.defaultFromStyle(Typeface.NORMAL))
.dimColor(R.color.colorBlack)
.tintTarget(false)
.drawShadow(true)
.cancelable(false)
.showFor(bsFAB);
}
}
@Override
protected void onStart() {
super.onStart();
Long tm = Runtime.getRuntime().totalMemory();
Long fm = Runtime.getRuntime().freeMemory();
Log.d("TAGARA", "tm: " + tm + " / fm: " + fm);
}
@Override
protected void onStop() {
super.onStop();
//Toast.makeText(this, "onStop", Toast.LENGTH_SHORT).show();
}
@Override
public void onBackPressed() {
super.onBackPressed();
//customCanvas.recycleBitmap();
}
@Override
public void onLowMemory() {
super.onLowMemory();
Toast.makeText(ShapesCopyActivity.this, "low memory", Toast.LENGTH_SHORT).show();
}
@Override
public void onDestroy() { // could be in onPause or onStop
Picasso.with(this).cancelRequest(target);
/*if ( toCompareBitmap != null ) {
toCompareBitmap.recycle();
}
if ( customCanvas != null ) {
customCanvas.clear();
}*/
/*if ( customCanvas != null ) {
int i = customCanvas.recycleBitmap();
Log.d("TAG", "i: " + i );
customCanvas.clearCanvas();
customCanvas.destroyDrawingCache();
customCanvas.clearPreviousCanvas();
System.gc();
}*/
super.onDestroy();
}
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
private String resp;
@Override
protected String doInBackground(String... params) {
compareImages();
//isImagesSimilar();
return "resp";
}
@Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
if ( compFlag ) {
Toast.makeText(ShapesCopyActivity.this, "Συγχαρητήρια, τα κατάφερες!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ShapesCopyActivity.this, "Λάθος!", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onPreExecute() {
// Things to be done before execution of long running operation. For
// example showing ProgessDialog
}
@Override
protected void onProgressUpdate(String... text) {
// Things to be done while execution of long running operation is in
// progress. For example updating ProgessDialog
}
}
private void getFireImage( String stringUrl ) {
final Uri uri = Uri.parse(stringUrl);
Picasso.with(ShapesCopyActivity.this).load(uri).networkPolicy(NetworkPolicy.OFFLINE).fit().centerInside().into(image, new Callback() {
//Picasso.with(ShapesCopyActivity.this).load(uri).fit().centerInside().into(image, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
Picasso.with(ShapesCopyActivity.this).load(uri).fit().centerCrop().into(image);
}
});
}
public void clearCanvas() {
customCanvas.clearCanvas();
customCanvas.destroyDrawingCache();
}
public void compareImages() {
ImageView imageView = (ImageView) findViewById(R.id.csI);
imageView.buildDrawingCache();
Bitmap bmapImage = imageView.getDrawingCache();
Bitmap bmapCanvas = customCanvas.getBitmap();
compareImagesPixelToPixel(bmapImage, bmapCanvas);
}
public boolean compareImagesPixelToPixel(Bitmap i1, Bitmap i2) {
compFlag = false;
//if (i1.getHeight() != i2.getHeight()) return false;
//if (i1.getWidth() != i2.getWidth()) return false;
int pixelsMatch = 0;
int pixelsNotMatch = 0;
mainLoop:
for (int y = 0; y < i1.getHeight(); ++y) {
for (int x = 0; x < i1.getWidth(); ++x) {
//Log.d("AAA", "i1 width: " + i1.getWidth() + " / i2 width: " + i2.getWidth() + " / x: " + x );
if (i1.getPixel(x, y) != i2.getPixel(x, y)) {
//return false;
pixelsNotMatch++;
} else {
//Log.d("PIXEL", "I1 pixels: " + i1.getPixel(x,y) + " / I2 pixels: " + i2.getPixel(x,y));
//Log.d("PIXEL", "match: " + pixelsMatch + " not : " + pixelsNotMatch);
pixelsMatch++;
if ( pixelsMatch >= 5000 ) {
compFlag = true;
break mainLoop;
}
}
}
}
Log.d("PIXEL", "height: " + i1.getHeight() + " width : " + i1.getWidth());
Log.d("PIXEL", "height2: " + i2.getHeight() + " width2 : " + i2.getWidth());
Log.d("PIXEL", "final match: " + pixelsMatch + " not : " + pixelsNotMatch);
mProgressDialog.dismiss();
return true;
}
private Target target = new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
toCompareBitmap = bitmap;
//Toast.makeText(ShapesCopyActivity.this, "Bitmap loaded: " + toCompareBitmap, Toast.LENGTH_SHORT).show();
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
// Drawer
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
//CanvasView cv = (CanvasView) findViewById(R.id.signature_canvas);
switch (id) {
case R.id.small: customCanvas.changeSize(0);
customCanvas.eraser(false);
break;
case R.id.medium: customCanvas.changeSize(1);
customCanvas.eraser(false);
break;
case R.id.large: customCanvas.changeSize(2);
customCanvas.eraser(false);
break;
case R.id.black: customCanvas.changeColor(4);
customCanvas.eraser(false);
break;
case R.id.red: customCanvas.changeColor(0);
customCanvas.eraser(false);
break;
case R.id.blue: customCanvas.changeColor(1);
customCanvas.eraser(false);
break;
case R.id.green: customCanvas.changeColor(2);
customCanvas.eraser(false);
break;
case R.id.paint: customCanvas.changeColor(4);
customCanvas.eraser(false);
break;
case R.id.eraser: customCanvas.changeColor(3);
customCanvas.eraser(true);
break;
case R.id.clearAll: customCanvas.clearPreviousCanvas();
customCanvas.eraser(false);
customCanvas.destroyDrawingCache();
break;
default: break;
}
DrawerLayout drawerFinal = (DrawerLayout)findViewById(R.id.drawer_layout);
drawerFinal.closeDrawer(GravityCompat.START);
return true;
}
// Not Used
public static Bitmap drawableToBitmap (Drawable drawable) {
Bitmap bitmap = null;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if(bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
private void isImagesSimilar() {
ImageView imageView = (ImageView) findViewById(R.id.csI);
imageView.buildDrawingCache();
Bitmap bmapImage = imageView.getDrawingCache();
Bitmap bmapCanvas = customCanvas.getBitmap();
int iw = bmapImage.getWidth();
int cw = bmapCanvas.getWidth();
mProgressDialog.dismiss();
if ( cw <= ( iw + 50) ) {
compFlag = true;
//Toast.makeText(ShapesCopyActivity.this, "Συγχαρητήρια,<SUF>
} else {
compFlag = false;
//Toast.makeText(ShapesCopyActivity.this, "Λάθος, ξαναπροσπάθησε.", Toast.LENGTH_SHORT).show();
}
Log.d("SIMILARITIES", "iw: " + iw + ", cw: " + cw);
}
private void unloadBackground() {
if (image != null)
image.setBackgroundDrawable(null);
if (toCompareBitmap!= null) {
toCompareBitmap.recycle();
}
toCompareBitmap = null;
}
}
|
43744_50
|
package gr.uoa.di.rdf.Geographica3.runtime.sut.impl;
import gr.uoa.di.rdf.Geographica3.runtime.sys.executor.RDF4JbasedExecutor;
import gr.uoa.di.rdf.Geographica3.runtime.sys.interfaces.impl.RDF4JBasedGeographicaSystem;
import gr.uoa.di.rdf.Geographica3.runtime.resultscollector.impl.ResultException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.log4j.Logger;
import org.eclipse.rdf4j.query.QueryLanguage;
import org.eclipse.rdf4j.query.Update;
import org.eclipse.rdf4j.query.UpdateExecutionException;
import org.eclipse.rdf4j.repository.RepositoryException;
import gr.uoa.di.rdf.Geographica3.runtime.executionspecs.IExecutionSpec;
import gr.uoa.di.rdf.Geographica3.runtime.hosts.IHost;
import gr.uoa.di.rdf.Geographica3.runtime.reportspecs.IReportSpec;
import gr.uoa.di.rdf.Geographica3.runtime.resultscollector.impl.QueryEvaluationFlag;
import gr.uoa.di.rdf.Geographica3.runtime.resultscollector.impl.QueryRepResults.QueryRepResult;
import gr.uoa.di.rdf.Geographica3.runtime.sut.ISUT;
import gr.uoa.di.rdf.Geographica3.runtime.sys.interfaces.IGeographicaSystem;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import org.eclipse.rdf4j.query.QueryEvaluationException;
/**
*
* @author GeoRDFBench Creator <GeoRDFBench@Creator>
* @since 09/12/2019
*/
public abstract class RDF4JBasedSUT implements ISUT<RDF4JBasedGeographicaSystem> {
// --- Static members -----------------------------
protected static Logger logger = Logger.getLogger(RDF4JBasedSUT.class.getSimpleName());
// --- Data members ------------------------------
protected IHost host;
protected Map<String, String> sysProperties;
protected RDF4JBasedGeographicaSystem _sys;
protected IReportSpec reportSpec;
protected IExecutionSpec execSpec;
protected Map<String, String> firstBindingSetValueMap;
protected int noRecsToPause = -1; // number of scanned records after which executor thread pauses to receive main thread's interrupts
protected int noMsecsToPause = 100; // number of msecs to pause the worker thread
// --- Constructors ------------------------------
public RDF4JBasedSUT(IHost host, Map<String, String> sysProperties,
IReportSpec reportSpec, IExecutionSpec execSpec) {
this.host = host;
if (sysProperties == null) {
System.out.println("ALERT! sysProperties is NULL!");
}
this.sysProperties = sysProperties;
this.reportSpec = reportSpec;
this.execSpec = execSpec;
this.firstBindingSetValueMap = new HashMap<>();
}
// --- Data Accessors -----------------------------------
@Override
public IHost getHost() {
return host;
}
@Override
public IReportSpec getReportSpec() {
return reportSpec;
}
@Override
public IExecutionSpec getExecSpec() {
return execSpec;
}
@Override
public int getNoRecsToPause() {
return noRecsToPause;
}
@Override
public void setNoRecsToPause(int noRecsToPause) {
this.noRecsToPause = noRecsToPause;
}
@Override
public int getNoMsecsToPause() {
return noMsecsToPause;
}
@Override
public void setNoMsecsToPause(int noMsecsToPause) {
this.noMsecsToPause = noMsecsToPause;
}
// --- Methods -----------------------------------
/**
* Return the value of the binding with {@link bindingName} from the first
* BindingSet.
*
* @return a String representing the value for the binding
*/
@Override
public Map<String, String> getFirstBindingSetValueMap() {
return firstBindingSetValueMap;
}
@Override
public RDF4JBasedGeographicaSystem getSystem() {
return _sys;
}
@Override
public void initialize() {
try {
logger.info("Initializing..");
// create an RDF4JBasedGeographicaSystem instance with default constructor
this._sys = new RDF4JBasedGeographicaSystem(this.sysProperties);
} catch (RuntimeException e) {
logger.fatal("Cannot initialize " + this.getClass().getSimpleName());
logger.fatal(e.toString());
} catch (Exception ex) {
java.util.logging.Logger.getLogger(RDF4JBasedSUT.class.getName()).log(Level.SEVERE, null, ex);
}
}
// @Override
// Using Callable interface and Futures for thread management
public QueryRepResult runTimedQueryByExecutor_ORIGINAL(String query, long timeoutSecs) throws Exception {
QueryRepResult qryRepResult = new QueryRepResult(QueryRepResult.DEFAULT);
boolean isFutureDone = false;
//maintains a thread for executing the doWork method
final ExecutorService execService = Executors.newFixedThreadPool(1);
//set the execService thread working
RDF4JbasedExecutor executor = new RDF4JbasedExecutor(query, _sys,
this.reportSpec, qryRepResult);
final Future<QueryRepResult> future = execService.submit((Callable<QueryRepResult>) executor);
//check the outcome of the execService thread and limit the time allowed for it to complete
long tt1 = System.nanoTime();
long tt2 = 0;
try {
//logger.info("Future started");
/* Wait if necessary for at most <timeoutsSecs> for the computation
** to complete, and then retrieves its result, if available */
qryRepResult = future.get(timeoutSecs, TimeUnit.SECONDS);
isFutureDone = true;
} catch (InterruptedException e) { // current thread was interrupted while waiting
future.cancel(true);
logger.error(e.toString());
} catch (ExecutionException e) { // the computation threw an exception
executor.setIsOpNotsupported(true);
qryRepResult = executor.getQryRepResult();
future.cancel(true);
tt2 = System.nanoTime();
logger.error(e.toString());
} catch (TimeoutException e) { // the wait timed out
executor.setIsTimedout(true);
qryRepResult = executor.getQryRepResult();
future.cancel(true);
tt2 = System.nanoTime();
logger.info("Time out occurred!");
this.restart();
// this.close();
} catch (QueryEvaluationException e) {
logger.error(e.toString());
} finally {
//logger.info("Executor shutting down the execService...");
execService.shutdown(); // Disable new tasks from being submitted
try {
//logger.info("Executor waiting for termination...");
execService.awaitTermination(timeoutSecs, TimeUnit.SECONDS);
} catch (InterruptedException e) {
logger.error(e.toString());
}
System.gc();
}
if (isFutureDone) {
this.firstBindingSetValueMap = executor.getFirstBindingSetValueMap();
return qryRepResult;
} else {
// logger.info("Future did not terminate properly ("
// + String.valueOf((executor.isIsTimedout()) ? "timed out" : (executor.isIsOpNotsupported()) ? "unsupported operation" : "unknown") + ")"
// + "\nExecutor returned (at interrupt time) query repetition result: " + qryRepResult.toString()
// + "\nExecutor returned (NOW) query repetition result: " + executor.getQryRepResult().toString());
if (executor.isIsOpNotsupported()) {
//logger.error("Future not done AND OperationNotSupported!");
qryRepResult.setNoResults(ResultException.UNSUPPORTED_OPERATOR.getResultException());
qryRepResult.setEvalFlag(QueryEvaluationFlag.EVALUATION_ERROR);
} else if (executor.isIsTimedout()) {
//logger.error("Future not done AND Timed out!");
qryRepResult.setNoResults(ResultException.TIMEDOUT.getResultException());
qryRepResult.setEvalFlag(QueryEvaluationFlag.EVALUATED);
}
// logger.info("Modified query repetition result is: " + qryRepResult.toString());
return qryRepResult;
}
}
@Override
// Using Runnable interface and explicit Thread management
public QueryRepResult runTimedQueryByExecutor(String query, long timeoutSecs) throws Exception {
QueryRepResult qryRepResult = new QueryRepResult(QueryRepResult.DEFAULT);
//maintains a thread for executing the doWork method
logger.info("Starting QueryExecutor thread");
long patience = timeoutSecs * (long) Math.pow(10, 9);
// int noRecsToPause = -1; // number of scanned records after which executor thread pauses to receive main thread's interrupts
// int noMsecsToPause = 100; // number of msecs to pause the worker thread
// logger.info("noRecsToPause = " + noRecsToPause + ", noMsecsToPause = " + noMsecsToPause);
RDF4JbasedExecutor executor = new RDF4JbasedExecutor(query, _sys,
this.reportSpec, qryRepResult, noRecsToPause, noMsecsToPause);
executor.setMaxQueryExecTime((int) timeoutSecs); // explicit conversion is ok!
Thread qet = new Thread(executor);
long startTime = System.nanoTime();
if (this._sys == null) {
logger.error("The _sys object is null. Cannot start executor!");
throw new Exception("[The _sys object is null. Cannot start executor!");
}
qet.start();
logger.info("Waiting for QueryExecutor thread to finish");
// boolean isFutureDone = true;
long timeoutProgressDuration; // nsecs
long timeoutProgressStep = timeoutSecs * 1000 / 4; // msecs
logger.info("Timeout progress step is " + timeoutProgressStep + " msecs");
float timeoutProgressPercentage;
while (qet.isAlive()) {
// Wait maximum of 1 second
// for MessageLoop thread
// to finish.
qet.join(timeoutProgressStep);
timeoutProgressDuration = System.nanoTime() - startTime;
timeoutProgressPercentage = timeoutProgressDuration * 100 / patience;
if ((timeoutProgressDuration > patience)) {
if (qet.isAlive()) {
qet.interrupt();
logger.info("Timeout expired! Sent interrupt to worker thread and waiting for it to join.");
// Shouldn't be long now
// -- wait indefinitely
qet.join();
}
} else {
logger.info("Percentage of expired timeout is " + timeoutProgressPercentage + " %");
}
}
this.firstBindingSetValueMap = executor.getFirstBindingSetValueMap();
System.gc();
// if (isFutureDone) {
// this.firstBindingSetValueMap = executor.getFirstBindingSetValueMap();
//// logger.info("Future did not terminate properly ("
//// + String.valueOf((executor.isIsTimedout()) ? "timed out" : (executor.isIsOpNotsupported()) ? "unsupported operation" : "unknown") + ")"
//// + "\nExecutor returned (at interrupt time) query repetition result: " + qryRepResult.toString()
//// + "\nExecutor returned (NOW) query repetition result: " + executor.getQryRepResult().toString());
// if (executor.isIsOpNotsupported()) {
// //logger.error("Future not done AND OperationNotSupported!");
// qryRepResult.setNoResults(ResultException.UNSUPPORTED_OPERATOR.getResultException());
// qryRepResult.setEvalFlag(QueryEvaluationFlag.EVALUATION_ERROR);
// } else if (executor.isIsTimedout()) {
// //logger.error("Future not done AND Timed out!");
// qryRepResult.setNoResults(ResultException.TIMEDOUT.getResultException());
// qryRepResult.setEvalFlag(QueryEvaluationFlag.EVALUATED);
// }
//// logger.info("Modified query repetition result is: " + qryRepResult.toString());
// }
return qryRepResult;
}
@Override
public long[] runUpdate(String query
) {
logger.info("Executing update...");
long t1 = System.nanoTime();
Update preparedUpdate = null;
try {
preparedUpdate = this._sys.getConnection().prepareUpdate(QueryLanguage.SPARQL, query);
} catch (RepositoryException e) {
logger.error("[RDF4J.update]", e);
}
logger.info("[RDF4J.update] executing update query: " + query);
try {
preparedUpdate.execute();
} catch (UpdateExecutionException e) {
logger.error("[RDF4J.update]", e);
}
long t2 = System.nanoTime();
logger.info("Update executed");
long[] ret = {-1, -1, t2 - t1, -1};
return ret;
}
@Override
public void close() {
logger.info("Closing..");
try {
if (_sys != null) {
_sys.close();
_sys = null;
} else {
logger.info("There is no instance of " + this.getClass().getSimpleName());
}
this.firstBindingSetValueMap = null;
} catch (Exception e) {
logger.error("TODO - Handle this Exception!");
e.printStackTrace();
}
// TODO - Να ελέγξω ποιός και τί ήθελε να κάνει!
// Runtime run = Runtime.getRuntime();
// Process pr = run.exec(restart_script);
// pr.waitFor();
//
System.gc();
try {
Thread.sleep(this.execSpec.getClearCacheDelaymSecs()); // TODO use different parameter for Java GC
} catch (InterruptedException e) {
logger.fatal("Cannot clear caches");
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
logger.fatal(stacktrace);
}
logger.info("Closed (caches not cleared)");
}
/**
* Plain RDF4JBasedSUTs have only operating system (JVM) caches to clear
*/
@Override
public void clearCaches() {
host.getOs().clearCaches(this.execSpec.getClearCacheDelaymSecs());
}
@Override
public void restart() {
Process pr;
try {
logger.info("Restarting..");
// close _sys
if (_sys != null) {
try {
_sys.close();
} catch (Exception e) {
logger.error("Exception occured while restarting RDF4J. ");
logger.debug(e.toString());
} finally {
_sys = null;
}
}
// reset important properties
this.firstBindingSetValueMap = null;
// this._sys.setInitialized(false);
this.initialize();
logger.info("RDF4J restarted");
} catch (RuntimeException e) {
logger.fatal("Cannot restart RDF4J");
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
logger.fatal(stacktrace);
}
}
// Bypass translation for RDF4J
@Override
public String translateQuery(String query, String label
) {
return query;
}
@Override
public IGeographicaSystem getGeographicaSystem() {
return this._sys;
}
/**
* By default RDF4J based SUT do not use a server component, therefore the
* default functionality is left empty.
*/
@Override
public void startServer() {
}
/**
* By default RDF4J based SUT do not use a server component, therefore the
* default functionality is left empty.
*/
@Override
public void stopServer() {
}
}
|
tioannid/geordfbench
|
runtime/src/main/java/gr/uoa/di/rdf/Geographica3/runtime/sut/impl/RDF4JBasedSUT.java
| 3,827
|
// TODO - Να ελέγξω ποιός και τί ήθελε να κάνει!
|
line_comment
|
el
|
package gr.uoa.di.rdf.Geographica3.runtime.sut.impl;
import gr.uoa.di.rdf.Geographica3.runtime.sys.executor.RDF4JbasedExecutor;
import gr.uoa.di.rdf.Geographica3.runtime.sys.interfaces.impl.RDF4JBasedGeographicaSystem;
import gr.uoa.di.rdf.Geographica3.runtime.resultscollector.impl.ResultException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.log4j.Logger;
import org.eclipse.rdf4j.query.QueryLanguage;
import org.eclipse.rdf4j.query.Update;
import org.eclipse.rdf4j.query.UpdateExecutionException;
import org.eclipse.rdf4j.repository.RepositoryException;
import gr.uoa.di.rdf.Geographica3.runtime.executionspecs.IExecutionSpec;
import gr.uoa.di.rdf.Geographica3.runtime.hosts.IHost;
import gr.uoa.di.rdf.Geographica3.runtime.reportspecs.IReportSpec;
import gr.uoa.di.rdf.Geographica3.runtime.resultscollector.impl.QueryEvaluationFlag;
import gr.uoa.di.rdf.Geographica3.runtime.resultscollector.impl.QueryRepResults.QueryRepResult;
import gr.uoa.di.rdf.Geographica3.runtime.sut.ISUT;
import gr.uoa.di.rdf.Geographica3.runtime.sys.interfaces.IGeographicaSystem;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import org.eclipse.rdf4j.query.QueryEvaluationException;
/**
*
* @author GeoRDFBench Creator <GeoRDFBench@Creator>
* @since 09/12/2019
*/
public abstract class RDF4JBasedSUT implements ISUT<RDF4JBasedGeographicaSystem> {
// --- Static members -----------------------------
protected static Logger logger = Logger.getLogger(RDF4JBasedSUT.class.getSimpleName());
// --- Data members ------------------------------
protected IHost host;
protected Map<String, String> sysProperties;
protected RDF4JBasedGeographicaSystem _sys;
protected IReportSpec reportSpec;
protected IExecutionSpec execSpec;
protected Map<String, String> firstBindingSetValueMap;
protected int noRecsToPause = -1; // number of scanned records after which executor thread pauses to receive main thread's interrupts
protected int noMsecsToPause = 100; // number of msecs to pause the worker thread
// --- Constructors ------------------------------
public RDF4JBasedSUT(IHost host, Map<String, String> sysProperties,
IReportSpec reportSpec, IExecutionSpec execSpec) {
this.host = host;
if (sysProperties == null) {
System.out.println("ALERT! sysProperties is NULL!");
}
this.sysProperties = sysProperties;
this.reportSpec = reportSpec;
this.execSpec = execSpec;
this.firstBindingSetValueMap = new HashMap<>();
}
// --- Data Accessors -----------------------------------
@Override
public IHost getHost() {
return host;
}
@Override
public IReportSpec getReportSpec() {
return reportSpec;
}
@Override
public IExecutionSpec getExecSpec() {
return execSpec;
}
@Override
public int getNoRecsToPause() {
return noRecsToPause;
}
@Override
public void setNoRecsToPause(int noRecsToPause) {
this.noRecsToPause = noRecsToPause;
}
@Override
public int getNoMsecsToPause() {
return noMsecsToPause;
}
@Override
public void setNoMsecsToPause(int noMsecsToPause) {
this.noMsecsToPause = noMsecsToPause;
}
// --- Methods -----------------------------------
/**
* Return the value of the binding with {@link bindingName} from the first
* BindingSet.
*
* @return a String representing the value for the binding
*/
@Override
public Map<String, String> getFirstBindingSetValueMap() {
return firstBindingSetValueMap;
}
@Override
public RDF4JBasedGeographicaSystem getSystem() {
return _sys;
}
@Override
public void initialize() {
try {
logger.info("Initializing..");
// create an RDF4JBasedGeographicaSystem instance with default constructor
this._sys = new RDF4JBasedGeographicaSystem(this.sysProperties);
} catch (RuntimeException e) {
logger.fatal("Cannot initialize " + this.getClass().getSimpleName());
logger.fatal(e.toString());
} catch (Exception ex) {
java.util.logging.Logger.getLogger(RDF4JBasedSUT.class.getName()).log(Level.SEVERE, null, ex);
}
}
// @Override
// Using Callable interface and Futures for thread management
public QueryRepResult runTimedQueryByExecutor_ORIGINAL(String query, long timeoutSecs) throws Exception {
QueryRepResult qryRepResult = new QueryRepResult(QueryRepResult.DEFAULT);
boolean isFutureDone = false;
//maintains a thread for executing the doWork method
final ExecutorService execService = Executors.newFixedThreadPool(1);
//set the execService thread working
RDF4JbasedExecutor executor = new RDF4JbasedExecutor(query, _sys,
this.reportSpec, qryRepResult);
final Future<QueryRepResult> future = execService.submit((Callable<QueryRepResult>) executor);
//check the outcome of the execService thread and limit the time allowed for it to complete
long tt1 = System.nanoTime();
long tt2 = 0;
try {
//logger.info("Future started");
/* Wait if necessary for at most <timeoutsSecs> for the computation
** to complete, and then retrieves its result, if available */
qryRepResult = future.get(timeoutSecs, TimeUnit.SECONDS);
isFutureDone = true;
} catch (InterruptedException e) { // current thread was interrupted while waiting
future.cancel(true);
logger.error(e.toString());
} catch (ExecutionException e) { // the computation threw an exception
executor.setIsOpNotsupported(true);
qryRepResult = executor.getQryRepResult();
future.cancel(true);
tt2 = System.nanoTime();
logger.error(e.toString());
} catch (TimeoutException e) { // the wait timed out
executor.setIsTimedout(true);
qryRepResult = executor.getQryRepResult();
future.cancel(true);
tt2 = System.nanoTime();
logger.info("Time out occurred!");
this.restart();
// this.close();
} catch (QueryEvaluationException e) {
logger.error(e.toString());
} finally {
//logger.info("Executor shutting down the execService...");
execService.shutdown(); // Disable new tasks from being submitted
try {
//logger.info("Executor waiting for termination...");
execService.awaitTermination(timeoutSecs, TimeUnit.SECONDS);
} catch (InterruptedException e) {
logger.error(e.toString());
}
System.gc();
}
if (isFutureDone) {
this.firstBindingSetValueMap = executor.getFirstBindingSetValueMap();
return qryRepResult;
} else {
// logger.info("Future did not terminate properly ("
// + String.valueOf((executor.isIsTimedout()) ? "timed out" : (executor.isIsOpNotsupported()) ? "unsupported operation" : "unknown") + ")"
// + "\nExecutor returned (at interrupt time) query repetition result: " + qryRepResult.toString()
// + "\nExecutor returned (NOW) query repetition result: " + executor.getQryRepResult().toString());
if (executor.isIsOpNotsupported()) {
//logger.error("Future not done AND OperationNotSupported!");
qryRepResult.setNoResults(ResultException.UNSUPPORTED_OPERATOR.getResultException());
qryRepResult.setEvalFlag(QueryEvaluationFlag.EVALUATION_ERROR);
} else if (executor.isIsTimedout()) {
//logger.error("Future not done AND Timed out!");
qryRepResult.setNoResults(ResultException.TIMEDOUT.getResultException());
qryRepResult.setEvalFlag(QueryEvaluationFlag.EVALUATED);
}
// logger.info("Modified query repetition result is: " + qryRepResult.toString());
return qryRepResult;
}
}
@Override
// Using Runnable interface and explicit Thread management
public QueryRepResult runTimedQueryByExecutor(String query, long timeoutSecs) throws Exception {
QueryRepResult qryRepResult = new QueryRepResult(QueryRepResult.DEFAULT);
//maintains a thread for executing the doWork method
logger.info("Starting QueryExecutor thread");
long patience = timeoutSecs * (long) Math.pow(10, 9);
// int noRecsToPause = -1; // number of scanned records after which executor thread pauses to receive main thread's interrupts
// int noMsecsToPause = 100; // number of msecs to pause the worker thread
// logger.info("noRecsToPause = " + noRecsToPause + ", noMsecsToPause = " + noMsecsToPause);
RDF4JbasedExecutor executor = new RDF4JbasedExecutor(query, _sys,
this.reportSpec, qryRepResult, noRecsToPause, noMsecsToPause);
executor.setMaxQueryExecTime((int) timeoutSecs); // explicit conversion is ok!
Thread qet = new Thread(executor);
long startTime = System.nanoTime();
if (this._sys == null) {
logger.error("The _sys object is null. Cannot start executor!");
throw new Exception("[The _sys object is null. Cannot start executor!");
}
qet.start();
logger.info("Waiting for QueryExecutor thread to finish");
// boolean isFutureDone = true;
long timeoutProgressDuration; // nsecs
long timeoutProgressStep = timeoutSecs * 1000 / 4; // msecs
logger.info("Timeout progress step is " + timeoutProgressStep + " msecs");
float timeoutProgressPercentage;
while (qet.isAlive()) {
// Wait maximum of 1 second
// for MessageLoop thread
// to finish.
qet.join(timeoutProgressStep);
timeoutProgressDuration = System.nanoTime() - startTime;
timeoutProgressPercentage = timeoutProgressDuration * 100 / patience;
if ((timeoutProgressDuration > patience)) {
if (qet.isAlive()) {
qet.interrupt();
logger.info("Timeout expired! Sent interrupt to worker thread and waiting for it to join.");
// Shouldn't be long now
// -- wait indefinitely
qet.join();
}
} else {
logger.info("Percentage of expired timeout is " + timeoutProgressPercentage + " %");
}
}
this.firstBindingSetValueMap = executor.getFirstBindingSetValueMap();
System.gc();
// if (isFutureDone) {
// this.firstBindingSetValueMap = executor.getFirstBindingSetValueMap();
//// logger.info("Future did not terminate properly ("
//// + String.valueOf((executor.isIsTimedout()) ? "timed out" : (executor.isIsOpNotsupported()) ? "unsupported operation" : "unknown") + ")"
//// + "\nExecutor returned (at interrupt time) query repetition result: " + qryRepResult.toString()
//// + "\nExecutor returned (NOW) query repetition result: " + executor.getQryRepResult().toString());
// if (executor.isIsOpNotsupported()) {
// //logger.error("Future not done AND OperationNotSupported!");
// qryRepResult.setNoResults(ResultException.UNSUPPORTED_OPERATOR.getResultException());
// qryRepResult.setEvalFlag(QueryEvaluationFlag.EVALUATION_ERROR);
// } else if (executor.isIsTimedout()) {
// //logger.error("Future not done AND Timed out!");
// qryRepResult.setNoResults(ResultException.TIMEDOUT.getResultException());
// qryRepResult.setEvalFlag(QueryEvaluationFlag.EVALUATED);
// }
//// logger.info("Modified query repetition result is: " + qryRepResult.toString());
// }
return qryRepResult;
}
@Override
public long[] runUpdate(String query
) {
logger.info("Executing update...");
long t1 = System.nanoTime();
Update preparedUpdate = null;
try {
preparedUpdate = this._sys.getConnection().prepareUpdate(QueryLanguage.SPARQL, query);
} catch (RepositoryException e) {
logger.error("[RDF4J.update]", e);
}
logger.info("[RDF4J.update] executing update query: " + query);
try {
preparedUpdate.execute();
} catch (UpdateExecutionException e) {
logger.error("[RDF4J.update]", e);
}
long t2 = System.nanoTime();
logger.info("Update executed");
long[] ret = {-1, -1, t2 - t1, -1};
return ret;
}
@Override
public void close() {
logger.info("Closing..");
try {
if (_sys != null) {
_sys.close();
_sys = null;
} else {
logger.info("There is no instance of " + this.getClass().getSimpleName());
}
this.firstBindingSetValueMap = null;
} catch (Exception e) {
logger.error("TODO - Handle this Exception!");
e.printStackTrace();
}
// TODO -<SUF>
// Runtime run = Runtime.getRuntime();
// Process pr = run.exec(restart_script);
// pr.waitFor();
//
System.gc();
try {
Thread.sleep(this.execSpec.getClearCacheDelaymSecs()); // TODO use different parameter for Java GC
} catch (InterruptedException e) {
logger.fatal("Cannot clear caches");
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
logger.fatal(stacktrace);
}
logger.info("Closed (caches not cleared)");
}
/**
* Plain RDF4JBasedSUTs have only operating system (JVM) caches to clear
*/
@Override
public void clearCaches() {
host.getOs().clearCaches(this.execSpec.getClearCacheDelaymSecs());
}
@Override
public void restart() {
Process pr;
try {
logger.info("Restarting..");
// close _sys
if (_sys != null) {
try {
_sys.close();
} catch (Exception e) {
logger.error("Exception occured while restarting RDF4J. ");
logger.debug(e.toString());
} finally {
_sys = null;
}
}
// reset important properties
this.firstBindingSetValueMap = null;
// this._sys.setInitialized(false);
this.initialize();
logger.info("RDF4J restarted");
} catch (RuntimeException e) {
logger.fatal("Cannot restart RDF4J");
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
logger.fatal(stacktrace);
}
}
// Bypass translation for RDF4J
@Override
public String translateQuery(String query, String label
) {
return query;
}
@Override
public IGeographicaSystem getGeographicaSystem() {
return this._sys;
}
/**
* By default RDF4J based SUT do not use a server component, therefore the
* default functionality is left empty.
*/
@Override
public void startServer() {
}
/**
* By default RDF4J based SUT do not use a server component, therefore the
* default functionality is left empty.
*/
@Override
public void stopServer() {
}
}
|
45862_4
|
package com.github.tminglei.bind;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.ResourceBundle;
import java.util.stream.Collectors;
import com.github.tminglei.bind.spi.*;
import static org.testng.Assert.*;
import static com.github.tminglei.bind.FrameworkUtils.*;
import static com.github.tminglei.bind.Utils.*;
public class ConstraintsTest {
private ResourceBundle bundle = ResourceBundle.getBundle("bind-messages");
private Messages messages = (key) -> bundle.getString(key);
@BeforeClass
public void start() {
System.out.println(cyan("test pre-defined constraints"));
}
// required test
@Test
public void testRequired_SingleInput() {
System.out.println(green(">> required - single input"));
Constraint required = Constraints.required();
assertEquals(required.apply("", newmap(entry("", null)), messages, new Options()._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'' is required")));
assertEquals(required.apply("", newmap(entry("", "")), messages, new Options()._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'' is required")));
assertEquals(required.apply("", newmap(entry("", "test")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
}
@Test
public void testRequired_MultiInput() {
System.out.println(green(">> required - multiple inputs"));
Constraint required = Constraints.required("%s is required");
assertEquals(required.apply("tt", newmap(entry("tt.a", "tt")), messages, new Options()._label("haha")._inputMode(InputMode.MULTIPLE)),
Collections.EMPTY_LIST);
assertEquals(required.apply("tt", newmap(entry("tt.a", null)), messages, new Options()._label("haha")._inputMode(InputMode.MULTIPLE)),
Collections.EMPTY_LIST);
assertEquals(required.apply("tt", newmap(entry("tt", null)), messages, new Options()._inputMode(InputMode.MULTIPLE)),
Arrays.asList(entry("tt", "tt is required")));
assertEquals(required.apply("tt", newmap(), messages, new Options()._inputMode(InputMode.MULTIPLE)),
Arrays.asList(entry("tt", "tt is required")));
}
@Test
public void testRequired_PloyInput() {
System.out.println(green(">> required - polymorphic input"));
Constraint required = Constraints.required("%s is required");
assertEquals(required.apply("tt", newmap(entry("tt.a", "tt")), messages, new Options()._label("haha")._inputMode(InputMode.POLYMORPHIC)),
Collections.EMPTY_LIST);
assertEquals(required.apply("tt", newmap(entry("tt.a", null)), messages, new Options()._label("haha")._inputMode(InputMode.POLYMORPHIC)),
Collections.EMPTY_LIST);
assertEquals(required.apply("tt", newmap(entry("tt", null)), messages, new Options()._inputMode(InputMode.POLYMORPHIC)),
Arrays.asList(entry("tt", "tt is required")));
assertEquals(required.apply("tt.a", newmap(entry("tt.a", null)), messages, new Options()._inputMode(InputMode.POLYMORPHIC)),
Arrays.asList(entry("tt.a", "a is required")));
}
// max length test
@Test
public void testMaxLength_SimpleUse() {
System.out.println(green(">> max length - simple use"));
Constraint maxlength = Constraints.maxLength(10);
assertEquals(maxlength.apply("", newmap(entry("", "wetyyuu")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
assertEquals(maxlength.apply("", newmap(entry("", "wetyettyiiie")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'wetyettyiiie' must be shorter than 10 characters (include boundary: true)")));
assertEquals(maxlength.apply("", newmap(entry("", "tuewerri97")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
}
@Test
public void testMaxLength_WithCustomMessage() {
System.out.println(green(">> max length - with custom message"));
Constraint maxlength = Constraints.maxLength(10, "'%s': length > %d");
assertEquals(maxlength.apply("", newmap(entry("", "eewryuooerjhy")), messages, new Options()._label("haha")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'eewryuooerjhy': length > 10")));
}
// min length test
@Test
public void testMinLength_SimpleUse() {
System.out.println(green(">> min length - simple use"));
Constraint minlength = Constraints.minLength(3);
assertEquals(minlength.apply("", newmap(entry("", "er")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'er' must be longer than 3 characters (include boundary: true)")));
assertEquals(minlength.apply("", newmap(entry("", "ert6")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
assertEquals(minlength.apply("", newmap(entry("", "tee")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
}
@Test
public void testMinLength_WithoutBoundary() {
System.out.println(green(">> min length - w/o boundary"));
Constraint minlength = Constraints.minLength(3, false);
assertEquals(minlength.apply("", newmap(entry("", "er")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'er' must be longer than 3 characters (include boundary: false)")));
assertEquals(minlength.apply("", newmap(entry("", "ert6")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
assertEquals(minlength.apply("", newmap(entry("", "tee")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'tee' must be longer than 3 characters (include boundary: false)")));
}
@Test
public void testMinLength_WithCustomMessage() {
System.out.println(green(">> min length - custom message"));
Constraint minlength = Constraints.minLength(3, "'%s': length cannot < %d");
assertEquals(minlength.apply("", newmap(entry("", "te")), messages, new Options()._label("haha")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'te': length cannot < 3")));
}
// length test
@Test
public void testLength_SimpleUse() {
System.out.println(green(">> length - simple use"));
Constraint length = Constraints.length(9);
assertEquals(length.apply("", newmap(entry("", "123456789")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
assertEquals(length.apply("", newmap(entry("", "123")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'123' must be 9 characters")));
assertEquals(length.apply("", newmap(entry("", "1234567890")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'1234567890' must be 9 characters")));
}
@Test
public void testLength_WithCustomMessage() {
System.out.println(green(">> length - with custom message"));
Constraint length = Constraints.length(9, "'%s': length not equals to %d");
assertEquals(length.apply("", newmap(entry("", "123")), messages, new Options()._label("haha")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'123': length not equals to 9")));
}
// oneOf test
@Test
public void testOneOf_SimpleUse() {
System.out.println(green(">> one of - simple use"));
Constraint oneof = Constraints.oneOf(Arrays.asList("a", "b", "c"));
assertEquals(oneof.apply("", newmap(entry("", "a")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
assertEquals(oneof.apply("", newmap(entry("", "t")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'t' must be one of [a, b, c]")));
assertEquals(oneof.apply("", newmap(entry("", null)), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'null' must be one of [a, b, c]")));
}
@Test
public void testOneOf_WithCustomMessage() {
System.out.println(green(">> one of - with custom message"));
Constraint oneof = Constraints.oneOf(Arrays.asList("a", "b", "c"), "'%s': is not one of %s");
assertEquals(oneof.apply("t.a", newmap(entry("t.a", "ts")), messages, new Options()._label("haha")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("t.a", "'ts': is not one of [a, b, c]")));
}
// pattern test
@Test
public void testPattern_SimpleUse() {
System.out.println(green(">> pattern - simple use"));
Constraint pattern = Constraints.pattern("^(\\d+)$");
assertEquals(pattern.apply("", newmap(entry("", "1234657")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
assertEquals(pattern.apply("", newmap(entry("", "32566y")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'32566y' must be '^(\\d+)$'")));
assertEquals(pattern.apply("", newmap(entry("", "123,567")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'123,567' must be '^(\\d+)$'")));
}
@Test
public void testPattern_WithCustomMessage() {
System.out.println(green(">> pattern - with custom message"));
Constraint pattern = Constraints.pattern("^(\\d+)$", "'%s' not match '%s'");
assertEquals(pattern.apply("", newmap(entry("", "t4366")), messages, new Options()._label("haha")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'t4366' not match '^(\\d+)$'")));
}
// patternNot test
@Test
public void testPatternNot_SimpleUse() {
System.out.println(green(">> pattern not - simple use"));
Constraint patternNot = Constraints.patternNot(".*\\[(\\d*[^\\d\\[\\]]+\\d*)+\\].*");
assertEquals(patternNot.apply("", newmap(entry("", "eree.[1234657].eee")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
assertEquals(patternNot.apply("", newmap(entry("", "errr.[32566y].ereee")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'errr.[32566y].ereee' mustn't be '.*\\[(\\d*[^\\d\\[\\]]+\\d*)+\\].*'")));
}
@Test
public void testPatternNot_WithCustomMessage() {
System.out.println(green(">> pattern not - with custom message"));
Constraint patternNot = Constraints.pattern("^(\\d+)$", "'%s' contains illegal array index");
assertEquals(patternNot.apply("", newmap(entry("", "ewtr.[t4366].eweee")), messages, new Options()._label("haha")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'ewtr.[t4366].eweee' contains illegal array index")));
}
// email test
/**
* test cases copied from:
* http://en.wikipedia.org/wiki/Email_address
*/
@Test
public void testEmail_ValidEmailAddresses() {
System.out.println(green(">> email - valid email addresses"));
Constraint email = Constraints.email("'%s' not valid");
Arrays.asList(
"niceandsimple@example.com",
"very.common@example.com",
"a.little.lengthy.but.fine@dept.example.com",
"disposable.style.email.with+symbol@example.com",
"other.email-with-dash@example.com"//,
// "user@localserver",
// internationalization examples
// "Pelé@example.com", //Latin Alphabet (with diacritics)
// "δοκιμή@παράδειγμα.δοκιμή", //Greek Alphabet
// "我買@屋企.香港", //Traditional Chinese Characters
// "甲斐@黒川.日本", //Japanese Characters
// "чебурашка@ящик-с-апельсинами.рф" //Cyrillic Characters
).stream().forEach(emailAddr -> {
assertEquals(email.apply("", newmap(entry("", emailAddr)), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
});
}
@Test
public void testEmail_InvalidEmailAddresses() {
System.out.println(green(">> email - invalid email addresses"));
Constraint email = Constraints.email();
Arrays.asList(
"Abc.example.com", //(an @ character must separate the local and domain parts)
"A@b@c@example.com", //(only one @ is allowed outside quotation marks)
"a\"b(c)d,e:f;g<h>i[j\\k]l@example.com", //(none of the special characters in this local part is allowed outside quotation marks)
"just\"not\"right@example.com", //(quoted strings must be dot separated or the only element making up the local-part)
"this is\"not\\allowed@example.com", //(spaces, quotes, and backslashes may only exist when within quoted strings and preceded by a backslash)
"this\\ still\\\"not\\\\allowed@example.com", //(even if escaped (preceded by a backslash), spaces, quotes, and backslashes must still be contained by quotes)
"john..doe@example.com", //(double dot before @)
"john.doe@example..com" //(double dot after @)
).stream().forEach(emailAddr -> {
assertEquals(email.apply("", newmap(entry("", emailAddr)), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'" + emailAddr + "' is not a valid email")));
});
}
// indexInKeys test
@Test
public void testIndexInKey_SimpleUse() {
System.out.println(green(">> index in key - simple use"));
Constraint index = Constraints.indexInKeys();
assertEquals(index.apply("a", newmap(entry("a[0]", "aaa")), messages, new Options()._inputMode(InputMode.MULTIPLE)),
Collections.EMPTY_LIST);
assertEquals(index.apply("a", newmap(entry("a[t0]", "aaa"), entry("a[3]", "tew")), messages, new Options()._label("")._inputMode(InputMode.MULTIPLE)),
Arrays.asList(entry("a[t0]", "'a[t0]' contains illegal array index")));
assertEquals(index.apply("a", newmap(entry("a[t1]", "aewr"), entry("a[t4]", "ewre")), messages,
new Options()._label("xx")._inputMode(InputMode.MULTIPLE)).stream().collect(Collectors.toSet()),
Arrays.asList(entry("a[t1]", "'a[t1]' contains illegal array index"), entry("a[t4]", "'a[t4]' contains illegal array index"))
.stream().collect(Collectors.toSet()));
}
@Test
public void testIndexInKey_WithCustomMessage() {
System.out.println(green(">> index in key - with custom message"));
Constraint index = Constraints.indexInKeys("illegal array index (%s)");
assertEquals(index.apply("a", newmap(entry("a[0]", "aaa")), messages, new Options()._label("xx")._inputMode(InputMode.MULTIPLE)),
Collections.EMPTY_LIST);
assertEquals(index.apply("a", newmap(entry("a[t0]", "aaa"), entry("a[3]", "tew")), messages, new Options()._label("")._inputMode(InputMode.MULTIPLE)),
Arrays.asList(entry("a[t0]", "illegal array index (a[t0])")));
assertEquals(index.apply("", newmap(entry("a[t1]", "aewr"), entry("a[t4].er", "ewre")), messages,
new Options()._label("xx")._inputMode(InputMode.MULTIPLE)).stream().collect(Collectors.toSet()),
Arrays.asList(entry("a[t1]", "illegal array index (a[t1])"), entry("a[t4].er", "illegal array index (a[t4].er)"))
.stream().collect(Collectors.toSet()));
}
}
|
tminglei/form-binder-java
|
src/test/java/com/github/tminglei/bind/ConstraintsTest.java
| 4,267
|
// "δοκιμή@παράδειγμα.δοκιμή", //Greek Alphabet
|
line_comment
|
el
|
package com.github.tminglei.bind;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.ResourceBundle;
import java.util.stream.Collectors;
import com.github.tminglei.bind.spi.*;
import static org.testng.Assert.*;
import static com.github.tminglei.bind.FrameworkUtils.*;
import static com.github.tminglei.bind.Utils.*;
public class ConstraintsTest {
private ResourceBundle bundle = ResourceBundle.getBundle("bind-messages");
private Messages messages = (key) -> bundle.getString(key);
@BeforeClass
public void start() {
System.out.println(cyan("test pre-defined constraints"));
}
// required test
@Test
public void testRequired_SingleInput() {
System.out.println(green(">> required - single input"));
Constraint required = Constraints.required();
assertEquals(required.apply("", newmap(entry("", null)), messages, new Options()._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'' is required")));
assertEquals(required.apply("", newmap(entry("", "")), messages, new Options()._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'' is required")));
assertEquals(required.apply("", newmap(entry("", "test")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
}
@Test
public void testRequired_MultiInput() {
System.out.println(green(">> required - multiple inputs"));
Constraint required = Constraints.required("%s is required");
assertEquals(required.apply("tt", newmap(entry("tt.a", "tt")), messages, new Options()._label("haha")._inputMode(InputMode.MULTIPLE)),
Collections.EMPTY_LIST);
assertEquals(required.apply("tt", newmap(entry("tt.a", null)), messages, new Options()._label("haha")._inputMode(InputMode.MULTIPLE)),
Collections.EMPTY_LIST);
assertEquals(required.apply("tt", newmap(entry("tt", null)), messages, new Options()._inputMode(InputMode.MULTIPLE)),
Arrays.asList(entry("tt", "tt is required")));
assertEquals(required.apply("tt", newmap(), messages, new Options()._inputMode(InputMode.MULTIPLE)),
Arrays.asList(entry("tt", "tt is required")));
}
@Test
public void testRequired_PloyInput() {
System.out.println(green(">> required - polymorphic input"));
Constraint required = Constraints.required("%s is required");
assertEquals(required.apply("tt", newmap(entry("tt.a", "tt")), messages, new Options()._label("haha")._inputMode(InputMode.POLYMORPHIC)),
Collections.EMPTY_LIST);
assertEquals(required.apply("tt", newmap(entry("tt.a", null)), messages, new Options()._label("haha")._inputMode(InputMode.POLYMORPHIC)),
Collections.EMPTY_LIST);
assertEquals(required.apply("tt", newmap(entry("tt", null)), messages, new Options()._inputMode(InputMode.POLYMORPHIC)),
Arrays.asList(entry("tt", "tt is required")));
assertEquals(required.apply("tt.a", newmap(entry("tt.a", null)), messages, new Options()._inputMode(InputMode.POLYMORPHIC)),
Arrays.asList(entry("tt.a", "a is required")));
}
// max length test
@Test
public void testMaxLength_SimpleUse() {
System.out.println(green(">> max length - simple use"));
Constraint maxlength = Constraints.maxLength(10);
assertEquals(maxlength.apply("", newmap(entry("", "wetyyuu")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
assertEquals(maxlength.apply("", newmap(entry("", "wetyettyiiie")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'wetyettyiiie' must be shorter than 10 characters (include boundary: true)")));
assertEquals(maxlength.apply("", newmap(entry("", "tuewerri97")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
}
@Test
public void testMaxLength_WithCustomMessage() {
System.out.println(green(">> max length - with custom message"));
Constraint maxlength = Constraints.maxLength(10, "'%s': length > %d");
assertEquals(maxlength.apply("", newmap(entry("", "eewryuooerjhy")), messages, new Options()._label("haha")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'eewryuooerjhy': length > 10")));
}
// min length test
@Test
public void testMinLength_SimpleUse() {
System.out.println(green(">> min length - simple use"));
Constraint minlength = Constraints.minLength(3);
assertEquals(minlength.apply("", newmap(entry("", "er")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'er' must be longer than 3 characters (include boundary: true)")));
assertEquals(minlength.apply("", newmap(entry("", "ert6")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
assertEquals(minlength.apply("", newmap(entry("", "tee")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
}
@Test
public void testMinLength_WithoutBoundary() {
System.out.println(green(">> min length - w/o boundary"));
Constraint minlength = Constraints.minLength(3, false);
assertEquals(minlength.apply("", newmap(entry("", "er")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'er' must be longer than 3 characters (include boundary: false)")));
assertEquals(minlength.apply("", newmap(entry("", "ert6")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
assertEquals(minlength.apply("", newmap(entry("", "tee")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'tee' must be longer than 3 characters (include boundary: false)")));
}
@Test
public void testMinLength_WithCustomMessage() {
System.out.println(green(">> min length - custom message"));
Constraint minlength = Constraints.minLength(3, "'%s': length cannot < %d");
assertEquals(minlength.apply("", newmap(entry("", "te")), messages, new Options()._label("haha")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'te': length cannot < 3")));
}
// length test
@Test
public void testLength_SimpleUse() {
System.out.println(green(">> length - simple use"));
Constraint length = Constraints.length(9);
assertEquals(length.apply("", newmap(entry("", "123456789")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
assertEquals(length.apply("", newmap(entry("", "123")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'123' must be 9 characters")));
assertEquals(length.apply("", newmap(entry("", "1234567890")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'1234567890' must be 9 characters")));
}
@Test
public void testLength_WithCustomMessage() {
System.out.println(green(">> length - with custom message"));
Constraint length = Constraints.length(9, "'%s': length not equals to %d");
assertEquals(length.apply("", newmap(entry("", "123")), messages, new Options()._label("haha")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'123': length not equals to 9")));
}
// oneOf test
@Test
public void testOneOf_SimpleUse() {
System.out.println(green(">> one of - simple use"));
Constraint oneof = Constraints.oneOf(Arrays.asList("a", "b", "c"));
assertEquals(oneof.apply("", newmap(entry("", "a")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
assertEquals(oneof.apply("", newmap(entry("", "t")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'t' must be one of [a, b, c]")));
assertEquals(oneof.apply("", newmap(entry("", null)), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'null' must be one of [a, b, c]")));
}
@Test
public void testOneOf_WithCustomMessage() {
System.out.println(green(">> one of - with custom message"));
Constraint oneof = Constraints.oneOf(Arrays.asList("a", "b", "c"), "'%s': is not one of %s");
assertEquals(oneof.apply("t.a", newmap(entry("t.a", "ts")), messages, new Options()._label("haha")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("t.a", "'ts': is not one of [a, b, c]")));
}
// pattern test
@Test
public void testPattern_SimpleUse() {
System.out.println(green(">> pattern - simple use"));
Constraint pattern = Constraints.pattern("^(\\d+)$");
assertEquals(pattern.apply("", newmap(entry("", "1234657")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
assertEquals(pattern.apply("", newmap(entry("", "32566y")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'32566y' must be '^(\\d+)$'")));
assertEquals(pattern.apply("", newmap(entry("", "123,567")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'123,567' must be '^(\\d+)$'")));
}
@Test
public void testPattern_WithCustomMessage() {
System.out.println(green(">> pattern - with custom message"));
Constraint pattern = Constraints.pattern("^(\\d+)$", "'%s' not match '%s'");
assertEquals(pattern.apply("", newmap(entry("", "t4366")), messages, new Options()._label("haha")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'t4366' not match '^(\\d+)$'")));
}
// patternNot test
@Test
public void testPatternNot_SimpleUse() {
System.out.println(green(">> pattern not - simple use"));
Constraint patternNot = Constraints.patternNot(".*\\[(\\d*[^\\d\\[\\]]+\\d*)+\\].*");
assertEquals(patternNot.apply("", newmap(entry("", "eree.[1234657].eee")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
assertEquals(patternNot.apply("", newmap(entry("", "errr.[32566y].ereee")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'errr.[32566y].ereee' mustn't be '.*\\[(\\d*[^\\d\\[\\]]+\\d*)+\\].*'")));
}
@Test
public void testPatternNot_WithCustomMessage() {
System.out.println(green(">> pattern not - with custom message"));
Constraint patternNot = Constraints.pattern("^(\\d+)$", "'%s' contains illegal array index");
assertEquals(patternNot.apply("", newmap(entry("", "ewtr.[t4366].eweee")), messages, new Options()._label("haha")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'ewtr.[t4366].eweee' contains illegal array index")));
}
// email test
/**
* test cases copied from:
* http://en.wikipedia.org/wiki/Email_address
*/
@Test
public void testEmail_ValidEmailAddresses() {
System.out.println(green(">> email - valid email addresses"));
Constraint email = Constraints.email("'%s' not valid");
Arrays.asList(
"niceandsimple@example.com",
"very.common@example.com",
"a.little.lengthy.but.fine@dept.example.com",
"disposable.style.email.with+symbol@example.com",
"other.email-with-dash@example.com"//,
// "user@localserver",
// internationalization examples
// "Pelé@example.com", //Latin Alphabet (with diacritics)
// "δοκιμή@παράδειγμα.δοκιμή", //Greek<SUF>
// "我買@屋企.香港", //Traditional Chinese Characters
// "甲斐@黒川.日本", //Japanese Characters
// "чебурашка@ящик-с-апельсинами.рф" //Cyrillic Characters
).stream().forEach(emailAddr -> {
assertEquals(email.apply("", newmap(entry("", emailAddr)), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
});
}
@Test
public void testEmail_InvalidEmailAddresses() {
System.out.println(green(">> email - invalid email addresses"));
Constraint email = Constraints.email();
Arrays.asList(
"Abc.example.com", //(an @ character must separate the local and domain parts)
"A@b@c@example.com", //(only one @ is allowed outside quotation marks)
"a\"b(c)d,e:f;g<h>i[j\\k]l@example.com", //(none of the special characters in this local part is allowed outside quotation marks)
"just\"not\"right@example.com", //(quoted strings must be dot separated or the only element making up the local-part)
"this is\"not\\allowed@example.com", //(spaces, quotes, and backslashes may only exist when within quoted strings and preceded by a backslash)
"this\\ still\\\"not\\\\allowed@example.com", //(even if escaped (preceded by a backslash), spaces, quotes, and backslashes must still be contained by quotes)
"john..doe@example.com", //(double dot before @)
"john.doe@example..com" //(double dot after @)
).stream().forEach(emailAddr -> {
assertEquals(email.apply("", newmap(entry("", emailAddr)), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'" + emailAddr + "' is not a valid email")));
});
}
// indexInKeys test
@Test
public void testIndexInKey_SimpleUse() {
System.out.println(green(">> index in key - simple use"));
Constraint index = Constraints.indexInKeys();
assertEquals(index.apply("a", newmap(entry("a[0]", "aaa")), messages, new Options()._inputMode(InputMode.MULTIPLE)),
Collections.EMPTY_LIST);
assertEquals(index.apply("a", newmap(entry("a[t0]", "aaa"), entry("a[3]", "tew")), messages, new Options()._label("")._inputMode(InputMode.MULTIPLE)),
Arrays.asList(entry("a[t0]", "'a[t0]' contains illegal array index")));
assertEquals(index.apply("a", newmap(entry("a[t1]", "aewr"), entry("a[t4]", "ewre")), messages,
new Options()._label("xx")._inputMode(InputMode.MULTIPLE)).stream().collect(Collectors.toSet()),
Arrays.asList(entry("a[t1]", "'a[t1]' contains illegal array index"), entry("a[t4]", "'a[t4]' contains illegal array index"))
.stream().collect(Collectors.toSet()));
}
@Test
public void testIndexInKey_WithCustomMessage() {
System.out.println(green(">> index in key - with custom message"));
Constraint index = Constraints.indexInKeys("illegal array index (%s)");
assertEquals(index.apply("a", newmap(entry("a[0]", "aaa")), messages, new Options()._label("xx")._inputMode(InputMode.MULTIPLE)),
Collections.EMPTY_LIST);
assertEquals(index.apply("a", newmap(entry("a[t0]", "aaa"), entry("a[3]", "tew")), messages, new Options()._label("")._inputMode(InputMode.MULTIPLE)),
Arrays.asList(entry("a[t0]", "illegal array index (a[t0])")));
assertEquals(index.apply("", newmap(entry("a[t1]", "aewr"), entry("a[t4].er", "ewre")), messages,
new Options()._label("xx")._inputMode(InputMode.MULTIPLE)).stream().collect(Collectors.toSet()),
Arrays.asList(entry("a[t1]", "illegal array index (a[t1])"), entry("a[t4].er", "illegal array index (a[t4].er)"))
.stream().collect(Collectors.toSet()));
}
}
|
6103_11
|
package greek.dev.challenge.charities.views;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
import com.sothree.slidinguppanel.SlidingUpPanelLayout.PanelSlideListener;
import com.sothree.slidinguppanel.SlidingUpPanelLayout.PanelState;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.BuildConfig;
import butterknife.ButterKnife;
import butterknife.OnClick;
import greek.dev.challenge.charities.R;
import greek.dev.challenge.charities.adapters.WishAdapter;
import greek.dev.challenge.charities.model.Wish;
import greek.dev.challenge.charities.utilities.CharitiesPreferences;
/**
* Created by nalex on 26/12/2017.
*/
public class ListWishesActivity extends AppCompatActivity {
ArrayList<Wish> wishes = new ArrayList<>();
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mCharitiesDatabaseReference; //references specific part of the database (wishes here)
private ChildEventListener mChildEventListener;
WishAdapter adapter;
private String uid;
private FirebaseAuth mAuth;
private CharitiesPreferences preferencesfManager;
private static final String TAG = "EmailPassword";
@BindView(R.id.send_wish)
public Button sendButton;
@BindView(R.id.name)
public TextView authorOfWish;
@BindView(R.id.charities_spinner)
public Spinner spinner;
@BindView(R.id.wish_text)
public TextView wishText;
@BindView(R.id.sliding_layout)
public SlidingUpPanelLayout mLayout;
@BindString(R.string.yes)
public String yesString;
@BindString(R.string.no)
public String noString;
@BindString(R.string.send_Wish_Dialog)
public String sendWishDialog;
@BindString(R.string.send_Wish_Dialog_Msg)
public String sendWishDialogMsg;
@BindString(R.string.fill_textview)
public String fillTextView;
@BindString(R.string.wish_sent)
public String wishSent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wishes);
ButterKnife.bind(this);
if (FirebaseApp.getApps(getApplicationContext()).isEmpty()) {
FirebaseApp.initializeApp(getApplicationContext());
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
}
mFirebaseDatabase = FirebaseDatabase.getInstance();
mCharitiesDatabaseReference = mFirebaseDatabase.getReference().child("wishes");
mCharitiesDatabaseReference.keepSynced(true);
attachDatabaseReadListener();
preferencesfManager = new CharitiesPreferences(this);
Log.v("ids list", preferencesfManager.getIds().toString());
uid = preferencesfManager.getCharityAp(this);
RecyclerView rvWishes = findViewById(R.id.rvWishes);
mAuth = FirebaseAuth.getInstance();
startAuth(greek.dev.challenge.charities.BuildConfig.USER_APP_ID);
adapter = new WishAdapter(this, wishes);
rvWishes.setAdapter(adapter);
setSpinnerList();
mLayout.addPanelSlideListener(new SlidingUpPanelLayout.PanelSlideListener() {
@Override
public void onPanelSlide(View panel, float slideOffset) {
Log.i(TAG, "onPanelSlide, offset " + slideOffset);
}
@Override
public void onPanelStateChanged(View panel, PanelState previousState, PanelState newState) {
// if (newState == PanelState.COLLAPSED){
// float pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics());
// int dp = Math.round(pixels);
// mLayout.setPanelHeight(dp);
// }
Log.i(TAG, "onPanelStateChanged " + newState);
}
});
StaggeredGridLayoutManager gridLayoutManager =
new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
rvWishes.setLayoutManager(gridLayoutManager);
}
private void setSpinnerList() {
ArrayList<String> namesList = preferencesfManager.getNames();
namesList.add(0, "Διαλέξτε οργανισμό:");
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(getApplicationContext(), R.layout.support_simple_spinner_dropdown_item, namesList);
adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
@OnClick(R.id.send_wish)
public void sendClick(View v) {
String author = authorOfWish.getText().toString();
String wish = wishText.getText().toString();
if (canSendWish()) {
if (!TextUtils.isEmpty(author) && !TextUtils.isEmpty(wish) && !(spinner.getSelectedItemPosition() == 0)) {
addWishToCloud(wish, author, spinner.getSelectedItem().toString());
Toast.makeText(this, wishSent, Toast.LENGTH_SHORT).show();
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
mLayout.setPanelState(PanelState.COLLAPSED);
} else {
Toast.makeText(this, fillTextView, Toast.LENGTH_SHORT).show();
}
} else {
showAlertToMakeWish();
}
}
private boolean canSendWish() {
List<String> tmpList = preferencesfManager.getIds();
return (!tmpList.isEmpty());
}
private void showAlertToMakeWish() {
AlertDialog.Builder builder = new AlertDialog.Builder(ListWishesActivity.this);
builder.setTitle(sendWishDialog);
builder.setMessage(sendWishDialogMsg);
//Yes Button
builder.setPositiveButton(yesString, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(ListWishesActivity.this, CharitiesResultsActivity.class);
startActivity(i);
dialog.dismiss();
finish();
}
});
//No Button
builder.setNegativeButton(noString, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void addWishToCloud(String wishText, String author, String charityName) {
//An if statement here is needed to check if the user has made a charity to this charity id
//Also we could check for valid size of our list and valid id
Wish wish = new Wish(wishText, author, charityName, System.currentTimeMillis());
mCharitiesDatabaseReference.push().setValue(wish);
}
@Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
}
private void signIn(String email, String password) {
Log.d(TAG, "signIn:" + email);
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithEmail:failure", task.getException());
}
}
});
}
private void attachDatabaseReadListener() {
if (mChildEventListener == null) {
mChildEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//results from database are deserialized
Wish wish = dataSnapshot.getValue(Wish.class);
wishes.add(0, wish);
adapter.notifyDataSetChanged();
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
mCharitiesDatabaseReference.addChildEventListener(mChildEventListener);
}
}
private void startAuth(String uid) {
//Τα log πρέπει να φύγουν και να γίνει uncomment η γραμμή singin με το test 2 και comment
//με το test, πριν δημοσιευθεί το signedapk
// signIn("test2@greekcharities.com",this.uid);
signIn("test@greekcharities.com", "353535");
}
private void detachDatabaseReadListener() {
if (mChildEventListener != null) {
mCharitiesDatabaseReference.removeEventListener(mChildEventListener);
mChildEventListener = null;
}
}
@Override
protected void onPause() {
super.onPause();
onSignedOutCleanup();
}
//not signed out now, but a cleanup is required onPause, so not to get duplicate EventListeners
private void onSignedOutCleanup() {
detachDatabaseReadListener();
}
}
|
tpakis/Charities
|
app/src/main/java/greek/dev/challenge/charities/views/ListWishesActivity.java
| 2,617
|
//Τα log πρέπει να φύγουν και να γίνει uncomment η γραμμή singin με το test 2 και comment
|
line_comment
|
el
|
package greek.dev.challenge.charities.views;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
import com.sothree.slidinguppanel.SlidingUpPanelLayout.PanelSlideListener;
import com.sothree.slidinguppanel.SlidingUpPanelLayout.PanelState;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.BuildConfig;
import butterknife.ButterKnife;
import butterknife.OnClick;
import greek.dev.challenge.charities.R;
import greek.dev.challenge.charities.adapters.WishAdapter;
import greek.dev.challenge.charities.model.Wish;
import greek.dev.challenge.charities.utilities.CharitiesPreferences;
/**
* Created by nalex on 26/12/2017.
*/
public class ListWishesActivity extends AppCompatActivity {
ArrayList<Wish> wishes = new ArrayList<>();
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mCharitiesDatabaseReference; //references specific part of the database (wishes here)
private ChildEventListener mChildEventListener;
WishAdapter adapter;
private String uid;
private FirebaseAuth mAuth;
private CharitiesPreferences preferencesfManager;
private static final String TAG = "EmailPassword";
@BindView(R.id.send_wish)
public Button sendButton;
@BindView(R.id.name)
public TextView authorOfWish;
@BindView(R.id.charities_spinner)
public Spinner spinner;
@BindView(R.id.wish_text)
public TextView wishText;
@BindView(R.id.sliding_layout)
public SlidingUpPanelLayout mLayout;
@BindString(R.string.yes)
public String yesString;
@BindString(R.string.no)
public String noString;
@BindString(R.string.send_Wish_Dialog)
public String sendWishDialog;
@BindString(R.string.send_Wish_Dialog_Msg)
public String sendWishDialogMsg;
@BindString(R.string.fill_textview)
public String fillTextView;
@BindString(R.string.wish_sent)
public String wishSent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wishes);
ButterKnife.bind(this);
if (FirebaseApp.getApps(getApplicationContext()).isEmpty()) {
FirebaseApp.initializeApp(getApplicationContext());
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
}
mFirebaseDatabase = FirebaseDatabase.getInstance();
mCharitiesDatabaseReference = mFirebaseDatabase.getReference().child("wishes");
mCharitiesDatabaseReference.keepSynced(true);
attachDatabaseReadListener();
preferencesfManager = new CharitiesPreferences(this);
Log.v("ids list", preferencesfManager.getIds().toString());
uid = preferencesfManager.getCharityAp(this);
RecyclerView rvWishes = findViewById(R.id.rvWishes);
mAuth = FirebaseAuth.getInstance();
startAuth(greek.dev.challenge.charities.BuildConfig.USER_APP_ID);
adapter = new WishAdapter(this, wishes);
rvWishes.setAdapter(adapter);
setSpinnerList();
mLayout.addPanelSlideListener(new SlidingUpPanelLayout.PanelSlideListener() {
@Override
public void onPanelSlide(View panel, float slideOffset) {
Log.i(TAG, "onPanelSlide, offset " + slideOffset);
}
@Override
public void onPanelStateChanged(View panel, PanelState previousState, PanelState newState) {
// if (newState == PanelState.COLLAPSED){
// float pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics());
// int dp = Math.round(pixels);
// mLayout.setPanelHeight(dp);
// }
Log.i(TAG, "onPanelStateChanged " + newState);
}
});
StaggeredGridLayoutManager gridLayoutManager =
new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
rvWishes.setLayoutManager(gridLayoutManager);
}
private void setSpinnerList() {
ArrayList<String> namesList = preferencesfManager.getNames();
namesList.add(0, "Διαλέξτε οργανισμό:");
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(getApplicationContext(), R.layout.support_simple_spinner_dropdown_item, namesList);
adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
@OnClick(R.id.send_wish)
public void sendClick(View v) {
String author = authorOfWish.getText().toString();
String wish = wishText.getText().toString();
if (canSendWish()) {
if (!TextUtils.isEmpty(author) && !TextUtils.isEmpty(wish) && !(spinner.getSelectedItemPosition() == 0)) {
addWishToCloud(wish, author, spinner.getSelectedItem().toString());
Toast.makeText(this, wishSent, Toast.LENGTH_SHORT).show();
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
mLayout.setPanelState(PanelState.COLLAPSED);
} else {
Toast.makeText(this, fillTextView, Toast.LENGTH_SHORT).show();
}
} else {
showAlertToMakeWish();
}
}
private boolean canSendWish() {
List<String> tmpList = preferencesfManager.getIds();
return (!tmpList.isEmpty());
}
private void showAlertToMakeWish() {
AlertDialog.Builder builder = new AlertDialog.Builder(ListWishesActivity.this);
builder.setTitle(sendWishDialog);
builder.setMessage(sendWishDialogMsg);
//Yes Button
builder.setPositiveButton(yesString, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(ListWishesActivity.this, CharitiesResultsActivity.class);
startActivity(i);
dialog.dismiss();
finish();
}
});
//No Button
builder.setNegativeButton(noString, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void addWishToCloud(String wishText, String author, String charityName) {
//An if statement here is needed to check if the user has made a charity to this charity id
//Also we could check for valid size of our list and valid id
Wish wish = new Wish(wishText, author, charityName, System.currentTimeMillis());
mCharitiesDatabaseReference.push().setValue(wish);
}
@Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
}
private void signIn(String email, String password) {
Log.d(TAG, "signIn:" + email);
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithEmail:failure", task.getException());
}
}
});
}
private void attachDatabaseReadListener() {
if (mChildEventListener == null) {
mChildEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//results from database are deserialized
Wish wish = dataSnapshot.getValue(Wish.class);
wishes.add(0, wish);
adapter.notifyDataSetChanged();
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
mCharitiesDatabaseReference.addChildEventListener(mChildEventListener);
}
}
private void startAuth(String uid) {
//Τα log<SUF>
//με το test, πριν δημοσιευθεί το signedapk
// signIn("test2@greekcharities.com",this.uid);
signIn("test@greekcharities.com", "353535");
}
private void detachDatabaseReadListener() {
if (mChildEventListener != null) {
mCharitiesDatabaseReference.removeEventListener(mChildEventListener);
mChildEventListener = null;
}
}
@Override
protected void onPause() {
super.onPause();
onSignedOutCleanup();
}
//not signed out now, but a cleanup is required onPause, so not to get duplicate EventListeners
private void onSignedOutCleanup() {
detachDatabaseReadListener();
}
}
|
4449_2
|
import java.awt.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
private static int PSIFOS_YPER = 1;
private static int PSIFOS_KATA = -1;
private static Grammateia gr;
public static void main(String[] args) {
//Object Creation
Lista_Aitisewn listaAitisewn = Lista_Aitisewn.ListaAitisewn();
Lista_Melwn listaMelwn = Lista_Melwn.ListaMelwn();
Lista_Eisigisewn listaEisigiseon = Lista_Eisigisewn.listaEisigiseon();
Melos m1 = new Melos("giannhs@uom.edu.gr","Mpananies");
Melos m2 = new Melos("panagiwths@uom.edu.gr","milo");
Melos m3 = new Melos("giwrgos@uom.edu.gr","aeras");
Melos m4 = new Melos("votsalos@uom.edu.gr","thalassa");
Proedros proedros = Proedros.arxikopoihse_Proedros("LinusTorvalds@uom.edu.gr", "i am the father of computer science");
Ereunitis e1 = new Ereunitis("mejustin@uom.edu.gr","galapagos");
Ereunitis e2 = new Ereunitis("TonyMontana@uom.edu.gr","communicatepls");
Ereunitis e3 = new Ereunitis("JordanPeterson@uom.edu.gr","psycho-logy");
Lista_Arxeiwn la = new Lista_Arxeiwn();
la.prosthiki_Arxeiou("xarti.pdf");
la.prosthiki_Arxeiou("dikaiologitika.docx");
Lista_Arxeiwn la1 = new Lista_Arxeiwn();
la1.prosthiki_Arxeiou("This_xarti.pdf");
la1.prosthiki_Arxeiou("dikaiologitika.docx");
Lista_Arxeiwn la2 = new Lista_Arxeiwn();
la2.prosthiki_Arxeiou("psych.pdf");
la2.prosthiki_Arxeiou("dikaiologitika.docx");
Lista_Arxeiwn la3 = new Lista_Arxeiwn();
Aitisi a1 = new Aitisi(e1,"On the Origin of Species","evolutionary biology",la);
Aitisi a2 = new Aitisi(e2,"A mathematical theory of communication","information theory",la1);
Aitisi a3 = new Aitisi(e3,"The Neuro-Psychoses of Defence","psychology",la2);
Aitisi a4 = new Aitisi(e3,"On the Psychical Mechanism of Hysterical Phenomena","psychology",la3);
gr = new Grammateia("daisecr@uom.edu.gr","uomcampus");
e1.ypovolli_Aitisis(a1);e2.ypovolli_Aitisis(a2);e3.ypovolli_Aitisis(a3);
gr.AnagnosiAitisewnGiaPrwtoElegxo();
printScenarioMenu();
Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();
switch (choice){
case 1:
scenario1(a1);
break;
case 2:
scenario2(a2);
break;
case 3:
scenario3(a3);
break;
case 4:
printKatalogous();
break;
}
while(choice != 4) {
printScenarioMenu();
choice = sc.nextInt();
switch (choice){
case 1:
scenario1(a1);
break;
case 2:
scenario2(a2);
break;
case 3:
scenario3(a3);
break;
case 4:
printKatalogous();
break;
}
}
}
private static void printKatalogous() {
try {
Lista_Aitisewn listaAitisewn = Lista_Aitisewn.ListaAitisewn();
Lista_Melwn listaMelwn = Lista_Melwn.ListaMelwn();
Lista_Eisigisewn listaEisigiseon = Lista_Eisigisewn.listaEisigiseon();
System.out.println("Εμφάνιση περιεχομένων των καταλόγων δεδομένων");
System.out.println("Δεδομένα Λίστας Αιτήσεων\n");
listaAitisewn.printData();
Thread.sleep(4000);
System.out.println("Δεδομένα Λίστας Εισηγήσεων\n");
listaEisigiseon.printData();
Thread.sleep(4000);
System.out.println("Δεδομένα Λίστας Μελών\n");
listaMelwn.printData();
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void scenario2(Aitisi a) {
//Σενάριο 2: Η αίτηση ελέγχεται, απορρίπτεται και εμφανίζονται όλες οι αιτήσεις που έχει υποβάλλει ο ερευνητής
Proedros proedros = Proedros.Get_instance();
Ereunitis e = a.getEreunitis();
try {
System.out.println("Η γραμματεία ελέγχει την αίτηση , προκύπτει ότι είναι ελλιπής και την απορρίπτει \n");
gr.aporripsi_Aitisis(a);
Thread.sleep(2000);
System.out.println("Ο ερευνητής πρέπει να δει τις αιτήσεις του για να δει την εξέλιξη όσων έχει υποβάλλει \n");
e.print_Aitiseis();
Thread.sleep(2000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
private static void scenario3(Aitisi a) {
//Σενάριο 3: Ο ερευνητής πρέπει να δει τις αιτήσεις του για να δει το αποτέλεδμα όσων έχει υποβάλλει.
try {
System.out.println("Ψάχνουμε τα μέλη και τον πρόεδρο\n");
Proedros proedros = Proedros.Get_instance();
Lista_Melwn listaMelwn = Lista_Melwn.ListaMelwn();
Melos m1 = listaMelwn.getMeli_EHDE().get(0);
Melos m2 = listaMelwn.getMeli_EHDE().get(1);
Melos m3 = listaMelwn.getMeli_EHDE().get(2);
Melos m4 = listaMelwn.getMeli_EHDE().get(3);
Ereunitis e = a.getEreunitis();
Thread.sleep(2000);
System.out.println("Η γραμματεία πρωτοκολλεί την αίτηση\n");
Thread.sleep(2000);
gr.protokollisi_Aitisis(a);
System.out.println("Ο πρόεδρος κάνει έλεγχο σύγκρουσης συμφερόντων\n");
Thread.sleep(2000);
proedros.apokleismos_melous(m3, a.getEisigisi());
System.out.println("Ο πρόεδρος απέκλεισε το μέλος:" + m1);
Thread.sleep(2000);
System.out.println("Ο πρόεδρος ολοκληρώνει τον έλεγχο σύγκρουσης συμφερόντων.\n");
Thread.sleep(2000);
proedros.Elegxos_Sygkrousis_Symferontwn(a);
System.out.println("Ο πρόεδρος ορίζει τον εισηγητή για την αίτηση.");
Thread.sleep(2000);
proedros.anathesi_Eisigisis(m1,a);
System.out.println("Εισηγητής ορίστηκε το μέλος: "+ m1);
Thread.sleep(2000);
System.out.println("Περιμένουμε τον εισηγητή να δημιουργήσει την εισήγηση.");
Thread.sleep(2000);
m1.dimiourgiseEisigisi(a,"He is just doing maths nothing of ethics that should concern us");
System.out.println("Συνεχίζουμε με την ψηφοφορία.");
Thread.sleep(2000);
proedros.psifos_Eisigisis(PSIFOS_YPER, a.getEisigisi());
m2.psifiseGiaEisigisiAitisis(a, PSIFOS_YPER);
m4.psifiseGiaEisigisiAitisis(a, PSIFOS_YPER);
System.out.println("Ψηφίσανε όλοι και ο πρόεδρος κλείνει την ψηφοφορία");
Thread.sleep(2000);
proedros.Psifoforia(a);
String message2 = (a.getEisigisi().getResult()) ? "Ginetai Apodekth":"Aporriptetai";
System.out.println(a.getTitle() + " " + message2);
System.out.println(a.getEisigisi().getResult());
Thread.sleep(2000);
System.out.println("Ο πρόεδρος θα γράψει την απόφαση για την αίτηση.");
Thread.sleep(2000);
proedros.syggrafi_Apofasis("Η αίτηση γίνεται δεκτή καθώς δεν τίθεται κανένα θέμα ηθικής", a.getApofasi());
proedros.ypografi_Apofasis(a);
System.out.println("Ο πρόεδρος υπέγραψε.\n Αποστέλλεται ενημερωτικό μήνυμα στον ερευνητή\n");
Thread.sleep(2000);
gr.enimerwse_Ereuniti(a);
Thread.sleep(2000);
System.out.println("Ο ερευνητής πρέπει να ελέγξει τις αιτήσεις του για να δει την κατάσταση τους\n");
e.print_Aitiseis();
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void scenario1(Aitisi a) {
//Σενάριο 1:
try {
System.out.println("Ψάχνουμε τον πρόεδρο, τα μέλη και τον ερευνητή\n");
Proedros proedros = Proedros.Get_instance();
Lista_Melwn listaMelwn = Lista_Melwn.ListaMelwn();
Melos m1 = listaMelwn.getMeli_EHDE().get(0);
Melos m2 = listaMelwn.getMeli_EHDE().get(1);
Melos m3 = listaMelwn.getMeli_EHDE().get(2);
Melos m4 = listaMelwn.getMeli_EHDE().get(3);
Ereunitis e = a.getEreunitis();
Thread.sleep(2000);
System.out.println("Η γραμματεία πρέπει να πρωτοκολλήσει την αίτηση.\n");
gr.protokollisi_Aitisis(a);
Thread.sleep(2000);
System.out.println("Ο πρόεδρος κάνει έλεγχο σύγκρουσης συμφερόντων.\n");
Thread.sleep(2000);
proedros.apokleismos_melous(m1, a.getEisigisi());
System.out.println("Ο Πρόεδρος απέκλεισε το μέλος: " + m1);
Thread.sleep(2000);
System.out.println("Ο πρόεδρος ολοκληρώνει τον έλεγχο σύγκρουσης συμφερόντων.\n");
Thread.sleep(2000);
proedros.Elegxos_Sygkrousis_Symferontwn(a);
System.out.println("Ο πρόεδρος πρέπει να αναθέσει εισηγητή.");
Thread.sleep(2000);
proedros.anathesi_Eisigisis(m2,a);
System.out.println("Ο πρόεδρος ανέθεσε την εισήγηση στο μέλος: "+ m2);
Thread.sleep(2000);
System.out.println("Ο εισηγήτης πρέπει να δημιουργήσει μια εισήγηση.");
Thread.sleep(2000);
m2.dimiourgiseEisigisi(a, "Μήπως να συννέλεγε επιστημονικά επιβεβαιωμένα δεδομένα?");
System.out.println("Ο εισηγητής καλείται να ψηφίσει.");
Thread.sleep(2000);
proedros.psifos_Eisigisis(PSIFOS_YPER, a.getEisigisi());
m3.psifiseGiaEisigisiAitisis(a, PSIFOS_KATA);
m4.psifiseGiaEisigisiAitisis(a, PSIFOS_KATA);
System.out.println("Ψηφίσανε όλοι και ο πρόεδρος κλείνει την ψηφοφορία.");
Thread.sleep(2000);
proedros.Psifoforia(a);
String message1 = (a.getEisigisi().getResult()) ? "Ginetai Apodekth":"Aporriptetai";
System.out.println(a.getTitle() + " " + message1);
Thread.sleep(2000);
System.out.println("Ο πρόεδρος θα γράψει την απόφαση για την αίτηση.");
Thread.sleep(2000);
proedros.syggrafi_Apofasis("Ο ερευνητής δεν συλλέγει πια δεδομένα τα οποία δημιουργούν "
+ "προβλήματα ηθικής άρα μπορεί να προχωρήσει.", a.getApofasi());
System.out.println("Ο πρόεδρος θα υπογράψει την απόφαση.");
Thread.sleep(2000);
proedros.ypografi_Apofasis(a);
System.out.println("Ο πρόεδρος υπέγραψε.\n Η γραμματεία αποστέλλει ενημερωτικό μήνυμα στον ερευνητή.");
Thread.sleep(2000);
gr.enimerwse_Ereuniti(a);
Thread.sleep(2000);
System.out.println("Ο ερευνητής πρέπει να ελέγξει τις αιτήσεις του για να δει την κατάσταση τους\n");
e.print_Aitiseis();
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void printScenarioMenu() {
System.out.println("\n ΕΦΑΡΜΟΓΗ ΓΙΑ ΤΗΝ ΕΗΔΕ ΤΟΥ ΠΑΜΑΚ\n");
System.out.println("Πλήκτρο 1: σενάριο αποδοχής της αίτησης από την γραμματεία και όχι από την επιτροπή.\n");
System.out.println("Πλήκτρο 2: σενάριο απόρριψης της αίτησης από την γραμματεία(ελλιπής).\n ");
System.out.println("Πλήκτρο 3: σενάριο αποδοχής της αίτησης από την γραμματεία και την επιτροπή.\n");
System.out.println("Πλήκτρο 4: για την εμφάνιση των Δεδομένων των Καταλόγων.\n");
}
}
|
tsantalis02/Uom_Applied_Informatics
|
Semester_04/System_Analysis_and_Design/Code/Case Study 2022-Systems Analysis & Design/src/Main.java
| 5,330
|
//Σενάριο 1:
|
line_comment
|
el
|
import java.awt.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
private static int PSIFOS_YPER = 1;
private static int PSIFOS_KATA = -1;
private static Grammateia gr;
public static void main(String[] args) {
//Object Creation
Lista_Aitisewn listaAitisewn = Lista_Aitisewn.ListaAitisewn();
Lista_Melwn listaMelwn = Lista_Melwn.ListaMelwn();
Lista_Eisigisewn listaEisigiseon = Lista_Eisigisewn.listaEisigiseon();
Melos m1 = new Melos("giannhs@uom.edu.gr","Mpananies");
Melos m2 = new Melos("panagiwths@uom.edu.gr","milo");
Melos m3 = new Melos("giwrgos@uom.edu.gr","aeras");
Melos m4 = new Melos("votsalos@uom.edu.gr","thalassa");
Proedros proedros = Proedros.arxikopoihse_Proedros("LinusTorvalds@uom.edu.gr", "i am the father of computer science");
Ereunitis e1 = new Ereunitis("mejustin@uom.edu.gr","galapagos");
Ereunitis e2 = new Ereunitis("TonyMontana@uom.edu.gr","communicatepls");
Ereunitis e3 = new Ereunitis("JordanPeterson@uom.edu.gr","psycho-logy");
Lista_Arxeiwn la = new Lista_Arxeiwn();
la.prosthiki_Arxeiou("xarti.pdf");
la.prosthiki_Arxeiou("dikaiologitika.docx");
Lista_Arxeiwn la1 = new Lista_Arxeiwn();
la1.prosthiki_Arxeiou("This_xarti.pdf");
la1.prosthiki_Arxeiou("dikaiologitika.docx");
Lista_Arxeiwn la2 = new Lista_Arxeiwn();
la2.prosthiki_Arxeiou("psych.pdf");
la2.prosthiki_Arxeiou("dikaiologitika.docx");
Lista_Arxeiwn la3 = new Lista_Arxeiwn();
Aitisi a1 = new Aitisi(e1,"On the Origin of Species","evolutionary biology",la);
Aitisi a2 = new Aitisi(e2,"A mathematical theory of communication","information theory",la1);
Aitisi a3 = new Aitisi(e3,"The Neuro-Psychoses of Defence","psychology",la2);
Aitisi a4 = new Aitisi(e3,"On the Psychical Mechanism of Hysterical Phenomena","psychology",la3);
gr = new Grammateia("daisecr@uom.edu.gr","uomcampus");
e1.ypovolli_Aitisis(a1);e2.ypovolli_Aitisis(a2);e3.ypovolli_Aitisis(a3);
gr.AnagnosiAitisewnGiaPrwtoElegxo();
printScenarioMenu();
Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();
switch (choice){
case 1:
scenario1(a1);
break;
case 2:
scenario2(a2);
break;
case 3:
scenario3(a3);
break;
case 4:
printKatalogous();
break;
}
while(choice != 4) {
printScenarioMenu();
choice = sc.nextInt();
switch (choice){
case 1:
scenario1(a1);
break;
case 2:
scenario2(a2);
break;
case 3:
scenario3(a3);
break;
case 4:
printKatalogous();
break;
}
}
}
private static void printKatalogous() {
try {
Lista_Aitisewn listaAitisewn = Lista_Aitisewn.ListaAitisewn();
Lista_Melwn listaMelwn = Lista_Melwn.ListaMelwn();
Lista_Eisigisewn listaEisigiseon = Lista_Eisigisewn.listaEisigiseon();
System.out.println("Εμφάνιση περιεχομένων των καταλόγων δεδομένων");
System.out.println("Δεδομένα Λίστας Αιτήσεων\n");
listaAitisewn.printData();
Thread.sleep(4000);
System.out.println("Δεδομένα Λίστας Εισηγήσεων\n");
listaEisigiseon.printData();
Thread.sleep(4000);
System.out.println("Δεδομένα Λίστας Μελών\n");
listaMelwn.printData();
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void scenario2(Aitisi a) {
//Σενάριο 2: Η αίτηση ελέγχεται, απορρίπτεται και εμφανίζονται όλες οι αιτήσεις που έχει υποβάλλει ο ερευνητής
Proedros proedros = Proedros.Get_instance();
Ereunitis e = a.getEreunitis();
try {
System.out.println("Η γραμματεία ελέγχει την αίτηση , προκύπτει ότι είναι ελλιπής και την απορρίπτει \n");
gr.aporripsi_Aitisis(a);
Thread.sleep(2000);
System.out.println("Ο ερευνητής πρέπει να δει τις αιτήσεις του για να δει την εξέλιξη όσων έχει υποβάλλει \n");
e.print_Aitiseis();
Thread.sleep(2000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
private static void scenario3(Aitisi a) {
//Σενάριο 3: Ο ερευνητής πρέπει να δει τις αιτήσεις του για να δει το αποτέλεδμα όσων έχει υποβάλλει.
try {
System.out.println("Ψάχνουμε τα μέλη και τον πρόεδρο\n");
Proedros proedros = Proedros.Get_instance();
Lista_Melwn listaMelwn = Lista_Melwn.ListaMelwn();
Melos m1 = listaMelwn.getMeli_EHDE().get(0);
Melos m2 = listaMelwn.getMeli_EHDE().get(1);
Melos m3 = listaMelwn.getMeli_EHDE().get(2);
Melos m4 = listaMelwn.getMeli_EHDE().get(3);
Ereunitis e = a.getEreunitis();
Thread.sleep(2000);
System.out.println("Η γραμματεία πρωτοκολλεί την αίτηση\n");
Thread.sleep(2000);
gr.protokollisi_Aitisis(a);
System.out.println("Ο πρόεδρος κάνει έλεγχο σύγκρουσης συμφερόντων\n");
Thread.sleep(2000);
proedros.apokleismos_melous(m3, a.getEisigisi());
System.out.println("Ο πρόεδρος απέκλεισε το μέλος:" + m1);
Thread.sleep(2000);
System.out.println("Ο πρόεδρος ολοκληρώνει τον έλεγχο σύγκρουσης συμφερόντων.\n");
Thread.sleep(2000);
proedros.Elegxos_Sygkrousis_Symferontwn(a);
System.out.println("Ο πρόεδρος ορίζει τον εισηγητή για την αίτηση.");
Thread.sleep(2000);
proedros.anathesi_Eisigisis(m1,a);
System.out.println("Εισηγητής ορίστηκε το μέλος: "+ m1);
Thread.sleep(2000);
System.out.println("Περιμένουμε τον εισηγητή να δημιουργήσει την εισήγηση.");
Thread.sleep(2000);
m1.dimiourgiseEisigisi(a,"He is just doing maths nothing of ethics that should concern us");
System.out.println("Συνεχίζουμε με την ψηφοφορία.");
Thread.sleep(2000);
proedros.psifos_Eisigisis(PSIFOS_YPER, a.getEisigisi());
m2.psifiseGiaEisigisiAitisis(a, PSIFOS_YPER);
m4.psifiseGiaEisigisiAitisis(a, PSIFOS_YPER);
System.out.println("Ψηφίσανε όλοι και ο πρόεδρος κλείνει την ψηφοφορία");
Thread.sleep(2000);
proedros.Psifoforia(a);
String message2 = (a.getEisigisi().getResult()) ? "Ginetai Apodekth":"Aporriptetai";
System.out.println(a.getTitle() + " " + message2);
System.out.println(a.getEisigisi().getResult());
Thread.sleep(2000);
System.out.println("Ο πρόεδρος θα γράψει την απόφαση για την αίτηση.");
Thread.sleep(2000);
proedros.syggrafi_Apofasis("Η αίτηση γίνεται δεκτή καθώς δεν τίθεται κανένα θέμα ηθικής", a.getApofasi());
proedros.ypografi_Apofasis(a);
System.out.println("Ο πρόεδρος υπέγραψε.\n Αποστέλλεται ενημερωτικό μήνυμα στον ερευνητή\n");
Thread.sleep(2000);
gr.enimerwse_Ereuniti(a);
Thread.sleep(2000);
System.out.println("Ο ερευνητής πρέπει να ελέγξει τις αιτήσεις του για να δει την κατάσταση τους\n");
e.print_Aitiseis();
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void scenario1(Aitisi a) {
//Σενάριο 1:<SUF>
try {
System.out.println("Ψάχνουμε τον πρόεδρο, τα μέλη και τον ερευνητή\n");
Proedros proedros = Proedros.Get_instance();
Lista_Melwn listaMelwn = Lista_Melwn.ListaMelwn();
Melos m1 = listaMelwn.getMeli_EHDE().get(0);
Melos m2 = listaMelwn.getMeli_EHDE().get(1);
Melos m3 = listaMelwn.getMeli_EHDE().get(2);
Melos m4 = listaMelwn.getMeli_EHDE().get(3);
Ereunitis e = a.getEreunitis();
Thread.sleep(2000);
System.out.println("Η γραμματεία πρέπει να πρωτοκολλήσει την αίτηση.\n");
gr.protokollisi_Aitisis(a);
Thread.sleep(2000);
System.out.println("Ο πρόεδρος κάνει έλεγχο σύγκρουσης συμφερόντων.\n");
Thread.sleep(2000);
proedros.apokleismos_melous(m1, a.getEisigisi());
System.out.println("Ο Πρόεδρος απέκλεισε το μέλος: " + m1);
Thread.sleep(2000);
System.out.println("Ο πρόεδρος ολοκληρώνει τον έλεγχο σύγκρουσης συμφερόντων.\n");
Thread.sleep(2000);
proedros.Elegxos_Sygkrousis_Symferontwn(a);
System.out.println("Ο πρόεδρος πρέπει να αναθέσει εισηγητή.");
Thread.sleep(2000);
proedros.anathesi_Eisigisis(m2,a);
System.out.println("Ο πρόεδρος ανέθεσε την εισήγηση στο μέλος: "+ m2);
Thread.sleep(2000);
System.out.println("Ο εισηγήτης πρέπει να δημιουργήσει μια εισήγηση.");
Thread.sleep(2000);
m2.dimiourgiseEisigisi(a, "Μήπως να συννέλεγε επιστημονικά επιβεβαιωμένα δεδομένα?");
System.out.println("Ο εισηγητής καλείται να ψηφίσει.");
Thread.sleep(2000);
proedros.psifos_Eisigisis(PSIFOS_YPER, a.getEisigisi());
m3.psifiseGiaEisigisiAitisis(a, PSIFOS_KATA);
m4.psifiseGiaEisigisiAitisis(a, PSIFOS_KATA);
System.out.println("Ψηφίσανε όλοι και ο πρόεδρος κλείνει την ψηφοφορία.");
Thread.sleep(2000);
proedros.Psifoforia(a);
String message1 = (a.getEisigisi().getResult()) ? "Ginetai Apodekth":"Aporriptetai";
System.out.println(a.getTitle() + " " + message1);
Thread.sleep(2000);
System.out.println("Ο πρόεδρος θα γράψει την απόφαση για την αίτηση.");
Thread.sleep(2000);
proedros.syggrafi_Apofasis("Ο ερευνητής δεν συλλέγει πια δεδομένα τα οποία δημιουργούν "
+ "προβλήματα ηθικής άρα μπορεί να προχωρήσει.", a.getApofasi());
System.out.println("Ο πρόεδρος θα υπογράψει την απόφαση.");
Thread.sleep(2000);
proedros.ypografi_Apofasis(a);
System.out.println("Ο πρόεδρος υπέγραψε.\n Η γραμματεία αποστέλλει ενημερωτικό μήνυμα στον ερευνητή.");
Thread.sleep(2000);
gr.enimerwse_Ereuniti(a);
Thread.sleep(2000);
System.out.println("Ο ερευνητής πρέπει να ελέγξει τις αιτήσεις του για να δει την κατάσταση τους\n");
e.print_Aitiseis();
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void printScenarioMenu() {
System.out.println("\n ΕΦΑΡΜΟΓΗ ΓΙΑ ΤΗΝ ΕΗΔΕ ΤΟΥ ΠΑΜΑΚ\n");
System.out.println("Πλήκτρο 1: σενάριο αποδοχής της αίτησης από την γραμματεία και όχι από την επιτροπή.\n");
System.out.println("Πλήκτρο 2: σενάριο απόρριψης της αίτησης από την γραμματεία(ελλιπής).\n ");
System.out.println("Πλήκτρο 3: σενάριο αποδοχής της αίτησης από την γραμματεία και την επιτροπή.\n");
System.out.println("Πλήκτρο 4: για την εμφάνιση των Δεδομένων των Καταλόγων.\n");
}
}
|
7663_10
|
/*
* Copyright 2019 George Tzikas <tzikas97@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package showflowpane;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
/**
*
* @author tzikas97
*/
public class ShowFlowPane extends Application {
/**
*
* @param myStage The application's first stage
*/
@Override
public void start(Stage myStage) {
//Δημιουργία FlowPane
FlowPane myPane = new FlowPane();
myPane.setOrientation(Orientation.VERTICAL); //Θέστε προσανατολισμό
myPane.setPadding(new Insets(10, 20, 30, 40)); //Θέστε ανω, κάτω, αριστερό και δεξί περιθώριο
myPane.setHgap(5); //θέστε οριζόντιο περιθώριο μεταξύ των εικόνων
myPane.setVgap(5); //θέστε κατακόρυφο περιθώριο μεταξύ των εικόνων
//Δημιουργία control nodes και τοποθέτησή τους εντος του pane
//Δημιουργία lblName, lblMiddleNameddleName, lblLastName
Label lblName = new Label("First Name:");
Label lblMiddleName = new Label("MI:");
Label lblLastName = new Label("Last Name:");
//Δημιουργία txtName, txtMiddleName, txtLastName
TextField txtName = new TextField();
TextField txtMiddleName = new TextField();
TextField txtLastName = new TextField();
//Προσθήκη κόμβων στο pane
myPane.getChildren().addAll(lblName, txtName, lblMiddleName, txtMiddleName, lblLastName, txtLastName);
//Δημιουργία σκηνικού διαστάσεων 250 χ 250 και προσθήκη του pane σε αυτό
Scene scene = new Scene(myPane, 250, 250);
//Προσθήκη σκηνικού στο παράθυρο
myStage.setScene(scene);
//Προσθήκη τίτλου "show Flow pane"
myStage.setTitle("show Flow pane");
//Εμφάνιση του παραθύρου
myStage.show();
}
/**
*
* @param args The command line arguments
*/
public static void main(String[] args) {
Application.launch(args);
}
}
|
tzikas97/javafx-uip
|
week_02/assignment_optional/output/ShowLoginFlow/src/showflowpane/ShowFlowPane.java
| 939
|
//Προσθήκη κόμβων στο pane
|
line_comment
|
el
|
/*
* Copyright 2019 George Tzikas <tzikas97@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package showflowpane;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
/**
*
* @author tzikas97
*/
public class ShowFlowPane extends Application {
/**
*
* @param myStage The application's first stage
*/
@Override
public void start(Stage myStage) {
//Δημιουργία FlowPane
FlowPane myPane = new FlowPane();
myPane.setOrientation(Orientation.VERTICAL); //Θέστε προσανατολισμό
myPane.setPadding(new Insets(10, 20, 30, 40)); //Θέστε ανω, κάτω, αριστερό και δεξί περιθώριο
myPane.setHgap(5); //θέστε οριζόντιο περιθώριο μεταξύ των εικόνων
myPane.setVgap(5); //θέστε κατακόρυφο περιθώριο μεταξύ των εικόνων
//Δημιουργία control nodes και τοποθέτησή τους εντος του pane
//Δημιουργία lblName, lblMiddleNameddleName, lblLastName
Label lblName = new Label("First Name:");
Label lblMiddleName = new Label("MI:");
Label lblLastName = new Label("Last Name:");
//Δημιουργία txtName, txtMiddleName, txtLastName
TextField txtName = new TextField();
TextField txtMiddleName = new TextField();
TextField txtLastName = new TextField();
//Προσθήκη κόμβων<SUF>
myPane.getChildren().addAll(lblName, txtName, lblMiddleName, txtMiddleName, lblLastName, txtLastName);
//Δημιουργία σκηνικού διαστάσεων 250 χ 250 και προσθήκη του pane σε αυτό
Scene scene = new Scene(myPane, 250, 250);
//Προσθήκη σκηνικού στο παράθυρο
myStage.setScene(scene);
//Προσθήκη τίτλου "show Flow pane"
myStage.setTitle("show Flow pane");
//Εμφάνιση του παραθύρου
myStage.show();
}
/**
*
* @param args The command line arguments
*/
public static void main(String[] args) {
Application.launch(args);
}
}
|
154_0
|
package com.example.passpal2;
import android.app.Dialog;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
import java.util.List;
import com.example.passpal2.MainAppsAdapter;
import it.xabaras.android.recyclerview.swipedecorator.RecyclerViewSwipeDecorator;
public class MainActivity extends AppCompatActivity implements RecyclerViewInterface {
String username;
private RecyclerView appsRecyclerView;
DataBaseHelper dbHelper = new DataBaseHelper(this);
private MainAppsAdapter mainAppsAdapter;
private List<AppsObj> selectedApps = new ArrayList<>();
private LinearLayoutManager layoutManager;
private Context context;
RelativeLayout Main_layout;
private List<AppsObj> apps = new ArrayList<>();
private static final int EDIT_APP_REQUEST = 2;
int userId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Ανάκτηση του username από το Intent ή SharedPreferences
Intent intent = getIntent();
username = intent.getStringExtra("username");
if (username == null || username.isEmpty()) {
SharedPreferences preferences = getSharedPreferences("user_credentials", MODE_PRIVATE);
username = preferences.getString("username", "");
}
getSupportActionBar().setTitle("Welcome, " + username + "!");
// Ανάκτηση του userId χρησιμοποιώντας το username
userId = dbHelper.getUserIdByUsername(username);
Main_layout = findViewById(R.id.Main_layout);
// AsyncTask για την ανάκτηση και εμφάνιση των εφαρμογών
new FetchAppsTask().execute(userId);
FloatingActionButton appsBtn = findViewById(R.id.appsBtn);
appsBtn.setOnClickListener(view -> {
Intent intentUserID = new Intent(MainActivity.this, AppSelectionActivity.class);
intentUserID.putExtra("USER_ID", userId);
startActivityForResult(intentUserID, 1);
});
appsRecyclerView = findViewById(R.id.appsRecyclerView);
layoutManager = new LinearLayoutManager(this);
appsRecyclerView.setLayoutManager(layoutManager);
// Αρχικοποίηση του MainAppsAdapter
mainAppsAdapter = new MainAppsAdapter(this, selectedApps);
// Set adapter to RecyclerView
appsRecyclerView.setAdapter(mainAppsAdapter);
appsRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
// Called when returning from AppSelectionActivity with selected apps
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == EDIT_APP_REQUEST && resultCode == RESULT_OK) {
if (data.hasExtra("POSITION")) {
int position = data.getIntExtra("POSITION", -1);
if (position != -1) {
// Προσαρμογή του RecyclerView στη συγκεκριμένη θέση
layoutManager.scrollToPosition(position);
}
}
ArrayList<Parcelable> parcelables = data.getParcelableArrayListExtra("selected_apps");
if (parcelables != null) {
List<AppsObj> apps = new ArrayList<>();
for (Parcelable parcelable : parcelables) {
if (parcelable instanceof AppsObj) {
apps.add((AppsObj) parcelable);
}
}
selectedApps.clear();
selectedApps.addAll(apps);
mainAppsAdapter.notifyDataSetChanged();
}
}
}
// RecyclerViewInterface method implementation
public void onItemClick(int position) {
AppsObj selectedApp = selectedApps.get(position);
//να πηγαινει στην αντισοτιχη ιστοσελιδα ή λινκ
Toast.makeText(MainActivity.this, "Clicked on app: " + selectedApp.getAppNames(), Toast.LENGTH_SHORT).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
showPopupMenu();
return true;
}
return super.onOptionsItemSelected(item);
}
private void showPopupMenu() {
PopupMenu popupMenu = new PopupMenu(this, findViewById(R.id.action_settings));
popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(item -> {
switch (item.getItemId()) {
//options(bottomsheet)
case R.id.menu_item1:
showDialog();
return true;
//LOG OUT
case R.id.menu_item2:
performLogout();
return true;
case R.id.menu_item3:
new AlertDialog.Builder(this)
.setTitle("About")
.setMessage("Ασφάλεια και οργάνωση στην παλάμη σας - αυτό είναι το όραμα του PassPal, της κορυφαίας εφαρμογής διαχείρισης στοιχείων πρόσβασης και εφαρμογών." +
" Με την έκδοση 1.0, το PassPal προσφέρει έναν άρτιο συνδυασμό απλότητας και καινοτομίας, επιτρέποντας σας να εγγραφείτε, να αποθηκεύσετε και να διαχειριστείτε ασφαλώς " +
"τις πληροφορίες πρόσβασης σε αγαπημένες σας εφαρμογές και ιστοσελίδες. Χάρη στην κρυπτογράφηση κορυφαίας τεχνολογίας, τα δεδομένα σας είναι προστατευμένα," +
" ενώ η ενσωματωμένη διασύνδεση με το Hunter API εξασφαλίζει ότι οι διευθύνσεις email που καταχωρίζετε είναι πάντα έγκυρες. " +
"Κατεβάστε το PassPal και βελτιώστε σήμερα τη διαχείριση των ψηφιακών σας προφίλ!")
.setPositiveButton(android.R.string.ok, (dialog, which) -> {
// Αν ο χρήστης επιλέξει να συνεχίσει, καλούμε την super.onBackPressed()
super.onBackPressed();
})
.show();
return true;
case R.id.menu_item4:
new AlertDialog.Builder(this)
.setTitle("Help")
.setMessage("Αγαπητέ χρήστη,\n" +
"\n" +
"Σας ευχαριστούμε που επιλέξατε την εφαρμογή PassPal! Αυτή η εφαρμογή σχεδιάστηκε για να κάνει τη διαχείριση των κωδικών πρόσβασης σας απλή και ασφαλή. Ακολουθούν οι βασικές λειτουργίες και πώς να τις χρησιμοποιήσετε:\n" +
"\n" +
"1.Εγγραφή/Σύνδεση: Ξεκινήστε δημιουργώντας έναν λογαριασμό χρήστη. Εάν έχετε ήδη λογαριασμό, συνδεθείτε με το όνομα χρήστη και τον κωδικό που έχετε ορίσει.\n" +
"\n" +
"2.Προσθήκη Εφαρμογών: Μόλις συνδεθείτε, μπορείτε να προσθέσετε εφαρμογές και ιστοσελίδες στη λίστα σας, καθώς και τους σχετικούς κωδικούς πρόσβασης.\n" +
"\n" +
"3.Διαχείριση κωδικών: Αποθηκεύστε και διαχειριστείτε ασφαλώς τους κωδικούς πρόσβασης, με τη δυνατότητα να τους επεξεργαστείτε ή να δημιουργήσετε νέους, μπορείτε ακόμα να επιτρέψετ και σε εμάς να σας προτείνουμε νέους κωδικούς.\n" +
"\n" +
"4.Ασφάλεια: Οι κωδικοί πρόσβασης σας είναι προστατευμένοι με σύγχρονες τεχνικές κρυπτογράφησης για να εξασφαλίζεται η ασφάλεια των δεδομένων σας.\n" +
"\n" +
"5.Πρόσβαση από παντού: Με την εφαρμογή PassPal, έχετε πρόσβαση στους κωδικούς σας από οποιαδήποτε συσκευή, ανά πάσα στιγμή.\n" +
"\n" +
"Αν χρειάζεστε περισσότερη βοήθεια ή έχετε απορίες, μη διστάσετε να μας επικοινωνήσετε μέσω της ενότητας επικοινωνίας στην εφαρμογή.\n" +
"\n" +
"Ειλικρινά,\n" +
"η ομάδα PassPal")
.setPositiveButton(android.R.string.ok, (dialog, which) -> {
super.onBackPressed();
})
.show();
return true;
/*
case R.id.menu_item5:
performLogout();
return true;*/
default:
return false;
}
});
popupMenu.show();
}
//For bottomSheet popup
private void showDialog() {
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(getWindow().FEATURE_NO_TITLE);
dialog.setContentView(R.layout.bottomsheet_layout);
LinearLayout EditLy = dialog.findViewById(R.id.EditLy);
LinearLayout ShareLy = dialog.findViewById(R.id.ShareLy);
LinearLayout UpdateLy = dialog.findViewById(R.id.UpdateLy);
LinearLayout LoginPswLy = dialog.findViewById(R.id.LoginPswLy);
LinearLayout SettingsLy = dialog.findViewById(R.id.SettingsLy);
EditLy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//EditActivity for apps activated
dialog.dismiss();
}
});
ShareLy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Log in app or website
dialog.dismiss();
}
});
UpdateLy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Update database
Toast.makeText(MainActivity.this, "Updating...", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
LoginPswLy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Will require a master password so he can go to the login and passwords activity with all apps their usernames and their passwords
dialog.dismiss();
}
});
SettingsLy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Settings can have the changes to the color of the app the interior and the background.
dialog.dismiss();
}
});
LinearLayout bottomSheetLayout = dialog.findViewById(R.id.bottom_sheet);
if (bottomSheetLayout != null) {
BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetLayout);
// Το κανει ορατο το bottomsheet
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
bottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
@Override
public void onStateChanged(@NonNull View bottomSheet, int newState) {
dialog.dismiss();
}
@Override
public void onSlide(@NonNull View bottomSheet, float slideOffset) {
// Additional functionality during bottom sheet slide
}
});
}
dialog.show();
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
dialog.getWindow().setGravity(Gravity.BOTTOM);
}
//Log out from popup menu LOGOUT FROM APP
private void performLogout() {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
private class FetchAppsTask extends AsyncTask<Integer, Void, List<AppsObj>> {
@Override
protected List<AppsObj> doInBackground(Integer... userIds) {
List<AppsObj> apps = dbHelper.getAllSelectedApps(userIds[0]);
Log.d("FetchAppsTask", "Επιστρεφόμενες εφαρμογές: " + apps.size());
Log.d("FetchAppsTask", "Ποιες ειναι οι εφαρμογες : " + apps);
return apps;
}
@Override
protected void onPostExecute(List<AppsObj> apps) {
super.onPostExecute(apps);
// Ενημέρωση του RecyclerView νέα λίστα εφαρμογών
mainAppsAdapter.setSelectedApps(apps);
attachSwipeToDeleteAndEditHelper();
Log.d("FetchAppsTask", "Ενημέρωση adapter με " + apps.size() + " εφαρμογές.");
for (AppsObj app : apps) {
Log.d("FetchApps", "App: " + app.getAppNames() );
}
}
}
/* public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder,
float dX, float dY, int actionState, boolean isCurrentlyActive) {
new RecyclerViewSwipeDecorator.Builder(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
//Adding color background and icon for deleteSwipe
.addSwipeLeftBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.red))
.addSwipeLeftActionIcon(R.drawable.deleteappitem)
//Adding color background and icon for editSwipe
.addSwipeRightBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.appGreen))
.addSwipeRightActionIcon(R.drawable.editappitem)
.create()
.decorate();
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}*/
//NEW SWIPE TZIO
private void attachSwipeToDeleteAndEditHelper() {
ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
if (direction == ItemTouchHelper.LEFT) {
// Διαγραφή της εφαρμογής
AppsObj app = mainAppsAdapter.getAppsList().get(position);
// Αποθήκευση της εφαρμογής τοπικα για το undo
AppsObj deletedApp = app;
int deletedIndex = position;
dbHelper.deleteApp(app.getAppNames(), dbHelper.getUserIdByUsername(username));
mainAppsAdapter.getAppsList().remove(position);
mainAppsAdapter.notifyItemRemoved(position);
// Εμφανίζει το Snackbar με την επιλογή Undo
Snackbar.make(appsRecyclerView, "App deleted", Snackbar.LENGTH_LONG)
.setAction("Undo", new View.OnClickListener() {
@Override
public void onClick(View view) {
// Επαναφορά της διαγραφείσας εφαρμογής
mainAppsAdapter.getAppsList().add(deletedIndex, deletedApp);
mainAppsAdapter.notifyItemInserted(deletedIndex);
}
}).show();
} else if (direction == ItemTouchHelper.RIGHT) {
// Επεξεργασία της εφαρμογής
AppsObj app = mainAppsAdapter.getAppsList().get(position);
// παιρνει τα δεδομενα της εφαρμογης και τα φορτωνει στην editapp
Intent intent = new Intent(MainActivity.this, EditSelectedAppActivity.class);
intent.putExtra("APP_DATA", app);
intent.putExtra("APP_ID", app.getId());
intent.putExtra("USER_ID",userId);
intent.putExtra("POSITION", position);
startActivityForResult(intent, EDIT_APP_REQUEST);
}
}
};
new ItemTouchHelper(simpleItemTouchCallback).attachToRecyclerView(appsRecyclerView);
}
}
|
tzioMelody/passpal2
|
app/src/main/java/com/example/passpal2/MainActivity.java
| 5,201
|
// Ανάκτηση του username από το Intent ή SharedPreferences
|
line_comment
|
el
|
package com.example.passpal2;
import android.app.Dialog;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
import java.util.List;
import com.example.passpal2.MainAppsAdapter;
import it.xabaras.android.recyclerview.swipedecorator.RecyclerViewSwipeDecorator;
public class MainActivity extends AppCompatActivity implements RecyclerViewInterface {
String username;
private RecyclerView appsRecyclerView;
DataBaseHelper dbHelper = new DataBaseHelper(this);
private MainAppsAdapter mainAppsAdapter;
private List<AppsObj> selectedApps = new ArrayList<>();
private LinearLayoutManager layoutManager;
private Context context;
RelativeLayout Main_layout;
private List<AppsObj> apps = new ArrayList<>();
private static final int EDIT_APP_REQUEST = 2;
int userId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Ανάκτηση του<SUF>
Intent intent = getIntent();
username = intent.getStringExtra("username");
if (username == null || username.isEmpty()) {
SharedPreferences preferences = getSharedPreferences("user_credentials", MODE_PRIVATE);
username = preferences.getString("username", "");
}
getSupportActionBar().setTitle("Welcome, " + username + "!");
// Ανάκτηση του userId χρησιμοποιώντας το username
userId = dbHelper.getUserIdByUsername(username);
Main_layout = findViewById(R.id.Main_layout);
// AsyncTask για την ανάκτηση και εμφάνιση των εφαρμογών
new FetchAppsTask().execute(userId);
FloatingActionButton appsBtn = findViewById(R.id.appsBtn);
appsBtn.setOnClickListener(view -> {
Intent intentUserID = new Intent(MainActivity.this, AppSelectionActivity.class);
intentUserID.putExtra("USER_ID", userId);
startActivityForResult(intentUserID, 1);
});
appsRecyclerView = findViewById(R.id.appsRecyclerView);
layoutManager = new LinearLayoutManager(this);
appsRecyclerView.setLayoutManager(layoutManager);
// Αρχικοποίηση του MainAppsAdapter
mainAppsAdapter = new MainAppsAdapter(this, selectedApps);
// Set adapter to RecyclerView
appsRecyclerView.setAdapter(mainAppsAdapter);
appsRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
// Called when returning from AppSelectionActivity with selected apps
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == EDIT_APP_REQUEST && resultCode == RESULT_OK) {
if (data.hasExtra("POSITION")) {
int position = data.getIntExtra("POSITION", -1);
if (position != -1) {
// Προσαρμογή του RecyclerView στη συγκεκριμένη θέση
layoutManager.scrollToPosition(position);
}
}
ArrayList<Parcelable> parcelables = data.getParcelableArrayListExtra("selected_apps");
if (parcelables != null) {
List<AppsObj> apps = new ArrayList<>();
for (Parcelable parcelable : parcelables) {
if (parcelable instanceof AppsObj) {
apps.add((AppsObj) parcelable);
}
}
selectedApps.clear();
selectedApps.addAll(apps);
mainAppsAdapter.notifyDataSetChanged();
}
}
}
// RecyclerViewInterface method implementation
public void onItemClick(int position) {
AppsObj selectedApp = selectedApps.get(position);
//να πηγαινει στην αντισοτιχη ιστοσελιδα ή λινκ
Toast.makeText(MainActivity.this, "Clicked on app: " + selectedApp.getAppNames(), Toast.LENGTH_SHORT).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
showPopupMenu();
return true;
}
return super.onOptionsItemSelected(item);
}
private void showPopupMenu() {
PopupMenu popupMenu = new PopupMenu(this, findViewById(R.id.action_settings));
popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(item -> {
switch (item.getItemId()) {
//options(bottomsheet)
case R.id.menu_item1:
showDialog();
return true;
//LOG OUT
case R.id.menu_item2:
performLogout();
return true;
case R.id.menu_item3:
new AlertDialog.Builder(this)
.setTitle("About")
.setMessage("Ασφάλεια και οργάνωση στην παλάμη σας - αυτό είναι το όραμα του PassPal, της κορυφαίας εφαρμογής διαχείρισης στοιχείων πρόσβασης και εφαρμογών." +
" Με την έκδοση 1.0, το PassPal προσφέρει έναν άρτιο συνδυασμό απλότητας και καινοτομίας, επιτρέποντας σας να εγγραφείτε, να αποθηκεύσετε και να διαχειριστείτε ασφαλώς " +
"τις πληροφορίες πρόσβασης σε αγαπημένες σας εφαρμογές και ιστοσελίδες. Χάρη στην κρυπτογράφηση κορυφαίας τεχνολογίας, τα δεδομένα σας είναι προστατευμένα," +
" ενώ η ενσωματωμένη διασύνδεση με το Hunter API εξασφαλίζει ότι οι διευθύνσεις email που καταχωρίζετε είναι πάντα έγκυρες. " +
"Κατεβάστε το PassPal και βελτιώστε σήμερα τη διαχείριση των ψηφιακών σας προφίλ!")
.setPositiveButton(android.R.string.ok, (dialog, which) -> {
// Αν ο χρήστης επιλέξει να συνεχίσει, καλούμε την super.onBackPressed()
super.onBackPressed();
})
.show();
return true;
case R.id.menu_item4:
new AlertDialog.Builder(this)
.setTitle("Help")
.setMessage("Αγαπητέ χρήστη,\n" +
"\n" +
"Σας ευχαριστούμε που επιλέξατε την εφαρμογή PassPal! Αυτή η εφαρμογή σχεδιάστηκε για να κάνει τη διαχείριση των κωδικών πρόσβασης σας απλή και ασφαλή. Ακολουθούν οι βασικές λειτουργίες και πώς να τις χρησιμοποιήσετε:\n" +
"\n" +
"1.Εγγραφή/Σύνδεση: Ξεκινήστε δημιουργώντας έναν λογαριασμό χρήστη. Εάν έχετε ήδη λογαριασμό, συνδεθείτε με το όνομα χρήστη και τον κωδικό που έχετε ορίσει.\n" +
"\n" +
"2.Προσθήκη Εφαρμογών: Μόλις συνδεθείτε, μπορείτε να προσθέσετε εφαρμογές και ιστοσελίδες στη λίστα σας, καθώς και τους σχετικούς κωδικούς πρόσβασης.\n" +
"\n" +
"3.Διαχείριση κωδικών: Αποθηκεύστε και διαχειριστείτε ασφαλώς τους κωδικούς πρόσβασης, με τη δυνατότητα να τους επεξεργαστείτε ή να δημιουργήσετε νέους, μπορείτε ακόμα να επιτρέψετ και σε εμάς να σας προτείνουμε νέους κωδικούς.\n" +
"\n" +
"4.Ασφάλεια: Οι κωδικοί πρόσβασης σας είναι προστατευμένοι με σύγχρονες τεχνικές κρυπτογράφησης για να εξασφαλίζεται η ασφάλεια των δεδομένων σας.\n" +
"\n" +
"5.Πρόσβαση από παντού: Με την εφαρμογή PassPal, έχετε πρόσβαση στους κωδικούς σας από οποιαδήποτε συσκευή, ανά πάσα στιγμή.\n" +
"\n" +
"Αν χρειάζεστε περισσότερη βοήθεια ή έχετε απορίες, μη διστάσετε να μας επικοινωνήσετε μέσω της ενότητας επικοινωνίας στην εφαρμογή.\n" +
"\n" +
"Ειλικρινά,\n" +
"η ομάδα PassPal")
.setPositiveButton(android.R.string.ok, (dialog, which) -> {
super.onBackPressed();
})
.show();
return true;
/*
case R.id.menu_item5:
performLogout();
return true;*/
default:
return false;
}
});
popupMenu.show();
}
//For bottomSheet popup
private void showDialog() {
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(getWindow().FEATURE_NO_TITLE);
dialog.setContentView(R.layout.bottomsheet_layout);
LinearLayout EditLy = dialog.findViewById(R.id.EditLy);
LinearLayout ShareLy = dialog.findViewById(R.id.ShareLy);
LinearLayout UpdateLy = dialog.findViewById(R.id.UpdateLy);
LinearLayout LoginPswLy = dialog.findViewById(R.id.LoginPswLy);
LinearLayout SettingsLy = dialog.findViewById(R.id.SettingsLy);
EditLy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//EditActivity for apps activated
dialog.dismiss();
}
});
ShareLy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Log in app or website
dialog.dismiss();
}
});
UpdateLy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Update database
Toast.makeText(MainActivity.this, "Updating...", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
LoginPswLy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Will require a master password so he can go to the login and passwords activity with all apps their usernames and their passwords
dialog.dismiss();
}
});
SettingsLy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Settings can have the changes to the color of the app the interior and the background.
dialog.dismiss();
}
});
LinearLayout bottomSheetLayout = dialog.findViewById(R.id.bottom_sheet);
if (bottomSheetLayout != null) {
BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetLayout);
// Το κανει ορατο το bottomsheet
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
bottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
@Override
public void onStateChanged(@NonNull View bottomSheet, int newState) {
dialog.dismiss();
}
@Override
public void onSlide(@NonNull View bottomSheet, float slideOffset) {
// Additional functionality during bottom sheet slide
}
});
}
dialog.show();
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
dialog.getWindow().setGravity(Gravity.BOTTOM);
}
//Log out from popup menu LOGOUT FROM APP
private void performLogout() {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
private class FetchAppsTask extends AsyncTask<Integer, Void, List<AppsObj>> {
@Override
protected List<AppsObj> doInBackground(Integer... userIds) {
List<AppsObj> apps = dbHelper.getAllSelectedApps(userIds[0]);
Log.d("FetchAppsTask", "Επιστρεφόμενες εφαρμογές: " + apps.size());
Log.d("FetchAppsTask", "Ποιες ειναι οι εφαρμογες : " + apps);
return apps;
}
@Override
protected void onPostExecute(List<AppsObj> apps) {
super.onPostExecute(apps);
// Ενημέρωση του RecyclerView νέα λίστα εφαρμογών
mainAppsAdapter.setSelectedApps(apps);
attachSwipeToDeleteAndEditHelper();
Log.d("FetchAppsTask", "Ενημέρωση adapter με " + apps.size() + " εφαρμογές.");
for (AppsObj app : apps) {
Log.d("FetchApps", "App: " + app.getAppNames() );
}
}
}
/* public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder,
float dX, float dY, int actionState, boolean isCurrentlyActive) {
new RecyclerViewSwipeDecorator.Builder(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
//Adding color background and icon for deleteSwipe
.addSwipeLeftBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.red))
.addSwipeLeftActionIcon(R.drawable.deleteappitem)
//Adding color background and icon for editSwipe
.addSwipeRightBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.appGreen))
.addSwipeRightActionIcon(R.drawable.editappitem)
.create()
.decorate();
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}*/
//NEW SWIPE TZIO
private void attachSwipeToDeleteAndEditHelper() {
ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
if (direction == ItemTouchHelper.LEFT) {
// Διαγραφή της εφαρμογής
AppsObj app = mainAppsAdapter.getAppsList().get(position);
// Αποθήκευση της εφαρμογής τοπικα για το undo
AppsObj deletedApp = app;
int deletedIndex = position;
dbHelper.deleteApp(app.getAppNames(), dbHelper.getUserIdByUsername(username));
mainAppsAdapter.getAppsList().remove(position);
mainAppsAdapter.notifyItemRemoved(position);
// Εμφανίζει το Snackbar με την επιλογή Undo
Snackbar.make(appsRecyclerView, "App deleted", Snackbar.LENGTH_LONG)
.setAction("Undo", new View.OnClickListener() {
@Override
public void onClick(View view) {
// Επαναφορά της διαγραφείσας εφαρμογής
mainAppsAdapter.getAppsList().add(deletedIndex, deletedApp);
mainAppsAdapter.notifyItemInserted(deletedIndex);
}
}).show();
} else if (direction == ItemTouchHelper.RIGHT) {
// Επεξεργασία της εφαρμογής
AppsObj app = mainAppsAdapter.getAppsList().get(position);
// παιρνει τα δεδομενα της εφαρμογης και τα φορτωνει στην editapp
Intent intent = new Intent(MainActivity.this, EditSelectedAppActivity.class);
intent.putExtra("APP_DATA", app);
intent.putExtra("APP_ID", app.getId());
intent.putExtra("USER_ID",userId);
intent.putExtra("POSITION", position);
startActivityForResult(intent, EDIT_APP_REQUEST);
}
}
};
new ItemTouchHelper(simpleItemTouchCallback).attachToRecyclerView(appsRecyclerView);
}
}
|
5643_26
|
package com.knkcloud.andoid.teiathcoupons.ui;
import java.io.File;
import java.util.ArrayList;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.knkcloud.andoid.teiathcoupons.R;
import com.knkcloud.andoid.teiathcoupons.customize.EncryptDecrypt;
import com.knkcloud.andoid.teiathcoupons.customize.FileManage;
import com.knkcloud.andoid.teiathcoupons.data.LogIn;
import com.knkcloud.andoid.teiathcoupons.utils.AStatus;
public class LoginUI extends Activity {
EditText clientinitialscreeneditTextUsername;
EditText clientinitialscreeneditTextpass;
CheckBox clientinitialscreencheckbox;
boolean nullusername=true;
boolean nullpass=true;;
boolean checked=false;
boolean emptyfile=false;
boolean asyncisfinished=false;
String FILENAME ="tei.txt";
ArrayList<String>filevalues= new ArrayList<String>();
ArrayList<String>Decryptedfilevalues= new ArrayList<String>();
String usr;
String pwd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
ImageButton imageButton1 = (ImageButton)findViewById(R.id.imageButton1);
imageButton1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LoginUI.this,WebViewActivity.class);
intent.putExtra("id", 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
}
});
ImageButton imageButton2 = (ImageButton)findViewById(R.id.imageButton2);
imageButton2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LoginUI.this,WebViewActivity.class);
intent.putExtra("id", 1);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
}
});
clientinitialscreeneditTextUsername = (EditText)findViewById(R.id.clientinitialscreeneditTextUsername);
TextView clientinitialscreenUsername = (TextView)findViewById(R.id.clientinitialscreenUsername);
clientinitialscreeneditTextpass = (EditText)findViewById(R.id.clientinitialscreeneditTextpass);
TextView clientinitialscreentextViewpass = (TextView)findViewById(R.id.clientinitialscreentextViewpass);
ImageButton clientinitialscreenbtn = (ImageButton)findViewById(R.id.clientinitialscreenbtn);
clientinitialscreencheckbox =(CheckBox)findViewById(R.id.clientinitialscreencheckbox);
clientinitialscreencheckbox.setTextColor(Color.rgb(102, 102, 102));
clientinitialscreenUsername.setTextColor(Color.rgb(102, 102, 102));
clientinitialscreentextViewpass.setTextColor(Color.rgb(102, 102, 102));
File file = getApplicationContext().getFileStreamPath(FILENAME);
//elegxos ean uparxei to arxeio
if(file.exists())
{
FileManage filemanipulation = new FileManage(getApplicationContext());
//anoikse arxeio
filemanipulation.FileOpen(FILENAME);
String fileisempty = filemanipulation.FileRead(FILENAME);
// elegxos ean einai adeio to arxeio
if(fileisempty.equals(null) || fileisempty.equals("") || fileisempty==null || fileisempty=="")
{
emptyfile=true;
}
//kleise arxeio
filemanipulation.FileInputClose(FILENAME);
//ean to arxeio den einai adeio
if(emptyfile==false)
{
//anoikse to
filemanipulation.FileOpen(FILENAME);
//vale tis KRUPTOGRAFIMENES times se ena arraylist<String> apo to arxeio pou periexei kai kena
filevalues = filemanipulation.FileReadtoArray(FILENAME);
//kleise arxeio
filemanipulation.FileInputClose(FILENAME);
//vale tis times tou parapanw Arraylist<string> xwris tis kenes times se ena neo
for(int i=0; i<filevalues.size()-1; i++)
{
if(filevalues.get(i).equals("")||filevalues.get(i).equals(null)|filevalues.get(i)==""||filevalues.get(i)=="")
{
// mi kaneis tipota
}
else
{ //vale tis decrypted times poy upirxan sto arxeio kai twra einai sto arraylist<String> se ena neo arraylist<String> pou den periexei kena
Decryptedfilevalues.add(filevalues.get(i));
}
}
//pare tin teleutai timi tou arxeiou pu einai i katastasi tou remember me true i false
String state=filevalues.get(filevalues.size()-1);
//kane ena object krutografisis/apokrutpografisis
EncryptDecrypt pp = new EncryptDecrypt(getApplicationContext());
if(state.equals("true")||state=="true" )
{
//an i katastasi itan clicked tote kane decrypt tis 2 times toy arraylist<string>
String PlainUsername = pp.Decrypt(Decryptedfilevalues.get(0));
String Plainpass = pp.Decrypt(Decryptedfilevalues.get(1));
//vale tis times sta pedia
clientinitialscreeneditTextUsername.setText(PlainUsername);
clientinitialscreeneditTextpass.setText(Plainpass);
clientinitialscreencheckbox.setChecked(true);
}
else
{ //ean to state den itan clicked oi formes einai adeies
clientinitialscreeneditTextUsername.setText("");
clientinitialscreeneditTextpass.setText("");
clientinitialscreencheckbox.setChecked(false);
}
}
}
clientinitialscreenbtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//to onoma den einai keno
nullusername=false ;
//to pass den einai keno
nullpass=false;
if(clientinitialscreeneditTextUsername.getText().toString()==""||clientinitialscreeneditTextUsername.getText().toString()==null||clientinitialscreeneditTextUsername.getText().toString().equals("")||clientinitialscreeneditTextUsername.getText().toString().equals(null))
{
//to onoma einai keno
nullusername=true;
}
if(clientinitialscreeneditTextpass.getText().toString()==""||clientinitialscreeneditTextpass.getText().toString()==null||clientinitialscreeneditTextpass.getText().toString().equals("")||clientinitialscreeneditTextpass.getText().toString().equals(null))
{
//to pass einai keno
nullpass=true;
}
if(nullusername==false && nullpass==false)
{//ean den einai kena swse tis times sto arxeio
StoreInFile();
//check internet status
if (haveNetworkConnection() ==true)
{
usr=clientinitialscreeneditTextUsername.getText().toString();
pwd=clientinitialscreeneditTextpass.getText().toString();
//dimioyrgia tou json pou stelnete sto login
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("\"User\":");
sb.append("{");
sb.append("\"username\":");
sb.append("\"");
sb.append(usr);
sb.append("\"");
sb.append(",");
sb.append("\"password\":");
sb.append("\"");
sb.append(pwd);
sb.append("\"");
sb.append("}");
sb.append("}");
new PostLogin(LoginUI.this).execute(sb.toString());
}
else
{
Toast.makeText(getApplicationContext(), R.string.checkinternet, Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getApplicationContext(), R.string.enternameandpass, Toast.LENGTH_LONG).show();
}
}
});
}
//elenxe ena uparxei sundesi sto internet
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
//apothikseuse sto arxeio kruptografimena ta username kai password
public void StoreInFile()
{
EncryptDecrypt pp = new EncryptDecrypt(getApplicationContext());
FileManage filemanipulation = new FileManage(getApplicationContext());
if(clientinitialscreencheckbox.isChecked())
{
String username = clientinitialscreeneditTextUsername.getText().toString();
String password = clientinitialscreeneditTextpass.getText().toString();
String state = "true";
String Cipherusername=pp.Encrypt(username);
String Cipherpassword=pp.Encrypt(password);
filemanipulation.FileCreate(FILENAME, MODE_PRIVATE);
filemanipulation.FileWrite(FILENAME, Cipherusername);
filemanipulation.FileChangeLine(FILENAME);
filemanipulation.FileWrite(FILENAME, Cipherpassword);
filemanipulation.FileChangeLine(FILENAME);
filemanipulation.FileWrite(FILENAME, state);
filemanipulation.FileOutputClose(FILENAME);
}
else
{
String username = clientinitialscreeneditTextUsername.getText().toString();
String password = clientinitialscreeneditTextpass.getText().toString();
String state = "false";
String Cipherusername=pp.Encrypt(username);
String Cipherpassword=pp.Encrypt(password);
filemanipulation.FileCreate(FILENAME, MODE_PRIVATE);
filemanipulation.FileWrite(FILENAME, Cipherusername);
filemanipulation.FileChangeLine(FILENAME);
filemanipulation.FileWrite(FILENAME, Cipherpassword);
filemanipulation.FileChangeLine(FILENAME);
filemanipulation.FileWrite(FILENAME, state);
filemanipulation.FileOutputClose(FILENAME);
}
}
// to async pou paizei to login
private class PostLogin extends LogIn {
public PostLogin(Context context) {
super(context);
}
@Override
public void onSuccess(String result) {
//Toast.makeText(getApplicationContext(), result, 1).show();
if(result.contains("403"))
{
Toast.makeText(getApplicationContext(), getResources().getString(R.string.faillogin), Toast.LENGTH_LONG).show();
}
else if(result.contains("200"))
{
Toast.makeText(getApplicationContext(), getResources().getString(R.string.successlogin), Toast.LENGTH_LONG).show();
Intent intent = new Intent(LoginUI.this, MainUI.class);
startActivity(intent);
}
// Toast.makeText(getApplicationContext(), getResources().getString(R.string.successlogin), 1).show();
//Toast.makeText(getApplicationContext(), getResources().getString(R.string.faillogin), 1).show();
}
@Override
public void onFail(AStatus cause) {
//Toast.makeText(getApplicationContext(), cause.getMessage(), Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), getResources().getString(R.string.checkinternet), Toast.LENGTH_LONG).show();
}
@Override
public void onWhatEver() {
//Toast.makeText(getApplicationContext(), "Υπήρξε κάποιο πρόβλημα με το διακομηστή.", Toast.LENGTH_LONG).show();
}
}
}
|
uniwa/offers-android
|
src/com/knkcloud/andoid/teiathcoupons/ui/LoginUI.java
| 3,273
|
//Toast.makeText(getApplicationContext(), "Υπήρξε κάποιο πρόβλημα με το διακομηστή.", Toast.LENGTH_LONG).show();
|
line_comment
|
el
|
package com.knkcloud.andoid.teiathcoupons.ui;
import java.io.File;
import java.util.ArrayList;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.knkcloud.andoid.teiathcoupons.R;
import com.knkcloud.andoid.teiathcoupons.customize.EncryptDecrypt;
import com.knkcloud.andoid.teiathcoupons.customize.FileManage;
import com.knkcloud.andoid.teiathcoupons.data.LogIn;
import com.knkcloud.andoid.teiathcoupons.utils.AStatus;
public class LoginUI extends Activity {
EditText clientinitialscreeneditTextUsername;
EditText clientinitialscreeneditTextpass;
CheckBox clientinitialscreencheckbox;
boolean nullusername=true;
boolean nullpass=true;;
boolean checked=false;
boolean emptyfile=false;
boolean asyncisfinished=false;
String FILENAME ="tei.txt";
ArrayList<String>filevalues= new ArrayList<String>();
ArrayList<String>Decryptedfilevalues= new ArrayList<String>();
String usr;
String pwd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
ImageButton imageButton1 = (ImageButton)findViewById(R.id.imageButton1);
imageButton1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LoginUI.this,WebViewActivity.class);
intent.putExtra("id", 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
}
});
ImageButton imageButton2 = (ImageButton)findViewById(R.id.imageButton2);
imageButton2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LoginUI.this,WebViewActivity.class);
intent.putExtra("id", 1);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
}
});
clientinitialscreeneditTextUsername = (EditText)findViewById(R.id.clientinitialscreeneditTextUsername);
TextView clientinitialscreenUsername = (TextView)findViewById(R.id.clientinitialscreenUsername);
clientinitialscreeneditTextpass = (EditText)findViewById(R.id.clientinitialscreeneditTextpass);
TextView clientinitialscreentextViewpass = (TextView)findViewById(R.id.clientinitialscreentextViewpass);
ImageButton clientinitialscreenbtn = (ImageButton)findViewById(R.id.clientinitialscreenbtn);
clientinitialscreencheckbox =(CheckBox)findViewById(R.id.clientinitialscreencheckbox);
clientinitialscreencheckbox.setTextColor(Color.rgb(102, 102, 102));
clientinitialscreenUsername.setTextColor(Color.rgb(102, 102, 102));
clientinitialscreentextViewpass.setTextColor(Color.rgb(102, 102, 102));
File file = getApplicationContext().getFileStreamPath(FILENAME);
//elegxos ean uparxei to arxeio
if(file.exists())
{
FileManage filemanipulation = new FileManage(getApplicationContext());
//anoikse arxeio
filemanipulation.FileOpen(FILENAME);
String fileisempty = filemanipulation.FileRead(FILENAME);
// elegxos ean einai adeio to arxeio
if(fileisempty.equals(null) || fileisempty.equals("") || fileisempty==null || fileisempty=="")
{
emptyfile=true;
}
//kleise arxeio
filemanipulation.FileInputClose(FILENAME);
//ean to arxeio den einai adeio
if(emptyfile==false)
{
//anoikse to
filemanipulation.FileOpen(FILENAME);
//vale tis KRUPTOGRAFIMENES times se ena arraylist<String> apo to arxeio pou periexei kai kena
filevalues = filemanipulation.FileReadtoArray(FILENAME);
//kleise arxeio
filemanipulation.FileInputClose(FILENAME);
//vale tis times tou parapanw Arraylist<string> xwris tis kenes times se ena neo
for(int i=0; i<filevalues.size()-1; i++)
{
if(filevalues.get(i).equals("")||filevalues.get(i).equals(null)|filevalues.get(i)==""||filevalues.get(i)=="")
{
// mi kaneis tipota
}
else
{ //vale tis decrypted times poy upirxan sto arxeio kai twra einai sto arraylist<String> se ena neo arraylist<String> pou den periexei kena
Decryptedfilevalues.add(filevalues.get(i));
}
}
//pare tin teleutai timi tou arxeiou pu einai i katastasi tou remember me true i false
String state=filevalues.get(filevalues.size()-1);
//kane ena object krutografisis/apokrutpografisis
EncryptDecrypt pp = new EncryptDecrypt(getApplicationContext());
if(state.equals("true")||state=="true" )
{
//an i katastasi itan clicked tote kane decrypt tis 2 times toy arraylist<string>
String PlainUsername = pp.Decrypt(Decryptedfilevalues.get(0));
String Plainpass = pp.Decrypt(Decryptedfilevalues.get(1));
//vale tis times sta pedia
clientinitialscreeneditTextUsername.setText(PlainUsername);
clientinitialscreeneditTextpass.setText(Plainpass);
clientinitialscreencheckbox.setChecked(true);
}
else
{ //ean to state den itan clicked oi formes einai adeies
clientinitialscreeneditTextUsername.setText("");
clientinitialscreeneditTextpass.setText("");
clientinitialscreencheckbox.setChecked(false);
}
}
}
clientinitialscreenbtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//to onoma den einai keno
nullusername=false ;
//to pass den einai keno
nullpass=false;
if(clientinitialscreeneditTextUsername.getText().toString()==""||clientinitialscreeneditTextUsername.getText().toString()==null||clientinitialscreeneditTextUsername.getText().toString().equals("")||clientinitialscreeneditTextUsername.getText().toString().equals(null))
{
//to onoma einai keno
nullusername=true;
}
if(clientinitialscreeneditTextpass.getText().toString()==""||clientinitialscreeneditTextpass.getText().toString()==null||clientinitialscreeneditTextpass.getText().toString().equals("")||clientinitialscreeneditTextpass.getText().toString().equals(null))
{
//to pass einai keno
nullpass=true;
}
if(nullusername==false && nullpass==false)
{//ean den einai kena swse tis times sto arxeio
StoreInFile();
//check internet status
if (haveNetworkConnection() ==true)
{
usr=clientinitialscreeneditTextUsername.getText().toString();
pwd=clientinitialscreeneditTextpass.getText().toString();
//dimioyrgia tou json pou stelnete sto login
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("\"User\":");
sb.append("{");
sb.append("\"username\":");
sb.append("\"");
sb.append(usr);
sb.append("\"");
sb.append(",");
sb.append("\"password\":");
sb.append("\"");
sb.append(pwd);
sb.append("\"");
sb.append("}");
sb.append("}");
new PostLogin(LoginUI.this).execute(sb.toString());
}
else
{
Toast.makeText(getApplicationContext(), R.string.checkinternet, Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getApplicationContext(), R.string.enternameandpass, Toast.LENGTH_LONG).show();
}
}
});
}
//elenxe ena uparxei sundesi sto internet
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
//apothikseuse sto arxeio kruptografimena ta username kai password
public void StoreInFile()
{
EncryptDecrypt pp = new EncryptDecrypt(getApplicationContext());
FileManage filemanipulation = new FileManage(getApplicationContext());
if(clientinitialscreencheckbox.isChecked())
{
String username = clientinitialscreeneditTextUsername.getText().toString();
String password = clientinitialscreeneditTextpass.getText().toString();
String state = "true";
String Cipherusername=pp.Encrypt(username);
String Cipherpassword=pp.Encrypt(password);
filemanipulation.FileCreate(FILENAME, MODE_PRIVATE);
filemanipulation.FileWrite(FILENAME, Cipherusername);
filemanipulation.FileChangeLine(FILENAME);
filemanipulation.FileWrite(FILENAME, Cipherpassword);
filemanipulation.FileChangeLine(FILENAME);
filemanipulation.FileWrite(FILENAME, state);
filemanipulation.FileOutputClose(FILENAME);
}
else
{
String username = clientinitialscreeneditTextUsername.getText().toString();
String password = clientinitialscreeneditTextpass.getText().toString();
String state = "false";
String Cipherusername=pp.Encrypt(username);
String Cipherpassword=pp.Encrypt(password);
filemanipulation.FileCreate(FILENAME, MODE_PRIVATE);
filemanipulation.FileWrite(FILENAME, Cipherusername);
filemanipulation.FileChangeLine(FILENAME);
filemanipulation.FileWrite(FILENAME, Cipherpassword);
filemanipulation.FileChangeLine(FILENAME);
filemanipulation.FileWrite(FILENAME, state);
filemanipulation.FileOutputClose(FILENAME);
}
}
// to async pou paizei to login
private class PostLogin extends LogIn {
public PostLogin(Context context) {
super(context);
}
@Override
public void onSuccess(String result) {
//Toast.makeText(getApplicationContext(), result, 1).show();
if(result.contains("403"))
{
Toast.makeText(getApplicationContext(), getResources().getString(R.string.faillogin), Toast.LENGTH_LONG).show();
}
else if(result.contains("200"))
{
Toast.makeText(getApplicationContext(), getResources().getString(R.string.successlogin), Toast.LENGTH_LONG).show();
Intent intent = new Intent(LoginUI.this, MainUI.class);
startActivity(intent);
}
// Toast.makeText(getApplicationContext(), getResources().getString(R.string.successlogin), 1).show();
//Toast.makeText(getApplicationContext(), getResources().getString(R.string.faillogin), 1).show();
}
@Override
public void onFail(AStatus cause) {
//Toast.makeText(getApplicationContext(), cause.getMessage(), Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), getResources().getString(R.string.checkinternet), Toast.LENGTH_LONG).show();
}
@Override
public void onWhatEver() {
//Toast.makeText(getApplicationContext(), "Υπήρξε<SUF>
}
}
}
|
5951_0
|
package com.iNNOS.mainengine;
import com.iNNOS.model.Client;
import com.iNNOS.model.Deliverable;
import com.iNNOS.model.Project;
import com.iNNOS.queryprocessor.Database;
public interface IMainEngine {
// Δημιουργία καινούριου έργου
public boolean createNewProject(Project projet);
// Δημιουργία νέου πελάτη
public boolean createNewClient(Client client);
// Δημιουργία καινούριου παραδοτέου
public Deliverable createNewDeliverbale(String identificationCode, String delivTitle, double contractualValue, String deadlineDate, String implementationMode);
// Σύνδεση με cloud database
public Database establishDbConnection();
}
|
vaggelisbarb/Business-Management-App
|
src/main/java/com/iNNOS/mainengine/IMainEngine.java
| 239
|
// Δημιουργία καινούριου έργου
|
line_comment
|
el
|
package com.iNNOS.mainengine;
import com.iNNOS.model.Client;
import com.iNNOS.model.Deliverable;
import com.iNNOS.model.Project;
import com.iNNOS.queryprocessor.Database;
public interface IMainEngine {
// Δημιουργία καινούριου<SUF>
public boolean createNewProject(Project projet);
// Δημιουργία νέου πελάτη
public boolean createNewClient(Client client);
// Δημιουργία καινούριου παραδοτέου
public Deliverable createNewDeliverbale(String identificationCode, String delivTitle, double contractualValue, String deadlineDate, String implementationMode);
// Σύνδεση με cloud database
public Database establishDbConnection();
}
|
524_0
|
import java.util.PriorityQueue;
import java.util.Queue;
/*Συλλογή των συχνοτήτων των συμβόλων που θέλουμε να συμπιέσουμε και χτίσιμο του κωδικού δέντρου για αυτό.*/
public final class Pinakas_suxnothtwn {
private int[] frequencies;
public Pinakas_suxnothtwn(int[] freqs) {
if (freqs == null) {
throw new NullPointerException("Null");
}
if (freqs.length < 2) {
throw new IllegalArgumentException("Τουλάχιστον 2 σύμβολα χρειάζονται");
}
for (int x : frequencies) {
if (x < 0) {
throw new IllegalArgumentException("Αρνητική συχνότητα");
}
}
}
public int getSymbolLimit() {
return frequencies.length;
}
public int get(int symbol) {
if (symbol < 0 || symbol >= frequencies.length)
throw new IllegalArgumentException("Σύμβολο εκτός εύρους");
return frequencies[symbol];
}
public void set(int symbol, int freq) {
if (symbol < 0 || symbol >= frequencies.length)
throw new IllegalArgumentException("Σύμβολο εκτός εύρους");
frequencies[symbol] = freq;
}
public void aukshsh(int symbol) {
if (symbol < 0 || symbol >= frequencies.length)
throw new IllegalArgumentException("Σύμβολο εκτός εύρους");
if (frequencies[symbol] == Integer.MAX_VALUE)
throw new RuntimeException("Αριθμητική υπερχείλιση");
frequencies[symbol]++;
}
// Επιστροφή ενός κώδικα δέντρου για αυτές τις συχνότητες.
public Kodikos_dentroy xtisimoDentrouKwdika() {
Queue<NodeWithFrequency> pqueue = new PriorityQueue<NodeWithFrequency>();
// Άθροισμα των φύλλων για τα σύμβολα με μη μηδενική συχνότητα.
for (int i = 0; i < frequencies.length; i++) {
if (frequencies[i] > 0)
pqueue.add(new NodeWithFrequency(new Fyllo(i), i, frequencies[i]));
}
// Δημιουργία τουλάχιστον 2 στοιχείων.
for (int i = 0; i < frequencies.length && pqueue.size() < 2; i++) {
if (i >= frequencies.length || frequencies[i] == 0) {
pqueue.add(new NodeWithFrequency(new Fyllo(i), i, 0));
}
}
if (pqueue.size() < 2) {
throw new AssertionError();
}
// Επαναληπτική ένωση των στοιχείων με τις χαμηλότερες συχνότητες.
while (pqueue.size() > 1) {
NodeWithFrequency nf1 = pqueue.remove();
NodeWithFrequency nf2 = pqueue.remove();
pqueue.add(new NodeWithFrequency(
new Esoterikos_komvos(nf1.komvos, nf2.komvos),
Math.min(nf1.lowestSymbol, nf2.lowestSymbol),
nf1.frequency + nf2.frequency));
}
// Επιστροφή του υπολοίπου.
return new Kodikos_dentroy((Esoterikos_komvos)pqueue.remove().komvos, frequencies.length);
}
private static class NodeWithFrequency implements Comparable<NodeWithFrequency> {
public final Komvos komvos;
public final int lowestSymbol;
public final long frequency;
public NodeWithFrequency(Komvos komvos, int lowestSymbol, long freq) {
this.komvos = komvos;
this.lowestSymbol = lowestSymbol;
this.frequency = freq;
}
public int compareTo(NodeWithFrequency other) {
if (frequency < other.frequency) {
return -1;
} else if (frequency > other.frequency) {
return 1;
} else if (lowestSymbol < other.lowestSymbol) {
return -1;
} else if (lowestSymbol > other.lowestSymbol) {
return 1;
} else {
return 0;
}
}
}
}
|
vktistopoulos/java2_telikh_ergasia
|
Pinakas_suxnothtwn.java
| 1,330
|
/*Συλλογή των συχνοτήτων των συμβόλων που θέλουμε να συμπιέσουμε και χτίσιμο του κωδικού δέντρου για αυτό.*/
|
block_comment
|
el
|
import java.util.PriorityQueue;
import java.util.Queue;
/*Συλλογή των συχνοτήτων<SUF>*/
public final class Pinakas_suxnothtwn {
private int[] frequencies;
public Pinakas_suxnothtwn(int[] freqs) {
if (freqs == null) {
throw new NullPointerException("Null");
}
if (freqs.length < 2) {
throw new IllegalArgumentException("Τουλάχιστον 2 σύμβολα χρειάζονται");
}
for (int x : frequencies) {
if (x < 0) {
throw new IllegalArgumentException("Αρνητική συχνότητα");
}
}
}
public int getSymbolLimit() {
return frequencies.length;
}
public int get(int symbol) {
if (symbol < 0 || symbol >= frequencies.length)
throw new IllegalArgumentException("Σύμβολο εκτός εύρους");
return frequencies[symbol];
}
public void set(int symbol, int freq) {
if (symbol < 0 || symbol >= frequencies.length)
throw new IllegalArgumentException("Σύμβολο εκτός εύρους");
frequencies[symbol] = freq;
}
public void aukshsh(int symbol) {
if (symbol < 0 || symbol >= frequencies.length)
throw new IllegalArgumentException("Σύμβολο εκτός εύρους");
if (frequencies[symbol] == Integer.MAX_VALUE)
throw new RuntimeException("Αριθμητική υπερχείλιση");
frequencies[symbol]++;
}
// Επιστροφή ενός κώδικα δέντρου για αυτές τις συχνότητες.
public Kodikos_dentroy xtisimoDentrouKwdika() {
Queue<NodeWithFrequency> pqueue = new PriorityQueue<NodeWithFrequency>();
// Άθροισμα των φύλλων για τα σύμβολα με μη μηδενική συχνότητα.
for (int i = 0; i < frequencies.length; i++) {
if (frequencies[i] > 0)
pqueue.add(new NodeWithFrequency(new Fyllo(i), i, frequencies[i]));
}
// Δημιουργία τουλάχιστον 2 στοιχείων.
for (int i = 0; i < frequencies.length && pqueue.size() < 2; i++) {
if (i >= frequencies.length || frequencies[i] == 0) {
pqueue.add(new NodeWithFrequency(new Fyllo(i), i, 0));
}
}
if (pqueue.size() < 2) {
throw new AssertionError();
}
// Επαναληπτική ένωση των στοιχείων με τις χαμηλότερες συχνότητες.
while (pqueue.size() > 1) {
NodeWithFrequency nf1 = pqueue.remove();
NodeWithFrequency nf2 = pqueue.remove();
pqueue.add(new NodeWithFrequency(
new Esoterikos_komvos(nf1.komvos, nf2.komvos),
Math.min(nf1.lowestSymbol, nf2.lowestSymbol),
nf1.frequency + nf2.frequency));
}
// Επιστροφή του υπολοίπου.
return new Kodikos_dentroy((Esoterikos_komvos)pqueue.remove().komvos, frequencies.length);
}
private static class NodeWithFrequency implements Comparable<NodeWithFrequency> {
public final Komvos komvos;
public final int lowestSymbol;
public final long frequency;
public NodeWithFrequency(Komvos komvos, int lowestSymbol, long freq) {
this.komvos = komvos;
this.lowestSymbol = lowestSymbol;
this.frequency = freq;
}
public int compareTo(NodeWithFrequency other) {
if (frequency < other.frequency) {
return -1;
} else if (frequency > other.frequency) {
return 1;
} else if (lowestSymbol < other.lowestSymbol) {
return -1;
} else if (lowestSymbol > other.lowestSymbol) {
return 1;
} else {
return 0;
}
}
}
}
|
16033_4
|
package gr.aueb.softeng.view.Owner.HomePage;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import gr.aueb.softeng.domain.Restaurant;
import gr.aueb.softeng.team08.R;
public class OwnerHomePageRecyclerViewAdapter extends RecyclerView.Adapter<OwnerHomePageRecyclerViewAdapter.ViewHolder>{
private final List<Restaurant> restaurants;
private final ItemSelectionListener listener;
/**
* Αρχικοποιεί την λίστα με τα εστιατόρια του ιδιοκτήτή που έχει κάνει το log in
* Αρχικοποιεί το αντικείμενο Listener που θα χρησιμοποιηθεί όταν ο χρήστης πατήσει επάνω σε κάποιο εστιατόριο
* @param restaurants τα εστιατόρια του ιδιοκτήτη
* @param listener το αντικείμενο item selection listener που θα χρησιμοποιήσουμε
*/
public OwnerHomePageRecyclerViewAdapter(List<Restaurant> restaurants, ItemSelectionListener listener){
this.restaurants = restaurants;
this.listener=listener;
}
/**
* Περνάει στον adapter το layout που θέλουμε να εμφανιστούν τα αντικείμενα της λίστας μας - τα εστιατόρια του ιδιοκτήτη στην περίπτωσή μας
* @param parent The ViewGroup into which the new View will be added after it is bound to
* an adapter position.
* @param viewType The view type of the new View.
*
* @return νέο αντικείμενο view holder με το custom layout των εστιατορίων
*/
@NonNull
@Override
public OwnerHomePageRecyclerViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.restaurant_list_item , parent, false));
}
/**
* Βάζει σε κάθε αντικείμενο εστιατορίου το όνομα του εστιατορίου στο συγκεκριμένο Text View που έχουμε δημιουργήσει
* δημιουργεί το On Click Listener το οποίο ενεργοποιείται όταν πατηθεί κάποιο συγκεκριμένο εστιατόριο
* @param holder The ViewHolder which should be updated to represent the contents of the
* item at the given position in the data set.
* @param position The position of the item within the adapter's data set.
*/
@Override
public void onBindViewHolder(@NonNull OwnerHomePageRecyclerViewAdapter.ViewHolder holder, int position) {
final Restaurant currentItem = restaurants.get(position);
holder.restName.setText("Name:"+String.valueOf(currentItem.getRestaurantName()));
holder.restName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
listener.selectRestaurant(currentItem);
}
});
}
/**
* Αρχικοποιεί το Text View που χρησιμοποιούμε στην παραπάνω μέθοδο
*/
public class ViewHolder extends RecyclerView.ViewHolder
{
public final TextView restName;
public ViewHolder(View view)
{
super(view);
restName = view.findViewById(R.id.RestaurantName);
}
/**
* @return επιστρέφει το όνομα του εστιατορίου αν καλεστεί με System.out.print
*/
@Override
public String toString() {
return super.toString() + " '" + restName.getText() + "'";
}
}
/**
*
* @return επιστρέφει το μέγεθος της λίστας με τα εστιατόρια
*/
@Override
public int getItemCount() {
return restaurants.size();
}
/**
* καλεί την μέθοδο που θέλουμε όταν πατηθεί ένα εστιατόριο
*/
public interface ItemSelectionListener
{
void selectRestaurant(Restaurant restaurant);
}
}
|
vleft02/Restaurant-Application
|
app/src/main/java/gr/aueb/softeng/view/Owner/HomePage/OwnerHomePageRecyclerViewAdapter.java
| 1,329
|
/**
* @return επιστρέφει το όνομα του εστιατορίου αν καλεστεί με System.out.print
*/
|
block_comment
|
el
|
package gr.aueb.softeng.view.Owner.HomePage;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import gr.aueb.softeng.domain.Restaurant;
import gr.aueb.softeng.team08.R;
public class OwnerHomePageRecyclerViewAdapter extends RecyclerView.Adapter<OwnerHomePageRecyclerViewAdapter.ViewHolder>{
private final List<Restaurant> restaurants;
private final ItemSelectionListener listener;
/**
* Αρχικοποιεί την λίστα με τα εστιατόρια του ιδιοκτήτή που έχει κάνει το log in
* Αρχικοποιεί το αντικείμενο Listener που θα χρησιμοποιηθεί όταν ο χρήστης πατήσει επάνω σε κάποιο εστιατόριο
* @param restaurants τα εστιατόρια του ιδιοκτήτη
* @param listener το αντικείμενο item selection listener που θα χρησιμοποιήσουμε
*/
public OwnerHomePageRecyclerViewAdapter(List<Restaurant> restaurants, ItemSelectionListener listener){
this.restaurants = restaurants;
this.listener=listener;
}
/**
* Περνάει στον adapter το layout που θέλουμε να εμφανιστούν τα αντικείμενα της λίστας μας - τα εστιατόρια του ιδιοκτήτη στην περίπτωσή μας
* @param parent The ViewGroup into which the new View will be added after it is bound to
* an adapter position.
* @param viewType The view type of the new View.
*
* @return νέο αντικείμενο view holder με το custom layout των εστιατορίων
*/
@NonNull
@Override
public OwnerHomePageRecyclerViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.restaurant_list_item , parent, false));
}
/**
* Βάζει σε κάθε αντικείμενο εστιατορίου το όνομα του εστιατορίου στο συγκεκριμένο Text View που έχουμε δημιουργήσει
* δημιουργεί το On Click Listener το οποίο ενεργοποιείται όταν πατηθεί κάποιο συγκεκριμένο εστιατόριο
* @param holder The ViewHolder which should be updated to represent the contents of the
* item at the given position in the data set.
* @param position The position of the item within the adapter's data set.
*/
@Override
public void onBindViewHolder(@NonNull OwnerHomePageRecyclerViewAdapter.ViewHolder holder, int position) {
final Restaurant currentItem = restaurants.get(position);
holder.restName.setText("Name:"+String.valueOf(currentItem.getRestaurantName()));
holder.restName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
listener.selectRestaurant(currentItem);
}
});
}
/**
* Αρχικοποιεί το Text View που χρησιμοποιούμε στην παραπάνω μέθοδο
*/
public class ViewHolder extends RecyclerView.ViewHolder
{
public final TextView restName;
public ViewHolder(View view)
{
super(view);
restName = view.findViewById(R.id.RestaurantName);
}
/**
* @return επιστρέφει το<SUF>*/
@Override
public String toString() {
return super.toString() + " '" + restName.getText() + "'";
}
}
/**
*
* @return επιστρέφει το μέγεθος της λίστας με τα εστιατόρια
*/
@Override
public int getItemCount() {
return restaurants.size();
}
/**
* καλεί την μέθοδο που θέλουμε όταν πατηθεί ένα εστιατόριο
*/
public interface ItemSelectionListener
{
void selectRestaurant(Restaurant restaurant);
}
}
|
68_1
|
//package Calculations;
import java.util.Arrays;
import java.util.Scanner;
//υπολογισμός ΜΚΔ και ΕΚΠ
public class Gcd_Lcm
{
int n,min,max;
int counter,counter1;
int gcd,lcm;
public void gdt_and_lcm()
{
System.out.println("please give me how many numbers");
Scanner in = new Scanner(System.in);
n= in.nextInt();
int [] num = new int[n];
//εισάγουμε τα δεδομένα(τις τιμές)
System.out.println("input the numbers (only positive integers):");
for (int i=0;i<n;i++)
{
num[i]=in.nextInt();
}
Arrays.sort(num);
min = num[0];
max = num[n-1];
counter=0;
counter1=0;
//Υπολογισμός ΜΚΔ θετικών ακέραιων αριθμών
while (counter<n)
{
counter=0;
for (int j=0;j<n;j++)
{
if ((num[j]%min)==0)
{
counter=counter+1;
}
}
if(counter!=n)
{
min=(min-1);
}
}
//υπολογισμός ΕΚΠ για θετκούς ακέραιους αριθμούς
while(counter1<n)
{
counter1=0;
for (int j=0;j<n;j++)
{
if (max%num[j]==0)
{
counter1=counter1+1;
}
}
if (counter1!=n)
{
max=max+1;
}
}
lcm=max;
gcd=min;
System.out.println("Initialism for greatest common divisor GCD is:"+gcd);
System.out.println("Initialism for least common multiple LCM is:"+lcm);
}
}
|
vmaurop/Math_is_fun
|
Gcd_Lcm.java
| 571
|
//εισάγουμε τα δεδομένα(τις τιμές)
|
line_comment
|
el
|
//package Calculations;
import java.util.Arrays;
import java.util.Scanner;
//υπολογισμός ΜΚΔ και ΕΚΠ
public class Gcd_Lcm
{
int n,min,max;
int counter,counter1;
int gcd,lcm;
public void gdt_and_lcm()
{
System.out.println("please give me how many numbers");
Scanner in = new Scanner(System.in);
n= in.nextInt();
int [] num = new int[n];
//εισάγουμε τα<SUF>
System.out.println("input the numbers (only positive integers):");
for (int i=0;i<n;i++)
{
num[i]=in.nextInt();
}
Arrays.sort(num);
min = num[0];
max = num[n-1];
counter=0;
counter1=0;
//Υπολογισμός ΜΚΔ θετικών ακέραιων αριθμών
while (counter<n)
{
counter=0;
for (int j=0;j<n;j++)
{
if ((num[j]%min)==0)
{
counter=counter+1;
}
}
if(counter!=n)
{
min=(min-1);
}
}
//υπολογισμός ΕΚΠ για θετκούς ακέραιους αριθμούς
while(counter1<n)
{
counter1=0;
for (int j=0;j<n;j++)
{
if (max%num[j]==0)
{
counter1=counter1+1;
}
}
if (counter1!=n)
{
max=max+1;
}
}
lcm=max;
gcd=min;
System.out.println("Initialism for greatest common divisor GCD is:"+gcd);
System.out.println("Initialism for least common multiple LCM is:"+lcm);
}
}
|
4125_0
|
package com.example.software_technology;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.net.URL;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Menu;
import javafx.scene.control.TextField;
import java.time.LocalDate;
import java.util.ResourceBundle;
public class CustomerController2 implements Initializable {
private Stage primary_stage = HotelMain.get_stage();
private Connection connection = HotelMain.get_connection();
@FXML
protected void change_scene_reservation() throws IOException {
HotelMain.change_scene("reservation.fxml");
}
@FXML
private ChoiceBox<String> choiceBox;
@FXML
private TextField adults;
@FXML
private TextField children;
@FXML
private CheckBox meal;
@FXML
private CheckBox pool;
@FXML
private CheckBox tennisCourt;
@FXML
private DatePicker checkInDate;
@FXML
private DatePicker checkOutDate;
@FXML
private Button backButton2;
@FXML
public void button_backButton2(ActionEvent actionevent) throws IOException {
HotelMain.change_scene("customer.fxml");
}
@Override // Ορισμός περιεχομένου μέσα στη λίστα τύπων δωματίου
public void initialize(URL url, ResourceBundle resourceBundle) {
choiceBox.getItems().addAll("ECONOMIC", "NORMAL", "SUITE");
}
@FXML
private void button_showButton() throws IOException, SQLException {
//HotelMain.change_scene("reservation.fxml");
Stage primary_stage = HotelMain.get_stage();
Connection connection = HotelMain.get_connection();
String adultSelection = adults.getText();
String childrenSelection = children.getText();
String choiceBox1 = choiceBox.getValue();
boolean mealSelection = meal.isSelected();
boolean poolSelection = pool.isSelected();
boolean tennisCourtSelection = tennisCourt.isSelected();
LocalDate checkInDateSelection = checkInDate.getValue();
LocalDate checkOutDateSelection = checkOutDate.getValue();
GridPane gridPane = new GridPane();
ScrollPane scrollpane = new ScrollPane(gridPane);
AnchorPane rootPane = new AnchorPane(scrollpane);
Scene scene = new Scene(rootPane, 500, 500);
primary_stage.setScene(scene);
primary_stage.getScene().setRoot(rootPane);
AnchorPane.setTopAnchor(scrollpane, 0.0);
AnchorPane.setBottomAnchor(scrollpane, 0.0);
AnchorPane.setLeftAnchor(scrollpane, 0.0);
AnchorPane.setRightAnchor(scrollpane, 0.0);
AnchorPane.setTopAnchor(gridPane, 0.0);
AnchorPane.setBottomAnchor(gridPane, 0.0);
AnchorPane.setLeftAnchor(gridPane, 0.0);
AnchorPane.setRightAnchor(gridPane, 0.0);
Button button = new Button("Back");
button.setStyle("-fx-padding: 10px;");
AnchorPane.setBottomAnchor(button, 10.0);
AnchorPane.setRightAnchor(button, 70.0);
rootPane.getChildren().add(button);
button.setOnMouseClicked(event -> {
try {
HotelMain.change_scene("customer.fxml");
} catch (IOException e) {
throw new RuntimeException(e);
}
});
int totalCount = Integer.parseInt(adultSelection) + Integer.parseInt(childrenSelection);
String sql2 = "SELECT * FROM ROOM inner join reservation on ROOM.ROOM_ID = reservation.ROOM_ID";
PreparedStatement statement1 = connection.prepareStatement(sql2);
ResultSet resultset1 = statement1.executeQuery();
int ROW=1;
while (resultset1.next()){
if(LocalDate.parse(resultset1.getString("CHECK_IN_DATE")).compareTo(((LocalDate) checkInDate.getValue())) < 0//CHECK_IN_DATE date is after checkInDate
&& LocalDate.parse(resultset1.getString("CHECK_IN_DATE")).compareTo(((LocalDate) checkOutDate.getValue())) > 0){//CHECK_IN_DATE date is before checkOutDate
continue;
}
else if(LocalDate.parse(resultset1.getString("CHECK_IN_DATE")).compareTo(((LocalDate) checkInDate.getValue())) > 0//CHECK_IN_DATE date is before checkInDate
&& LocalDate.parse(resultset1.getString("CHECK_OUT_DATE")).compareTo(((LocalDate) checkOutDate.getValue())) > 0){//CHECK_OUT_DATE date is before checkOutDate
continue;
}
else if(LocalDate.parse(resultset1.getString("CHECK_OUT_DATE")).compareTo(((LocalDate) checkInDate.getValue())) < 0//CHECK_OUT_DATE date is after checkInDate
&& LocalDate.parse(resultset1.getString("CHECK_OUT_DATE")).compareTo(((LocalDate) checkOutDate.getValue())) > 0){//CHECK_OUT_DATE date is before checkOutDate
continue;
}
else if((Integer.parseInt(resultset1.getString("ROOM_ID")) + 1 )<= ROW){
continue;
}
Rectangle box = new Rectangle(300, 100); // Create a rectangle as a box
Text nameText = new Text("Price: "+resultset1.getString("PRICE_PER_NIGHT")+" "+"Capacity: "+resultset1.getString("ROOM_CAPACITY"));
nameText.setId(String.valueOf(resultset1.getString("ROOM_ID")));
nameText.setWrappingWidth(100); // Set the width of the text box
nameText.setFont(Font.font("Arial", FontWeight.BOLD, 12));
nameText.setTextAlignment(TextAlignment.CENTER);
nameText.setMouseTransparent(true);
box.setFill(Color.AQUA);
box.setStroke(Color.BURLYWOOD);
box.setStrokeWidth(2);
box.setOnMouseClicked(event -> {
try {
String[] parts = nameText.getText().split(" ");
make_reservation(checkInDate.getValue().toString(),checkOutDate.getValue().toString(), HotelMain.getID(),box.getId(),
parts[1], adults.getText(), children.getText(), mealSelection,poolSelection, tennisCourtSelection);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (SQLException e) {
throw new RuntimeException(e);
}
});
gridPane.add(box, 1, ROW); // Add the box to the GridPane
gridPane.add(nameText, 1, ROW);
ROW++;
}
primary_stage.show();
}
@FXML
private void make_reservation(String checkInDate,String checkOutDate,String customerid ,String roomid,
String price ,String adults ,String children,boolean meal,boolean pool,boolean tennis) throws IOException, SQLException {
String sql = "INSERT INTO reservation (CHECK_IN_DATE, CHECK_OUT_DATE, CUSTOMER_ID, ROOM_ID, PRICE, ADULT_NUMBER," +
"CHILDREN_NUMBER,INCLUDED_MEAL,INCLUDED_POOL,INCLUDED_TENNIS_COURT) VALUES (?,?,?,?,?,?,?,?,?,?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, checkInDate); // Set the value for the first parameter placeholder
statement.setString(2, checkOutDate); // Set the value for the second parameter placeholder
statement.setString(3, customerid); // Set the value for the third parameter placeholder
statement.setString(4, roomid); // Set the value for the third parameter placeholder
statement.setString(5, price); // Set the value for the third parameter placeholder
statement.setString(6, adults); // Set the value for the third parameter placeholder
statement.setString(7, children); // Set the value for the third parameter placeholder
statement.setBoolean(8, meal); // Set the value for the third parameter placeholder
statement.setBoolean(9, pool); // Set the value for the third parameter placeholder
statement.setBoolean(10, tennis); // Set the value for the third parameter placeholder
int rowsInserted = statement.executeUpdate();
HotelMain.change_scene("customer.fxml");
}
}
|
vpanagiotou531/Software-Technology-2022-23
|
Final Code/SQL/Software_Technology/src/main/java/com/example/software_technology/CustomerController2.java
| 2,104
|
// Ορισμός περιεχομένου μέσα στη λίστα τύπων δωματίου
|
line_comment
|
el
|
package com.example.software_technology;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.net.URL;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Menu;
import javafx.scene.control.TextField;
import java.time.LocalDate;
import java.util.ResourceBundle;
public class CustomerController2 implements Initializable {
private Stage primary_stage = HotelMain.get_stage();
private Connection connection = HotelMain.get_connection();
@FXML
protected void change_scene_reservation() throws IOException {
HotelMain.change_scene("reservation.fxml");
}
@FXML
private ChoiceBox<String> choiceBox;
@FXML
private TextField adults;
@FXML
private TextField children;
@FXML
private CheckBox meal;
@FXML
private CheckBox pool;
@FXML
private CheckBox tennisCourt;
@FXML
private DatePicker checkInDate;
@FXML
private DatePicker checkOutDate;
@FXML
private Button backButton2;
@FXML
public void button_backButton2(ActionEvent actionevent) throws IOException {
HotelMain.change_scene("customer.fxml");
}
@Override // Ορισμός περιεχομένου<SUF>
public void initialize(URL url, ResourceBundle resourceBundle) {
choiceBox.getItems().addAll("ECONOMIC", "NORMAL", "SUITE");
}
@FXML
private void button_showButton() throws IOException, SQLException {
//HotelMain.change_scene("reservation.fxml");
Stage primary_stage = HotelMain.get_stage();
Connection connection = HotelMain.get_connection();
String adultSelection = adults.getText();
String childrenSelection = children.getText();
String choiceBox1 = choiceBox.getValue();
boolean mealSelection = meal.isSelected();
boolean poolSelection = pool.isSelected();
boolean tennisCourtSelection = tennisCourt.isSelected();
LocalDate checkInDateSelection = checkInDate.getValue();
LocalDate checkOutDateSelection = checkOutDate.getValue();
GridPane gridPane = new GridPane();
ScrollPane scrollpane = new ScrollPane(gridPane);
AnchorPane rootPane = new AnchorPane(scrollpane);
Scene scene = new Scene(rootPane, 500, 500);
primary_stage.setScene(scene);
primary_stage.getScene().setRoot(rootPane);
AnchorPane.setTopAnchor(scrollpane, 0.0);
AnchorPane.setBottomAnchor(scrollpane, 0.0);
AnchorPane.setLeftAnchor(scrollpane, 0.0);
AnchorPane.setRightAnchor(scrollpane, 0.0);
AnchorPane.setTopAnchor(gridPane, 0.0);
AnchorPane.setBottomAnchor(gridPane, 0.0);
AnchorPane.setLeftAnchor(gridPane, 0.0);
AnchorPane.setRightAnchor(gridPane, 0.0);
Button button = new Button("Back");
button.setStyle("-fx-padding: 10px;");
AnchorPane.setBottomAnchor(button, 10.0);
AnchorPane.setRightAnchor(button, 70.0);
rootPane.getChildren().add(button);
button.setOnMouseClicked(event -> {
try {
HotelMain.change_scene("customer.fxml");
} catch (IOException e) {
throw new RuntimeException(e);
}
});
int totalCount = Integer.parseInt(adultSelection) + Integer.parseInt(childrenSelection);
String sql2 = "SELECT * FROM ROOM inner join reservation on ROOM.ROOM_ID = reservation.ROOM_ID";
PreparedStatement statement1 = connection.prepareStatement(sql2);
ResultSet resultset1 = statement1.executeQuery();
int ROW=1;
while (resultset1.next()){
if(LocalDate.parse(resultset1.getString("CHECK_IN_DATE")).compareTo(((LocalDate) checkInDate.getValue())) < 0//CHECK_IN_DATE date is after checkInDate
&& LocalDate.parse(resultset1.getString("CHECK_IN_DATE")).compareTo(((LocalDate) checkOutDate.getValue())) > 0){//CHECK_IN_DATE date is before checkOutDate
continue;
}
else if(LocalDate.parse(resultset1.getString("CHECK_IN_DATE")).compareTo(((LocalDate) checkInDate.getValue())) > 0//CHECK_IN_DATE date is before checkInDate
&& LocalDate.parse(resultset1.getString("CHECK_OUT_DATE")).compareTo(((LocalDate) checkOutDate.getValue())) > 0){//CHECK_OUT_DATE date is before checkOutDate
continue;
}
else if(LocalDate.parse(resultset1.getString("CHECK_OUT_DATE")).compareTo(((LocalDate) checkInDate.getValue())) < 0//CHECK_OUT_DATE date is after checkInDate
&& LocalDate.parse(resultset1.getString("CHECK_OUT_DATE")).compareTo(((LocalDate) checkOutDate.getValue())) > 0){//CHECK_OUT_DATE date is before checkOutDate
continue;
}
else if((Integer.parseInt(resultset1.getString("ROOM_ID")) + 1 )<= ROW){
continue;
}
Rectangle box = new Rectangle(300, 100); // Create a rectangle as a box
Text nameText = new Text("Price: "+resultset1.getString("PRICE_PER_NIGHT")+" "+"Capacity: "+resultset1.getString("ROOM_CAPACITY"));
nameText.setId(String.valueOf(resultset1.getString("ROOM_ID")));
nameText.setWrappingWidth(100); // Set the width of the text box
nameText.setFont(Font.font("Arial", FontWeight.BOLD, 12));
nameText.setTextAlignment(TextAlignment.CENTER);
nameText.setMouseTransparent(true);
box.setFill(Color.AQUA);
box.setStroke(Color.BURLYWOOD);
box.setStrokeWidth(2);
box.setOnMouseClicked(event -> {
try {
String[] parts = nameText.getText().split(" ");
make_reservation(checkInDate.getValue().toString(),checkOutDate.getValue().toString(), HotelMain.getID(),box.getId(),
parts[1], adults.getText(), children.getText(), mealSelection,poolSelection, tennisCourtSelection);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (SQLException e) {
throw new RuntimeException(e);
}
});
gridPane.add(box, 1, ROW); // Add the box to the GridPane
gridPane.add(nameText, 1, ROW);
ROW++;
}
primary_stage.show();
}
@FXML
private void make_reservation(String checkInDate,String checkOutDate,String customerid ,String roomid,
String price ,String adults ,String children,boolean meal,boolean pool,boolean tennis) throws IOException, SQLException {
String sql = "INSERT INTO reservation (CHECK_IN_DATE, CHECK_OUT_DATE, CUSTOMER_ID, ROOM_ID, PRICE, ADULT_NUMBER," +
"CHILDREN_NUMBER,INCLUDED_MEAL,INCLUDED_POOL,INCLUDED_TENNIS_COURT) VALUES (?,?,?,?,?,?,?,?,?,?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, checkInDate); // Set the value for the first parameter placeholder
statement.setString(2, checkOutDate); // Set the value for the second parameter placeholder
statement.setString(3, customerid); // Set the value for the third parameter placeholder
statement.setString(4, roomid); // Set the value for the third parameter placeholder
statement.setString(5, price); // Set the value for the third parameter placeholder
statement.setString(6, adults); // Set the value for the third parameter placeholder
statement.setString(7, children); // Set the value for the third parameter placeholder
statement.setBoolean(8, meal); // Set the value for the third parameter placeholder
statement.setBoolean(9, pool); // Set the value for the third parameter placeholder
statement.setBoolean(10, tennis); // Set the value for the third parameter placeholder
int rowsInserted = statement.executeUpdate();
HotelMain.change_scene("customer.fxml");
}
}
|
24076_6
|
package gr.cti.eslate.scripting.logo;
import java.util.ListResourceBundle;
public class DatabasePrimitivesBundle_el_GR extends ListResourceBundle {
public Object [][] getContents() {
return contents;
}
static final Object[][] contents={
{"DB.SETCELL", "ΒΔ.ΘΈΣΕΚΕΛΛΙ"},
// {"SETCELL", "θκ"},
{"DB.CELL", "ΒΔ.ΚΕΛΛΙ"},
{"DB.FIELD", "ΒΔ.ΠΕΔΙΟ"},
{"DB.RECORD", "ΒΔ.ΕΓΓΡΑΦΗ"},
{"DB.RECORDCOUNT", "ΒΔ.ΑΡΙΘΜΟΣΕΓΓΡΑΦΩΝ"},
// {"RECORDCOUNT", "αεγγ"},
{"DB.SETACTIVERECORD", "ΒΔ.ΘΕΣΕΕΝΕΡΓΗΕΓΓΡΑΦΗ"},
// {"SETACTIVERECORD", "θεεγγ"},
{"DB.ACTIVERECORD", "ΒΔ.ΕΝΕΡΓΗΕΓΓΡΑΦΗ"},
// {"ACTIVERECORD", "εεγγ"},
{"DB.SELECTRECORDS", "ΒΔ.ΕΠΕΛΕΞΕΕΓΓΡΑΦΕΣ"},
// {"SELECTRECORDS", "επεγγρ"},
{"DB.SELECTEDRECORDS", "ΒΔ.ΕΠΙΛΕΓΜΕΝΕΣΕΓΓΡΑΦΕΣ"},
// {"SELECTEDRECORDS", "επεγγ"},
{"DB.SELECTEDRECORDCOUNT", "ΒΔ.ΑΡΙΘΜΟΣΕΠΙΛΕΓΜΕΝΩΝΕΓΓΡΑΦΩΝ"},
// {"SELECTEDRECORDCOUNT", "αεεγγ"},
{"DB.SELECT", "ΒΔ.ΕΠΕΛΕΞΕ"},
{"DB.CLEARSELECTION", "ΒΔ.ΚΑΘΑΡΙΣΜΟΣΕΠΙΛΟΓΗΣ"},
// {"CLEARSELECTION", "κεπ"},
{"DB.INVERTSELECTION", "ΒΔ.ΑΝΤΙΣΤΡΟΦΗΕΠΙΛΟΓΗΣ"},
// {"INVERTSELECTION", "αεπ"},
{"DB.SELECTALL", "ΒΔ.ΕΠΕΛΕΞΕΟΛΑ"},
// {"SELECTALL", "επόλα"},
{"DB.SFIELD", "ΒΔ.ΕΠΕΔΙΟ"},
{"DB.FIELDNAMES", "ΒΔ.ΟΝΟΜΑΤΑΠΕΔΙΩΝ"},
// {"FIELDNAMES", "ονπεδ"},
{"DB.DMIN", "ΒΔ.ΜΙΚΡΟΤΕΡΟΠΕΔΙΟΥ"},
// {"DMIN", "μικρΠεδ"},
{"DB.DMAX", "ΒΔ.ΜΕΓΑΛΥΤΕΡΟΠΕΔΙΟΥ"},
// {"DMAX", "μεγΠεδ"},
{"DB.DSMALL", "ΒΔ.ΜΙΚΡΟΤΕΡΟΚΑΤΑΣΕΙΡΑ"},
// {"DSMALL", "μικκσ"},
{"DB.DBIG", "ΒΔ.ΜΕΓΑΛΥΤΕΡΟΚΑΤΑΣΕΙΡΑ"},
// {"DBIG", "μεγκσ"},
{"DB.DRANK", "ΒΔ.ΔΙΑΒΑΘΜΙΣΜΕΝΟΚΑΤΑΣΕΙΡΑ"},
// {"DRANK", "διαβκσ"},
{"DB.DSUM", "ΒΔ.ΑΘΡΟΙΣΜΑΠΕΔΙΟΥ"},
// {"DSUM", "αθρπεδ"},
{"DB.DPRODUCT", "ΒΔ.ΓΙΝΟΜΕΝΟΠΕΔΙΟΥ"},
// {"DPRODUCT", "γινπεδ"},
{"DB.DAVERAGE", "ΒΔ.ΜΕΣΟΣΟΡΟΣΠΕΔΙΟΥ"},
// {"DAVERAGE", "μεσπεδ"},
{"DB.DGEOMEAN", "ΒΔ.ΓΕΩΜΕΣΟΣΠΕΔΙΟΥ"},
// {"DGEOMEAN", "γμεσπεδ"},
{"DB.DCOUNT", "ΒΔ.ΑΡΙΘΜΟΣΕΜΦΑΝΙΣΕΩΝ"},
// {"DCOUNT", "αεμφ"}
{"DB.ADDRECORD", "ΒΔ.ΠΡΟΣΘΕΣΕΕΓΓΡΑΦΗ"},
{"DB.CURTIME", "ΒΔ.ΤΡΕΧΩΝΧΡΟΝΟΣ"},
{"DB.ADDITIONALLYSELECTRECORD", "ΒΔ.ΕΠΕΛΕΞΕΕΠΙΠΛΕΟΝΕΓΓΡΑΦΗ"},
{"DB.DVARIANCE", "ΒΔ.ΔΙΑΚΥΜΑΝΣΗ"},
{"DB.DSTDEV", "ΒΔ.ΤΥΠΙΚΗΑΠΟΚΛΙΣΗ"},
{"DB.ACTIVETABLENAME", "ΒΔ.ΟΝΟΜΑΕΝΕΡΓΟΥΠΙΝΑΚΑ"},
{"DB.ADDEMPTYRECORD", "ΒΔ.ΠΡΟΣΘΕΣΕΚΕΝΗΕΓΓΡΑΦΗ"},
{"DB.ADDFIELD", "ΒΔ.ΠΡΟΣΘΕΣΕΠΕΔΙΟ"},
{"DB.ADDCALCULATEDFIELD", "ΒΔ.ΠΡΟΣΘΕΣΕΥΠΟΛΟΓΙΖΟΜΕΝΟΠΕΔΙΟ"},
{"DB.REMOVEFIELD", "ΒΔ.ΑΦΑΙΡΕΣΕΠΕΔΙΟ"},
{"DB.REMOVERECORD", "ΒΔ.ΑΦΑΙΡΕΣΕΕΓΓΡΑΦΗ"},
{"DB.SETTABLENAME", "ΒΔ.ΘΕΣΕΟΝΟΜΑΠΙΝΑΚΑ"},
{"DB.SETFIELDEDITABLE", "ΒΔ.ΘΕΣΕΠΕΔΙΟΜΕΤΑΒΑΛΛΟΜΕΝΟ"},
};
}
|
vpapakir/myeslate
|
widgetESlate/src/gr/cti/eslate/scripting/logo/DatabasePrimitivesBundle_el_GR.java
| 2,107
|
// {"FIELDNAMES", "ονπεδ"},
|
line_comment
|
el
|
package gr.cti.eslate.scripting.logo;
import java.util.ListResourceBundle;
public class DatabasePrimitivesBundle_el_GR extends ListResourceBundle {
public Object [][] getContents() {
return contents;
}
static final Object[][] contents={
{"DB.SETCELL", "ΒΔ.ΘΈΣΕΚΕΛΛΙ"},
// {"SETCELL", "θκ"},
{"DB.CELL", "ΒΔ.ΚΕΛΛΙ"},
{"DB.FIELD", "ΒΔ.ΠΕΔΙΟ"},
{"DB.RECORD", "ΒΔ.ΕΓΓΡΑΦΗ"},
{"DB.RECORDCOUNT", "ΒΔ.ΑΡΙΘΜΟΣΕΓΓΡΑΦΩΝ"},
// {"RECORDCOUNT", "αεγγ"},
{"DB.SETACTIVERECORD", "ΒΔ.ΘΕΣΕΕΝΕΡΓΗΕΓΓΡΑΦΗ"},
// {"SETACTIVERECORD", "θεεγγ"},
{"DB.ACTIVERECORD", "ΒΔ.ΕΝΕΡΓΗΕΓΓΡΑΦΗ"},
// {"ACTIVERECORD", "εεγγ"},
{"DB.SELECTRECORDS", "ΒΔ.ΕΠΕΛΕΞΕΕΓΓΡΑΦΕΣ"},
// {"SELECTRECORDS", "επεγγρ"},
{"DB.SELECTEDRECORDS", "ΒΔ.ΕΠΙΛΕΓΜΕΝΕΣΕΓΓΡΑΦΕΣ"},
// {"SELECTEDRECORDS", "επεγγ"},
{"DB.SELECTEDRECORDCOUNT", "ΒΔ.ΑΡΙΘΜΟΣΕΠΙΛΕΓΜΕΝΩΝΕΓΓΡΑΦΩΝ"},
// {"SELECTEDRECORDCOUNT", "αεεγγ"},
{"DB.SELECT", "ΒΔ.ΕΠΕΛΕΞΕ"},
{"DB.CLEARSELECTION", "ΒΔ.ΚΑΘΑΡΙΣΜΟΣΕΠΙΛΟΓΗΣ"},
// {"CLEARSELECTION", "κεπ"},
{"DB.INVERTSELECTION", "ΒΔ.ΑΝΤΙΣΤΡΟΦΗΕΠΙΛΟΓΗΣ"},
// {"INVERTSELECTION", "αεπ"},
{"DB.SELECTALL", "ΒΔ.ΕΠΕΛΕΞΕΟΛΑ"},
// {"SELECTALL", "επόλα"},
{"DB.SFIELD", "ΒΔ.ΕΠΕΔΙΟ"},
{"DB.FIELDNAMES", "ΒΔ.ΟΝΟΜΑΤΑΠΕΔΙΩΝ"},
// {"FIELDNAMES", <SUF>
{"DB.DMIN", "ΒΔ.ΜΙΚΡΟΤΕΡΟΠΕΔΙΟΥ"},
// {"DMIN", "μικρΠεδ"},
{"DB.DMAX", "ΒΔ.ΜΕΓΑΛΥΤΕΡΟΠΕΔΙΟΥ"},
// {"DMAX", "μεγΠεδ"},
{"DB.DSMALL", "ΒΔ.ΜΙΚΡΟΤΕΡΟΚΑΤΑΣΕΙΡΑ"},
// {"DSMALL", "μικκσ"},
{"DB.DBIG", "ΒΔ.ΜΕΓΑΛΥΤΕΡΟΚΑΤΑΣΕΙΡΑ"},
// {"DBIG", "μεγκσ"},
{"DB.DRANK", "ΒΔ.ΔΙΑΒΑΘΜΙΣΜΕΝΟΚΑΤΑΣΕΙΡΑ"},
// {"DRANK", "διαβκσ"},
{"DB.DSUM", "ΒΔ.ΑΘΡΟΙΣΜΑΠΕΔΙΟΥ"},
// {"DSUM", "αθρπεδ"},
{"DB.DPRODUCT", "ΒΔ.ΓΙΝΟΜΕΝΟΠΕΔΙΟΥ"},
// {"DPRODUCT", "γινπεδ"},
{"DB.DAVERAGE", "ΒΔ.ΜΕΣΟΣΟΡΟΣΠΕΔΙΟΥ"},
// {"DAVERAGE", "μεσπεδ"},
{"DB.DGEOMEAN", "ΒΔ.ΓΕΩΜΕΣΟΣΠΕΔΙΟΥ"},
// {"DGEOMEAN", "γμεσπεδ"},
{"DB.DCOUNT", "ΒΔ.ΑΡΙΘΜΟΣΕΜΦΑΝΙΣΕΩΝ"},
// {"DCOUNT", "αεμφ"}
{"DB.ADDRECORD", "ΒΔ.ΠΡΟΣΘΕΣΕΕΓΓΡΑΦΗ"},
{"DB.CURTIME", "ΒΔ.ΤΡΕΧΩΝΧΡΟΝΟΣ"},
{"DB.ADDITIONALLYSELECTRECORD", "ΒΔ.ΕΠΕΛΕΞΕΕΠΙΠΛΕΟΝΕΓΓΡΑΦΗ"},
{"DB.DVARIANCE", "ΒΔ.ΔΙΑΚΥΜΑΝΣΗ"},
{"DB.DSTDEV", "ΒΔ.ΤΥΠΙΚΗΑΠΟΚΛΙΣΗ"},
{"DB.ACTIVETABLENAME", "ΒΔ.ΟΝΟΜΑΕΝΕΡΓΟΥΠΙΝΑΚΑ"},
{"DB.ADDEMPTYRECORD", "ΒΔ.ΠΡΟΣΘΕΣΕΚΕΝΗΕΓΓΡΑΦΗ"},
{"DB.ADDFIELD", "ΒΔ.ΠΡΟΣΘΕΣΕΠΕΔΙΟ"},
{"DB.ADDCALCULATEDFIELD", "ΒΔ.ΠΡΟΣΘΕΣΕΥΠΟΛΟΓΙΖΟΜΕΝΟΠΕΔΙΟ"},
{"DB.REMOVEFIELD", "ΒΔ.ΑΦΑΙΡΕΣΕΠΕΔΙΟ"},
{"DB.REMOVERECORD", "ΒΔ.ΑΦΑΙΡΕΣΕΕΓΓΡΑΦΗ"},
{"DB.SETTABLENAME", "ΒΔ.ΘΕΣΕΟΝΟΜΑΠΙΝΑΚΑ"},
{"DB.SETFIELDEDITABLE", "ΒΔ.ΘΕΣΕΠΕΔΙΟΜΕΤΑΒΑΛΛΟΜΕΝΟ"},
};
}
|
18878_3
|
/**
* Κλάση που αναπαριστά έναν κύκλο
* <p>
* Class that represents a circle
*/
public class Circle {
double r;
/**
* Κατασκευαστής / Constructor
*
* @param r η ακτίνα του κύκλου / the circle's radius
*/
public Circle(double r) {
this.r=r;
}
/**
* Επιστρέφει το εμβαδό του κύκλου. Το εμβαδό είναι π*r*r, όπου r η ακτίνα του κύκλου. Το π μπορείτε να το πάρετε
* από την κλάση Math, με Math.PI
* <p>
* Returns the total area of the circle. The formula is π*r*r, where r is the radius of the circle. You can get π
* from the Math class, using Math.PI.
*
* @return εμβαδό του κύκλου / the circle's total area.
*/
public double getArea() {
return Math.PI*this.r*this.r;
}
/**
* Επιστρέφει την περίμετρο του κύκλου. Η περίμετρος του κύκλου ισούται με 2π*r, όπου r η ακτίνα του κύκλου.
* <p>
* Returns the perimeter of the circle. The perimeter of the circle is equal to 2π*r, where r is the circle's
* radius
*
* @return Την περίμετρο του κύκλου / the circle's perimeter.
*/
public double getPerimeter() {
return 2*Math.PI*this.r;
}
/**
* Επιστρέφει την ακτίνα του κύκλου / Returns the radius of the circle.
*
* @return ακτίνα του κύκλου / the circle's radius.
*/
public double getRadius() {
return this.r;
}
}
|
vtsipras/3rd-Semester---CSD-AUTH
|
Object-oriented programming/Labs/Lab6/src/Circle.java
| 605
|
/**
* Επιστρέφει την περίμετρο του κύκλου. Η περίμετρος του κύκλου ισούται με 2π*r, όπου r η ακτίνα του κύκλου.
* <p>
* Returns the perimeter of the circle. The perimeter of the circle is equal to 2π*r, where r is the circle's
* radius
*
* @return Την περίμετρο του κύκλου / the circle's perimeter.
*/
|
block_comment
|
el
|
/**
* Κλάση που αναπαριστά έναν κύκλο
* <p>
* Class that represents a circle
*/
public class Circle {
double r;
/**
* Κατασκευαστής / Constructor
*
* @param r η ακτίνα του κύκλου / the circle's radius
*/
public Circle(double r) {
this.r=r;
}
/**
* Επιστρέφει το εμβαδό του κύκλου. Το εμβαδό είναι π*r*r, όπου r η ακτίνα του κύκλου. Το π μπορείτε να το πάρετε
* από την κλάση Math, με Math.PI
* <p>
* Returns the total area of the circle. The formula is π*r*r, where r is the radius of the circle. You can get π
* from the Math class, using Math.PI.
*
* @return εμβαδό του κύκλου / the circle's total area.
*/
public double getArea() {
return Math.PI*this.r*this.r;
}
/**
* Επιστρέφει την περίμετρο<SUF>*/
public double getPerimeter() {
return 2*Math.PI*this.r;
}
/**
* Επιστρέφει την ακτίνα του κύκλου / Returns the radius of the circle.
*
* @return ακτίνα του κύκλου / the circle's radius.
*/
public double getRadius() {
return this.r;
}
}
|
4407_0
|
package com.unipi.chrisavg.eventity;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.login.LoginManager;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.AutocompletePrediction;
import com.google.android.libraries.places.api.model.AutocompleteSessionToken;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.net.FetchPlaceRequest;
import com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.SearchView;
import androidx.core.app.ActivityCompat;
import androidx.core.view.GravityCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.unipi.chrisavg.eventity.databinding.ActivityMainBinding;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
private ActivityMainBinding binding;
FirebaseAuth mAuth;
CollectionReference users;
FirebaseFirestore db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.appBarMain.toolbar);
setStatusBarCustomColor(this);
mAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
users = db.collection("Users");
DrawerLayout drawer = binding.drawerLayout;
NavigationView navigationView = binding.navView;
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_tickets, R.id.nav_settings,R.id.nav_bot)
.setOpenableLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
//Απο εδώ κάνουμε την ανακατεύθυνση στα items του navigation drawer
navigationView.setNavigationItemSelectedListener(item -> {
switch (item.getItemId()) {
case R.id.nav_home:
navController.navigate(R.id.nav_home);
break;
case R.id.nav_tickets:
navController.navigate(R.id.nav_tickets);
break;
case R.id.nav_settings:
navController.navigate(R.id.nav_settings);
break;
case R.id.nav_bot:
navController.navigate(R.id.nav_bot);
break;
case R.id.nav_logout:
SignOut();
break;
}
// Κλείσιμο του navigation drawer μετά την επιλογή στοιχείου
drawer.closeDrawer(GravityCompat.START);
return true;
});
//Αν κάποιο activity έχει δώσει εντολή να ανοίξουμε το tickets fragment τοτε ανακατευθύνουμε στο MainActivity
// δηλαδή το συγκεκριμένο καθώς ειναι το κυριο activity που ρυθμίζει και τα navigations στα nav drawer items.
Intent intent = getIntent();
boolean openTicketsFragment = false;
if (intent != null) {
openTicketsFragment = intent.getBooleanExtra("OpenTicketsFragment",false);
}
if (openTicketsFragment){
navController.navigate(R.id.nav_tickets);
}
// Αλλάζουμε το title του nav_header_main
TextView textViewHeaderTitle = navigationView.getHeaderView(0).findViewById(R.id.textViewHeaderTitle);
textViewHeaderTitle.setText(mAuth.getCurrentUser().getDisplayName());
// Αλλάζουμε το subtitle του nav_header_main
TextView textViewHeaderSubtitle = navigationView.getHeaderView(0).findViewById(R.id.textViewHeaderSubtitle);
textViewHeaderSubtitle.setText(mAuth.getCurrentUser().getEmail());
}
private void setStatusBarCustomColor(AppCompatActivity activity){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
activity.getWindow().setStatusBarColor(getResources().getColor(R.color.statusBarColor));
}
}
@Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
public void SignOut(){
mAuth.signOut();
LoginManager.getInstance().logOut();
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().remove("preferencesSelected").apply();
Intent intent = new Intent(MainActivity.this,WelcomeActivity.class);
startActivity(intent);
finish();
}
@Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
String preferencesSelected = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("preferencesSelected",null);
if(currentUser!= null && preferencesSelected!=null ){
//Αν ο χρηστης δεν εχει επιλεξει τα ενδιαφεροντα του τον ανακατευθυνουμε στο HobbySelection activity για να επιλεξει
if (preferencesSelected.equals("False")){
Intent intent = new Intent(MainActivity.this,HobbySelection.class);
startActivity(intent);
finish();
}
}
}
}
|
xristos-avgerinos/Eventity
|
app/src/main/java/com/unipi/chrisavg/eventity/MainActivity.java
| 1,842
|
//Απο εδώ κάνουμε την ανακατεύθυνση στα items του navigation drawer
|
line_comment
|
el
|
package com.unipi.chrisavg.eventity;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.login.LoginManager;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.AutocompletePrediction;
import com.google.android.libraries.places.api.model.AutocompleteSessionToken;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.net.FetchPlaceRequest;
import com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.SearchView;
import androidx.core.app.ActivityCompat;
import androidx.core.view.GravityCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.unipi.chrisavg.eventity.databinding.ActivityMainBinding;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
private ActivityMainBinding binding;
FirebaseAuth mAuth;
CollectionReference users;
FirebaseFirestore db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.appBarMain.toolbar);
setStatusBarCustomColor(this);
mAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
users = db.collection("Users");
DrawerLayout drawer = binding.drawerLayout;
NavigationView navigationView = binding.navView;
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_tickets, R.id.nav_settings,R.id.nav_bot)
.setOpenableLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
//Απο εδώ<SUF>
navigationView.setNavigationItemSelectedListener(item -> {
switch (item.getItemId()) {
case R.id.nav_home:
navController.navigate(R.id.nav_home);
break;
case R.id.nav_tickets:
navController.navigate(R.id.nav_tickets);
break;
case R.id.nav_settings:
navController.navigate(R.id.nav_settings);
break;
case R.id.nav_bot:
navController.navigate(R.id.nav_bot);
break;
case R.id.nav_logout:
SignOut();
break;
}
// Κλείσιμο του navigation drawer μετά την επιλογή στοιχείου
drawer.closeDrawer(GravityCompat.START);
return true;
});
//Αν κάποιο activity έχει δώσει εντολή να ανοίξουμε το tickets fragment τοτε ανακατευθύνουμε στο MainActivity
// δηλαδή το συγκεκριμένο καθώς ειναι το κυριο activity που ρυθμίζει και τα navigations στα nav drawer items.
Intent intent = getIntent();
boolean openTicketsFragment = false;
if (intent != null) {
openTicketsFragment = intent.getBooleanExtra("OpenTicketsFragment",false);
}
if (openTicketsFragment){
navController.navigate(R.id.nav_tickets);
}
// Αλλάζουμε το title του nav_header_main
TextView textViewHeaderTitle = navigationView.getHeaderView(0).findViewById(R.id.textViewHeaderTitle);
textViewHeaderTitle.setText(mAuth.getCurrentUser().getDisplayName());
// Αλλάζουμε το subtitle του nav_header_main
TextView textViewHeaderSubtitle = navigationView.getHeaderView(0).findViewById(R.id.textViewHeaderSubtitle);
textViewHeaderSubtitle.setText(mAuth.getCurrentUser().getEmail());
}
private void setStatusBarCustomColor(AppCompatActivity activity){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
activity.getWindow().setStatusBarColor(getResources().getColor(R.color.statusBarColor));
}
}
@Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
public void SignOut(){
mAuth.signOut();
LoginManager.getInstance().logOut();
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().remove("preferencesSelected").apply();
Intent intent = new Intent(MainActivity.this,WelcomeActivity.class);
startActivity(intent);
finish();
}
@Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
String preferencesSelected = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("preferencesSelected",null);
if(currentUser!= null && preferencesSelected!=null ){
//Αν ο χρηστης δεν εχει επιλεξει τα ενδιαφεροντα του τον ανακατευθυνουμε στο HobbySelection activity για να επιλεξει
if (preferencesSelected.equals("False")){
Intent intent = new Intent(MainActivity.this,HobbySelection.class);
startActivity(intent);
finish();
}
}
}
}
|
17680_6
|
package com.unipi.chrisavg.smartalert;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class AddAlertActivity extends AppCompatActivity implements LocationListener {
EditText titleEditText;
EditText timestampEditText;
EditText locationEditText;
EditText descriptionEditText;
Spinner dropdown;
LocationManager locationManager;
FirebaseDatabase database;
DatabaseReference reference;
Location locationForModel;
Date dateForModel;
ProgressBar progressBar;
Map<String,String> languageCat;
String[] items;
ArrayAdapter<String> adapter;
SimpleDateFormat formatter;
Intent intent;
static final int LOCATION_SETTINGS_REQUEST = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_alert);
titleEditText = findViewById(R.id.titleEditText);
timestampEditText = findViewById(R.id.timestampEditText);
locationEditText = findViewById(R.id.locationEditText);
dropdown = findViewById(R.id.spinner);
descriptionEditText = findViewById(R.id.descriptionEditText);
progressBar = findViewById(R.id.progressBar);
languageCat=new HashMap<>();
languageCat.put( "Πλημμύρα" ,"Flood" );
languageCat.put( "Πυρκαγιά" ,"Fire" );
languageCat.put( "Σεισμός" ,"Earthquake" );
languageCat.put( "Ακραία Θερμοκρασία","Extreme Temperature" );
languageCat.put( "Χιονοθύελλα" ,"Snowstorm" );
languageCat.put( "Ανεμοστρόβυλος" ,"Tornado" );
languageCat.put( "Καταιγίδα" ,"Storm" );
database = FirebaseDatabase.getInstance();
reference = database.getReference("Emergency Alerts");
//φτιαχνω εναν adapter με τα στοιχεια της λιστας items και το περναω στο dropdown spinner
items = new String[]{getString(R.string.select_alert_category),getString(R.string.flood), getString(R.string.fire), getString(R.string.earthquake), getString(R.string.extreme_temperature),getString(R.string.snowstorm),getString(R.string.tornado),getString(R.string.storm)};
adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items){
@Override
public boolean isEnabled(int position){
// Disable the first item from Spinner
// First item will be use for hint
return position != 0;
}
@Override
public View getDropDownView(
int position, View convertView,
@NonNull ViewGroup parent) {
// Get the item view
View view = super.getDropDownView(
position, convertView, parent);
TextView textView = (TextView) view;
if(position == 0){
// Set the hint text color gray
textView.setTextColor(Color.GRAY);
}
else { textView.setTextColor(Color.BLACK); }
return view;
}
};
dropdown.setAdapter(adapter);
getSupportActionBar().setTitle(R.string.new_emergency_alert);
formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm");
dateForModel = new Date();
timestampEditText.setText(formatter.format(dateForModel));
timestampEditText.setKeyListener(null);
locationEditText.setKeyListener(null);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//κανω εναν τυπικο ελεγχο αν εχω τα permissions αν και για να εχω φτασει σε αυτο το activity ο χρηστης εχει αποδεχτει τα permissions
finish();
}else{
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(!isGPSEnabled){ //αν δεν εχει ανοιξει το location στο κινητο του τοτε τον στελνω στα settings αν θελει ωστε να το ανοιξει και να παρω την τοποθεσια του
showSettingsAlert();
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,this);
}
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle(R.string.gps_settings);
alertDialog.setMessage(R.string.settings_menu);
alertDialog.setPositiveButton(R.string.settings, (dialog, which) -> {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent,LOCATION_SETTINGS_REQUEST);
});
alertDialog.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.cancel());
alertDialog.show();
}
public void showMessage(String title, String text){
new AlertDialog.Builder(this)
.setCancelable(true)
.setTitle(title)
.setMessage(text)
.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.actionbar1,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
intent = new Intent(getApplicationContext(), CitizenProfileActivity.class);
switch(item.getItemId()) {
case R.id.CancelButton:
finish();
startActivity(intent);
break;
case R.id.SaveButton:
if (locationEditText.getText().toString().isEmpty()){ //δεν μπορει να γινει αποθηκευση του alert αν δεν εχει παρθει το location του χρηστη αυτοματα
showMessage(getString(R.string.no_gps_connection),getString(R.string.gps_loading));
}
else if (titleEditText.getText().toString().trim().isEmpty() ){
showMessage(getString(R.string.simple_title),getString(R.string.please_give_a_title));
}else if(dropdown.getSelectedItemPosition() == 0){
showMessage(getString(R.string.simple_category), getString(R.string.select_category));
}
else{
//Save category only in english locale
String category;
if(languageCat.containsKey(dropdown.getSelectedItem().toString())){
category =languageCat.get(dropdown.getSelectedItem().toString());
}else{
category=dropdown.getSelectedItem().toString();
}
EmergencyAlerts emergencyAlerts = new EmergencyAlerts(titleEditText.getText().toString(), dateForModel.getTime() ,
locationForModel.getLatitude(),locationForModel.getLongitude(),
locationEditText.getText().toString(),category,descriptionEditText.getText().toString());
reference.push().setValue(emergencyAlerts, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(@Nullable DatabaseError error, @NonNull DatabaseReference ref) {
if (error == null){
Toast.makeText(AddAlertActivity.this, getString(R.string.alert_reported), Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(AddAlertActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
finish();
startActivity(intent);
}
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
@Override
public void onLocationChanged(@NonNull Location location) {
Geocoder geocoder;
List<Address> addresses = new ArrayList<>();
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
} catch (IOException e) {
e.printStackTrace();
}
//απο τις συντεταγμενες latitude και longitude παιρνω την διευθνυση του και οτι αλλη πληροφορια θελω
String address;
if (addresses.size()!=0){
address = addresses.get(0).getAddressLine(0);
locationEditText.setText(address);
locationForModel = location;
progressBar.setVisibility(View.GONE);
locationManager.removeUpdates(this);
}
}
@Override
public void onProviderEnabled(@NonNull String provider) {
}
@Override
public void onProviderDisabled(@NonNull String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LOCATION_SETTINGS_REQUEST) {
// user is back from location settings
finish();
startActivity(getIntent()); //reload activity to get location
}
}
}
|
xristos-avgerinos/SmartAlert
|
app/src/main/java/com/unipi/chrisavg/smartalert/AddAlertActivity.java
| 2,607
|
//αν δεν εχει ανοιξει το location στο κινητο του τοτε τον στελνω στα settings αν θελει ωστε να το ανοιξει και να παρω την τοποθεσια του
|
line_comment
|
el
|
package com.unipi.chrisavg.smartalert;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class AddAlertActivity extends AppCompatActivity implements LocationListener {
EditText titleEditText;
EditText timestampEditText;
EditText locationEditText;
EditText descriptionEditText;
Spinner dropdown;
LocationManager locationManager;
FirebaseDatabase database;
DatabaseReference reference;
Location locationForModel;
Date dateForModel;
ProgressBar progressBar;
Map<String,String> languageCat;
String[] items;
ArrayAdapter<String> adapter;
SimpleDateFormat formatter;
Intent intent;
static final int LOCATION_SETTINGS_REQUEST = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_alert);
titleEditText = findViewById(R.id.titleEditText);
timestampEditText = findViewById(R.id.timestampEditText);
locationEditText = findViewById(R.id.locationEditText);
dropdown = findViewById(R.id.spinner);
descriptionEditText = findViewById(R.id.descriptionEditText);
progressBar = findViewById(R.id.progressBar);
languageCat=new HashMap<>();
languageCat.put( "Πλημμύρα" ,"Flood" );
languageCat.put( "Πυρκαγιά" ,"Fire" );
languageCat.put( "Σεισμός" ,"Earthquake" );
languageCat.put( "Ακραία Θερμοκρασία","Extreme Temperature" );
languageCat.put( "Χιονοθύελλα" ,"Snowstorm" );
languageCat.put( "Ανεμοστρόβυλος" ,"Tornado" );
languageCat.put( "Καταιγίδα" ,"Storm" );
database = FirebaseDatabase.getInstance();
reference = database.getReference("Emergency Alerts");
//φτιαχνω εναν adapter με τα στοιχεια της λιστας items και το περναω στο dropdown spinner
items = new String[]{getString(R.string.select_alert_category),getString(R.string.flood), getString(R.string.fire), getString(R.string.earthquake), getString(R.string.extreme_temperature),getString(R.string.snowstorm),getString(R.string.tornado),getString(R.string.storm)};
adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items){
@Override
public boolean isEnabled(int position){
// Disable the first item from Spinner
// First item will be use for hint
return position != 0;
}
@Override
public View getDropDownView(
int position, View convertView,
@NonNull ViewGroup parent) {
// Get the item view
View view = super.getDropDownView(
position, convertView, parent);
TextView textView = (TextView) view;
if(position == 0){
// Set the hint text color gray
textView.setTextColor(Color.GRAY);
}
else { textView.setTextColor(Color.BLACK); }
return view;
}
};
dropdown.setAdapter(adapter);
getSupportActionBar().setTitle(R.string.new_emergency_alert);
formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm");
dateForModel = new Date();
timestampEditText.setText(formatter.format(dateForModel));
timestampEditText.setKeyListener(null);
locationEditText.setKeyListener(null);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//κανω εναν τυπικο ελεγχο αν εχω τα permissions αν και για να εχω φτασει σε αυτο το activity ο χρηστης εχει αποδεχτει τα permissions
finish();
}else{
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(!isGPSEnabled){ //αν δεν<SUF>
showSettingsAlert();
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,this);
}
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle(R.string.gps_settings);
alertDialog.setMessage(R.string.settings_menu);
alertDialog.setPositiveButton(R.string.settings, (dialog, which) -> {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent,LOCATION_SETTINGS_REQUEST);
});
alertDialog.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.cancel());
alertDialog.show();
}
public void showMessage(String title, String text){
new AlertDialog.Builder(this)
.setCancelable(true)
.setTitle(title)
.setMessage(text)
.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.actionbar1,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
intent = new Intent(getApplicationContext(), CitizenProfileActivity.class);
switch(item.getItemId()) {
case R.id.CancelButton:
finish();
startActivity(intent);
break;
case R.id.SaveButton:
if (locationEditText.getText().toString().isEmpty()){ //δεν μπορει να γινει αποθηκευση του alert αν δεν εχει παρθει το location του χρηστη αυτοματα
showMessage(getString(R.string.no_gps_connection),getString(R.string.gps_loading));
}
else if (titleEditText.getText().toString().trim().isEmpty() ){
showMessage(getString(R.string.simple_title),getString(R.string.please_give_a_title));
}else if(dropdown.getSelectedItemPosition() == 0){
showMessage(getString(R.string.simple_category), getString(R.string.select_category));
}
else{
//Save category only in english locale
String category;
if(languageCat.containsKey(dropdown.getSelectedItem().toString())){
category =languageCat.get(dropdown.getSelectedItem().toString());
}else{
category=dropdown.getSelectedItem().toString();
}
EmergencyAlerts emergencyAlerts = new EmergencyAlerts(titleEditText.getText().toString(), dateForModel.getTime() ,
locationForModel.getLatitude(),locationForModel.getLongitude(),
locationEditText.getText().toString(),category,descriptionEditText.getText().toString());
reference.push().setValue(emergencyAlerts, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(@Nullable DatabaseError error, @NonNull DatabaseReference ref) {
if (error == null){
Toast.makeText(AddAlertActivity.this, getString(R.string.alert_reported), Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(AddAlertActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
finish();
startActivity(intent);
}
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
@Override
public void onLocationChanged(@NonNull Location location) {
Geocoder geocoder;
List<Address> addresses = new ArrayList<>();
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
} catch (IOException e) {
e.printStackTrace();
}
//απο τις συντεταγμενες latitude και longitude παιρνω την διευθνυση του και οτι αλλη πληροφορια θελω
String address;
if (addresses.size()!=0){
address = addresses.get(0).getAddressLine(0);
locationEditText.setText(address);
locationForModel = location;
progressBar.setVisibility(View.GONE);
locationManager.removeUpdates(this);
}
}
@Override
public void onProviderEnabled(@NonNull String provider) {
}
@Override
public void onProviderDisabled(@NonNull String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LOCATION_SETTINGS_REQUEST) {
// user is back from location settings
finish();
startActivity(getIntent()); //reload activity to get location
}
}
}
|
27212_2
|
//κλαση animal
package com.company;
import java.io.*;
public class Animal implements Serializable {
private String code;
private String name;
private String homogeneity;
private double weight;
private int age;
//δημιουργια constuctor περνωντας ως ορισματα τις ιδιοτητες του καθε ζωου επειδη ολα τα ζωα εχουν τις συγκεκριμενες ιδιοτητες
public Animal(String code, String name, String homogeneity, double weight, int age) {
this.code = code;
this.name = name;
this.homogeneity = homogeneity;
this.weight = weight;
this.age = age;
}
//δημιουργουμε getters και setters
//χρειαζομαι τους setters ωστε στην επεξεργασια να αλλαζω τις τιμες που εχω περσαει στο καθε ζωο μεσω του constructor
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHomogeneity() {
return homogeneity;
}
public void setHomogeneity(String homogeneity) {
this.homogeneity = homogeneity;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
|
xristos-avgerinos/Virtual-Zoo-Control-Application
|
demo/src/com/company/Animal.java
| 502
|
//χρειαζομαι τους setters ωστε στην επεξεργασια να αλλαζω τις τιμες που εχω περσαει στο καθε ζωο μεσω του constructor
|
line_comment
|
el
|
//κλαση animal
package com.company;
import java.io.*;
public class Animal implements Serializable {
private String code;
private String name;
private String homogeneity;
private double weight;
private int age;
//δημιουργια constuctor περνωντας ως ορισματα τις ιδιοτητες του καθε ζωου επειδη ολα τα ζωα εχουν τις συγκεκριμενες ιδιοτητες
public Animal(String code, String name, String homogeneity, double weight, int age) {
this.code = code;
this.name = name;
this.homogeneity = homogeneity;
this.weight = weight;
this.age = age;
}
//δημιουργουμε getters και setters
//χρειαζομαι τους<SUF>
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHomogeneity() {
return homogeneity;
}
public void setHomogeneity(String homogeneity) {
this.homogeneity = homogeneity;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
|
15128_1
|
package squidpony.gdx.tests;
import com.badlogic.gdx.utils.IntSet;
import java.io.InputStream;
import java.util.TreeSet;
/**
* Created by Tommy Ettinger on 12/1/2016.
*/
public class FontMerge {
private static String stringifyStream(InputStream is) {
java.util.Scanner s = new java.util.Scanner(is);
s.useDelimiter("\\A");
String nx = s.hasNext() ? s.next() : "";
s.close();
return nx;
}
public static void main(String[] args)
{
IntSet inco = new IntSet(1024), scp = new IntSet(1024),
cm = new IntSet(1024), gent = new IntSet(1024);
TreeSet<Character> all = new TreeSet<>();
String iStr = stringifyStream(FontMerge.class.getResourceAsStream("/InconsolataLGC.txt")),
sStr = stringifyStream(FontMerge.class.getResourceAsStream("/SourceCodePro.txt")),
cStr = stringifyStream(FontMerge.class.getResourceAsStream("/CM.txt")),
gStr = stringifyStream(FontMerge.class.getResourceAsStream("/Gentium.txt"));
for (int i = 0; i < iStr.length(); i++) {
inco.add(iStr.codePointAt(i));
}
for (int i = 0; i < sStr.length(); i++) {
scp.add(sStr.codePointAt(i));
}
for (int i = 0; i < cStr.length(); i++) {
cm.add(cStr.codePointAt(i));
}
for (int i = 0; i < gStr.length(); i++) {
gent.add(gStr.codePointAt(i));
}
IntSet.IntSetIterator ii = inco.iterator();
int q;
while (ii.hasNext)
{
q = ii.next();
if(scp.contains(q) && cm.contains(q))// && gent.contains(q))
{
all.add((char)q);
}
}
int shown = 0;
for(Character c : all)
{
if(c >= 32)
{
System.out.print(c);
if(++shown >= 80)
{
shown = 0;
System.out.println();
}
}
}
}
}
/*
" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmno"+
"pqrstuvwxyz{|}~¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàá"+
"âãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİı"+
"IJijĴĵĶķĹĺĻļĽľĿŀŁłŃńŅņŇňŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƒǺǻǼǽǾ"+
"ǿȘșȚțȷˆˇˉˋ˘˙˚˛˜˝;΄΅Ά·ΈΉΊΌΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυ"+
"φχψωϊϋόύώЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхц"+
"чшщъыьэюяѐёђѓєѕіїјљњћќѝўџѢѣѲѳѴѵҐґẀẁẂẃẄẅỲỳ–—‘’‚‛“”„†‡•…‰‹›ⁿ₤€№™Ω℮←↑→↓∆−√≈─│┌┐└┘├┤"+
"┬┴┼═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫■□▪▫▲▼◊○●◦♀♂♠♣♥♦♪"
*/
|
yellowstonegames/SquidLib
|
squidlib/etc/FontMerge.java
| 1,505
|
/*
" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmno"+
"pqrstuvwxyz{|}~¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàá"+
"âãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİı"+
"IJijĴĵĶķĹĺĻļĽľĿŀŁłŃńŅņŇňŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƒǺǻǼǽǾ"+
"ǿȘșȚțȷˆˇˉˋ˘˙˚˛˜˝;΄΅Ά·ΈΉΊΌΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυ"+
"φχψωϊϋόύώЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхц"+
"чшщъыьэюяѐёђѓєѕіїјљњћќѝўџѢѣѲѳѴѵҐґẀẁẂẃẄẅỲỳ–—‘’‚‛“”„†‡•…‰‹›ⁿ₤€№™Ω℮←↑→↓∆−√≈─│┌┐└┘├┤"+
"┬┴┼═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫■□▪▫▲▼◊○●◦♀♂♠♣♥♦♪"
*/
|
block_comment
|
el
|
package squidpony.gdx.tests;
import com.badlogic.gdx.utils.IntSet;
import java.io.InputStream;
import java.util.TreeSet;
/**
* Created by Tommy Ettinger on 12/1/2016.
*/
public class FontMerge {
private static String stringifyStream(InputStream is) {
java.util.Scanner s = new java.util.Scanner(is);
s.useDelimiter("\\A");
String nx = s.hasNext() ? s.next() : "";
s.close();
return nx;
}
public static void main(String[] args)
{
IntSet inco = new IntSet(1024), scp = new IntSet(1024),
cm = new IntSet(1024), gent = new IntSet(1024);
TreeSet<Character> all = new TreeSet<>();
String iStr = stringifyStream(FontMerge.class.getResourceAsStream("/InconsolataLGC.txt")),
sStr = stringifyStream(FontMerge.class.getResourceAsStream("/SourceCodePro.txt")),
cStr = stringifyStream(FontMerge.class.getResourceAsStream("/CM.txt")),
gStr = stringifyStream(FontMerge.class.getResourceAsStream("/Gentium.txt"));
for (int i = 0; i < iStr.length(); i++) {
inco.add(iStr.codePointAt(i));
}
for (int i = 0; i < sStr.length(); i++) {
scp.add(sStr.codePointAt(i));
}
for (int i = 0; i < cStr.length(); i++) {
cm.add(cStr.codePointAt(i));
}
for (int i = 0; i < gStr.length(); i++) {
gent.add(gStr.codePointAt(i));
}
IntSet.IntSetIterator ii = inco.iterator();
int q;
while (ii.hasNext)
{
q = ii.next();
if(scp.contains(q) && cm.contains(q))// && gent.contains(q))
{
all.add((char)q);
}
}
int shown = 0;
for(Character c : all)
{
if(c >= 32)
{
System.out.print(c);
if(++shown >= 80)
{
shown = 0;
System.out.println();
}
}
}
}
}
/*
" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmno"+
"pqrstuvwxyz{|}~¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàá"+<SUF>*/
|
2784_10
|
/*
This file is part of Arcadeflex.
Arcadeflex 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.
Arcadeflex 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 Arcadeflex. If not, see <http://www.gnu.org/licenses/>.
*/
package gr.codebb.arcadeflex_convertor;
/**
*
* @author george
*/
public class machineConvert {
static final int machine_mem_read=20;
static final int machine_mem_write=21;
static final int machine_init=22;
static final int machine_interrupt=25;
public static void ConvertMachine()
{
Convertor.inpos = 0;//position of pointer inside the buffers
Convertor.outpos = 0;
boolean only_once_flag=false;//gia na baleis to header mono mia fora
boolean line_change_flag=false;
int type=0;
int l=0;
int k=0;
label0:
do
{
if(Convertor.inpos >= Convertor.inbuf.length)//an to megethos einai megalitero spase to loop
{
break;
}
char c = sUtil.getChar(); //pare ton character
if(line_change_flag)
{
for(int i1 = 0; i1 < k; i1++)
{
sUtil.putString("\t");
}
line_change_flag = false;
}
switch(c)
{
case 35: // '#'
if(!sUtil.getToken("#include"))//an den einai #include min to trexeis
{
break;
}
sUtil.skipLine();
if(!only_once_flag)//trekse auto to komati mono otan bris to proto include
{
only_once_flag = true;
sUtil.putString("/*\r\n");
sUtil.putString(" * ported to v" + Convertor.mameversion + "\r\n");
sUtil.putString(" * using automatic conversion tool v" + Convertor.convertorversion + "\r\n");
/*sUtil.putString(" * converted at : " + Convertor.timenow() + "\r\n");*/
sUtil.putString(" *\r\n");
sUtil.putString(" *\r\n");
sUtil.putString(" *\r\n");
sUtil.putString(" */ \r\n");
sUtil.putString("package machine;\r\n");
sUtil.putString("\r\n");
sUtil.putString((new StringBuilder()).append("public class ").append(Convertor.className).append("\r\n").toString());
sUtil.putString("{\r\n");
k=1;
line_change_flag = true;
}
continue;
case 10: // '\n'
Convertor.outbuf[Convertor.outpos++] = Convertor.inbuf[Convertor.inpos++];
line_change_flag = true;
continue;
case 45: // '-'
char c3 = sUtil.getNextChar();
if(c3 != '>')
{
break;
}
Convertor.outbuf[Convertor.outpos++] = '.';
Convertor.inpos += 2;
continue;
case 105: // 'i'
int i = Convertor.inpos;
if(sUtil.getToken("if"))
{
sUtil.skipSpace();
if(sUtil.parseChar() != '(')
{
Convertor.inpos = i;
break;
}
sUtil.skipSpace();
Convertor.token[0] = sUtil.parseToken();
sUtil.skipSpace();
if(sUtil.getChar() == '&')
{
Convertor.inpos++;
sUtil.skipSpace();
Convertor.token[1] = sUtil.parseToken();
sUtil.skipSpace();
Convertor.token[0] = (new StringBuilder()).append("(").append(Convertor.token[0]).append(" & ").append(Convertor.token[1]).append(")").toString();
}
if(sUtil.parseChar() != ')')
{
Convertor.inpos = i;
break;
}
sUtil.putString((new StringBuilder()).append("if (").append(Convertor.token[0]).append(" != 0)").toString());
continue;
}
if(!sUtil.getToken("int"))
{
break;
}
sUtil.skipSpace();
Convertor.token[0] = sUtil.parseToken();
sUtil.skipSpace();
if(sUtil.parseChar() != '(')
{
Convertor.inpos = i;
break;
}
sUtil.skipSpace();
if(sUtil.getToken("void"))//an to soma tis function einai (void)
{
if(sUtil.parseChar() != ')')
{
Convertor.inpos = i;
break;
}
if(Convertor.token[0].contains("_interrupt"))
{
sUtil.putString((new StringBuilder()).append("public static InterruptPtr ").append(Convertor.token[0]).append(" = new InterruptPtr() { public int handler() ").toString());
type = machine_interrupt;
l = -1;
continue label0; //ξαναργυρνα στην αρχη για να μην γραψεις και την παλια συνάρτηση
}
}
if(sUtil.getToken("int"))
{
sUtil.skipSpace();
Convertor.token[1] = sUtil.parseToken();
sUtil.skipSpace();
if(sUtil.parseChar() != ')')
{
Convertor.inpos = i;
break;
}
sUtil.skipSpace();
if(Convertor.token[0].length()>0 && Convertor.token[1].length()>0)
{
sUtil.putString((new StringBuilder()).append("public static ReadHandlerPtr ").append(Convertor.token[0]).append(" = new ReadHandlerPtr() { public int handler(int ").append(Convertor.token[1]).append(")").toString());
type = machine_mem_read;
l = -1;
continue label0;
}
}
Convertor.inpos = i;
break;
case 118: // 'v'
int j = Convertor.inpos;
if(!sUtil.getToken("void"))
{
break;
}
sUtil.skipSpace();
Convertor.token[0] = sUtil.parseToken();
sUtil.skipSpace();
if(sUtil.parseChar() != '(')
{
Convertor.inpos = j;
break;
}
sUtil.skipSpace();
if(sUtil.getToken("void"))//an to soma tis function einai (void)
{
if(sUtil.parseChar() != ')')
{
Convertor.inpos = j;
break;
}
if(Convertor.token[0].contains("init_machine"))
{
sUtil.putString((new StringBuilder()).append("public static InitMachinePtr ").append(Convertor.token[0]).append(" = new InitMachinePtr() { public void handler() ").toString());
type = machine_init;
l = -1;
continue label0; //ξαναργυρνα στην αρχη για να μην γραψεις και την παλια συνάρτηση
}
}
if(!sUtil.getToken("int"))
{
Convertor.inpos = j;
break;
}
sUtil.skipSpace();
Convertor.token[1] = sUtil.parseToken();
sUtil.skipSpace();
if(sUtil.parseChar() != ',')
{
Convertor.inpos = j;
break;
}
sUtil.skipSpace();
if(!sUtil.getToken("int"))
{
Convertor.inpos = j;
break;
}
sUtil.skipSpace();
Convertor.token[2] = sUtil.parseToken();
sUtil.skipSpace();
if(sUtil.parseChar() != ')')
{
Convertor.inpos = j;
break;
}
sUtil.skipSpace();
if(Convertor.token[0].length()>0 && Convertor.token[1].length()>0 && Convertor.token[2].length()>0)
{
sUtil.putString((new StringBuilder()).append("public static WriteHandlerPtr ").append(Convertor.token[0]).append(" = new WriteHandlerPtr() { public void handler(int ").append(Convertor.token[1]).append(", int ").append(Convertor.token[2]).append(")").toString());
type = machine_mem_write;
l = -1;
continue label0; //ξαναργυρνα στην αρχη για να μην γραψεις και την παλια συνάρτηση
}
Convertor.inpos = j;
break;
case 123: // '{'
l++;
break;
case 125: // '}'
l--;
if(type != machine_mem_read && type != machine_mem_write && type!=machine_init && type!=machine_interrupt || l != -1)
{
break;
}
sUtil.putString("} };");
Convertor.inpos++;
type = -1;
continue;
}
Convertor.outbuf[Convertor.outpos++] = Convertor.inbuf[Convertor.inpos++];//grapse to inputbuffer sto output
}while(true);
if(only_once_flag)
{
sUtil.putString("}\r\n");
}
}
}
|
yuripourre-forks/arcadeflex036
|
convertor/src/main/java/gr/codebb/arcadeflex_convertor/machineConvert.java
| 2,434
|
//ξαναργυρνα στην αρχη για να μην γραψεις και την παλια συνάρτηση
|
line_comment
|
el
|
/*
This file is part of Arcadeflex.
Arcadeflex 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.
Arcadeflex 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 Arcadeflex. If not, see <http://www.gnu.org/licenses/>.
*/
package gr.codebb.arcadeflex_convertor;
/**
*
* @author george
*/
public class machineConvert {
static final int machine_mem_read=20;
static final int machine_mem_write=21;
static final int machine_init=22;
static final int machine_interrupt=25;
public static void ConvertMachine()
{
Convertor.inpos = 0;//position of pointer inside the buffers
Convertor.outpos = 0;
boolean only_once_flag=false;//gia na baleis to header mono mia fora
boolean line_change_flag=false;
int type=0;
int l=0;
int k=0;
label0:
do
{
if(Convertor.inpos >= Convertor.inbuf.length)//an to megethos einai megalitero spase to loop
{
break;
}
char c = sUtil.getChar(); //pare ton character
if(line_change_flag)
{
for(int i1 = 0; i1 < k; i1++)
{
sUtil.putString("\t");
}
line_change_flag = false;
}
switch(c)
{
case 35: // '#'
if(!sUtil.getToken("#include"))//an den einai #include min to trexeis
{
break;
}
sUtil.skipLine();
if(!only_once_flag)//trekse auto to komati mono otan bris to proto include
{
only_once_flag = true;
sUtil.putString("/*\r\n");
sUtil.putString(" * ported to v" + Convertor.mameversion + "\r\n");
sUtil.putString(" * using automatic conversion tool v" + Convertor.convertorversion + "\r\n");
/*sUtil.putString(" * converted at : " + Convertor.timenow() + "\r\n");*/
sUtil.putString(" *\r\n");
sUtil.putString(" *\r\n");
sUtil.putString(" *\r\n");
sUtil.putString(" */ \r\n");
sUtil.putString("package machine;\r\n");
sUtil.putString("\r\n");
sUtil.putString((new StringBuilder()).append("public class ").append(Convertor.className).append("\r\n").toString());
sUtil.putString("{\r\n");
k=1;
line_change_flag = true;
}
continue;
case 10: // '\n'
Convertor.outbuf[Convertor.outpos++] = Convertor.inbuf[Convertor.inpos++];
line_change_flag = true;
continue;
case 45: // '-'
char c3 = sUtil.getNextChar();
if(c3 != '>')
{
break;
}
Convertor.outbuf[Convertor.outpos++] = '.';
Convertor.inpos += 2;
continue;
case 105: // 'i'
int i = Convertor.inpos;
if(sUtil.getToken("if"))
{
sUtil.skipSpace();
if(sUtil.parseChar() != '(')
{
Convertor.inpos = i;
break;
}
sUtil.skipSpace();
Convertor.token[0] = sUtil.parseToken();
sUtil.skipSpace();
if(sUtil.getChar() == '&')
{
Convertor.inpos++;
sUtil.skipSpace();
Convertor.token[1] = sUtil.parseToken();
sUtil.skipSpace();
Convertor.token[0] = (new StringBuilder()).append("(").append(Convertor.token[0]).append(" & ").append(Convertor.token[1]).append(")").toString();
}
if(sUtil.parseChar() != ')')
{
Convertor.inpos = i;
break;
}
sUtil.putString((new StringBuilder()).append("if (").append(Convertor.token[0]).append(" != 0)").toString());
continue;
}
if(!sUtil.getToken("int"))
{
break;
}
sUtil.skipSpace();
Convertor.token[0] = sUtil.parseToken();
sUtil.skipSpace();
if(sUtil.parseChar() != '(')
{
Convertor.inpos = i;
break;
}
sUtil.skipSpace();
if(sUtil.getToken("void"))//an to soma tis function einai (void)
{
if(sUtil.parseChar() != ')')
{
Convertor.inpos = i;
break;
}
if(Convertor.token[0].contains("_interrupt"))
{
sUtil.putString((new StringBuilder()).append("public static InterruptPtr ").append(Convertor.token[0]).append(" = new InterruptPtr() { public int handler() ").toString());
type = machine_interrupt;
l = -1;
continue label0; //ξαναργυρνα στην<SUF>
}
}
if(sUtil.getToken("int"))
{
sUtil.skipSpace();
Convertor.token[1] = sUtil.parseToken();
sUtil.skipSpace();
if(sUtil.parseChar() != ')')
{
Convertor.inpos = i;
break;
}
sUtil.skipSpace();
if(Convertor.token[0].length()>0 && Convertor.token[1].length()>0)
{
sUtil.putString((new StringBuilder()).append("public static ReadHandlerPtr ").append(Convertor.token[0]).append(" = new ReadHandlerPtr() { public int handler(int ").append(Convertor.token[1]).append(")").toString());
type = machine_mem_read;
l = -1;
continue label0;
}
}
Convertor.inpos = i;
break;
case 118: // 'v'
int j = Convertor.inpos;
if(!sUtil.getToken("void"))
{
break;
}
sUtil.skipSpace();
Convertor.token[0] = sUtil.parseToken();
sUtil.skipSpace();
if(sUtil.parseChar() != '(')
{
Convertor.inpos = j;
break;
}
sUtil.skipSpace();
if(sUtil.getToken("void"))//an to soma tis function einai (void)
{
if(sUtil.parseChar() != ')')
{
Convertor.inpos = j;
break;
}
if(Convertor.token[0].contains("init_machine"))
{
sUtil.putString((new StringBuilder()).append("public static InitMachinePtr ").append(Convertor.token[0]).append(" = new InitMachinePtr() { public void handler() ").toString());
type = machine_init;
l = -1;
continue label0; //ξαναργυρνα στην αρχη για να μην γραψεις και την παλια συνάρτηση
}
}
if(!sUtil.getToken("int"))
{
Convertor.inpos = j;
break;
}
sUtil.skipSpace();
Convertor.token[1] = sUtil.parseToken();
sUtil.skipSpace();
if(sUtil.parseChar() != ',')
{
Convertor.inpos = j;
break;
}
sUtil.skipSpace();
if(!sUtil.getToken("int"))
{
Convertor.inpos = j;
break;
}
sUtil.skipSpace();
Convertor.token[2] = sUtil.parseToken();
sUtil.skipSpace();
if(sUtil.parseChar() != ')')
{
Convertor.inpos = j;
break;
}
sUtil.skipSpace();
if(Convertor.token[0].length()>0 && Convertor.token[1].length()>0 && Convertor.token[2].length()>0)
{
sUtil.putString((new StringBuilder()).append("public static WriteHandlerPtr ").append(Convertor.token[0]).append(" = new WriteHandlerPtr() { public void handler(int ").append(Convertor.token[1]).append(", int ").append(Convertor.token[2]).append(")").toString());
type = machine_mem_write;
l = -1;
continue label0; //ξαναργυρνα στην αρχη για να μην γραψεις και την παλια συνάρτηση
}
Convertor.inpos = j;
break;
case 123: // '{'
l++;
break;
case 125: // '}'
l--;
if(type != machine_mem_read && type != machine_mem_write && type!=machine_init && type!=machine_interrupt || l != -1)
{
break;
}
sUtil.putString("} };");
Convertor.inpos++;
type = -1;
continue;
}
Convertor.outbuf[Convertor.outpos++] = Convertor.inbuf[Convertor.inpos++];//grapse to inputbuffer sto output
}while(true);
if(only_once_flag)
{
sUtil.putString("}\r\n");
}
}
}
|
3094_4
|
package com.example.newdiplwm;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProviders;
import com.google.android.material.button.MaterialButton;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class ScalingGame extends AppCompatActivity {
private static final int THRESHOLD_EASY = 120;
private static final int THRESHOLD_ALL = 180;
MaterialButton startButton,leftButton,rightButton,equalButton;//na ginoyn material buttons
ImageView exit , replayTutorial;
private LinearLayout logoLinear, textsLinear;
TextView leftText, rightText,textRounds , textMsg , textMsgTime;
TextView textQuestion;
int leftNumber,rightNumber,result,choice;
int RoundsCounter = 1, TotalRounds = 0;
String menuDifficulty,currentDifficulty;
HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
HashMap<Integer,Character> symbols = new HashMap<Integer, Character>();
HashMap<Integer,Integer> divideNumbers = new HashMap<Integer, Integer>();
HashMap<String, Integer> pointsHashMap = new HashMap<String, Integer>();
CountDownTimer RoundTimer;
int game_id = -1;
int user_id = -1;
private static final String WRONG = "Λάθος! ";
private static final String CORRECT = "Σωστά! ";
private String rightResult = "";
private Timestamp startTime;
private Timestamp endTime;
private Timestamp startspeed;
private Timestamp endspeed;
private double totalspeed=0;
private int hit = 0, miss = 0, totalPoints=0, trueCounter=0;
private boolean missPoints = false;
private GameEventViewModel gameEventViewModel;
private UserViewModel userViewModel;
private Session session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scaling_game);
session = new Session(getApplicationContext());
if (!session.getPlayAgainVideo() && RoundsCounter == 1) {
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
showTutorialPopUp();
}
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("TutorialScalingGame");
if (prev != null) {
fragmentTransaction.remove(prev);
fragmentTransaction.commit();
fm.popBackStack();
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_USER);
}
game_id = session.getGameIdSession();
user_id = session.getUserIdSession();
menuDifficulty = session.getModeSession();
startButton = findViewById(R.id.startButtonScalling);
leftButton = findViewById(R.id.buttonLeft);
leftButton.setBackgroundColor(getResources().getColor(R.color.yellow));
rightButton = findViewById(R.id.buttonRight);
rightButton.setBackgroundColor(getResources().getColor(R.color.yellow));
equalButton = findViewById(R.id.buttonEqual);
equalButton.setBackgroundColor(getResources().getColor(R.color.yellow));
exit = findViewById(R.id.ExitScalGame);
replayTutorial = findViewById(R.id.ReplayTutorialSCG);
textMsgTime = findViewById(R.id.msgScaling1);
textMsg = findViewById(R.id.msgScaling);
textsLinear = findViewById(R.id.textsScaling);
leftText = findViewById(R.id.textLeft);
rightText = findViewById(R.id.textRight);
logoLinear = findViewById(R.id.imageLogoDisplaySCG);
textRounds = findViewById(R.id.textRoundsScaling);
textQuestion = findViewById(R.id.calcution_TextQuestion);
gameEventViewModel = ViewModelProviders.of(this).get(GameEventViewModel.class);
userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
disableButtons();
hashMap.put("EASY", 3);
hashMap.put("MEDIUM", 4);
hashMap.put("ADVANCED", 5);
pointsHashMap.put("EASY",0);
pointsHashMap.put("MEDIUM",5);
pointsHashMap.put("ADVANCED",10);
symbols.put(1,'+');
symbols.put(2,'-');
symbols.put(3,'×');
symbols.put(4,'÷');
if (menuDifficulty.equals("ALL"))
{
TotalRounds = 5;
//ksekinaei apo easy
currentDifficulty = "EASY";
initializeDivideNumbers();
}
else if (menuDifficulty.equals("EASY"))
{
TotalRounds = 3;
currentDifficulty = "EASY";
}
else if (menuDifficulty.equals("MEDIUM"))
{
TotalRounds = 3;
currentDifficulty = "MEDIUM";
}
else if (menuDifficulty.equals("ADVANCED"))
{
TotalRounds = 3;
currentDifficulty = "ADVANCED";
initializeDivideNumbers();
}
else if (menuDifficulty.equals("EASYtoMEDIUM"))
{
TotalRounds = 4;
currentDifficulty = "EASY";
}
RoundTimer = new CountDownTimer(6000, 1000) {
public void onTick(long millisUntilFinished) {
textMsgTime.setText(getResources().getString(R.string.nextRound)+millisUntilFinished/1000);
//roundTimerIsOn =true;
}
public void onFinish() {
//roundTimerIsOn =false;
textMsgTime.setText("-");
createRound();
enableButtons();
hideMsgDisplayButtons();
replayTutorial.setClickable(true);
replayTutorial.setAlpha(1f);
}
};
//mia fora tha treksei auto
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
logoLinear.setVisibility(View.GONE);
rightButton.setVisibility(View.VISIBLE);
leftButton.setVisibility(View.VISIBLE);
equalButton.setVisibility(View.VISIBLE);
rightText.setVisibility(View.VISIBLE);
leftText.setVisibility(View.VISIBLE);
startTime = new Timestamp(System.currentTimeMillis());
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("TutorialScalingGame");
if (prev != null) {
fragmentTransaction.remove(prev);
fragmentTransaction.commit();
fm.popBackStack();
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_USER);
}
enableButtons();
createRound();
//kalutera na mhn feugei to button ekkinisis ΚΑΛΥΤΕΡΑ View.INVISIBLE
startButton.setVisibility(View.GONE);
}
});
leftButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//textQuestion.setText("Η αριστερή πλευρά είναι Μεγαλύτερη από την δεξία.");
endspeed = new Timestamp(System.currentTimeMillis());
long speedtime = endspeed.getTime() - startspeed.getTime();
double speedTimeInSeconds = TimeUnit.MILLISECONDS.toSeconds(speedtime);
totalspeed +=speedTimeInSeconds;
choice = -1;
checkRound();
disableButtons();
if (RoundsCounter>TotalRounds)
{
endTime = new Timestamp(System.currentTimeMillis());
long playtime = endTime.getTime() - startTime.getTime();
double playTimeInSeconds = TimeUnit.MILLISECONDS.toSeconds(playtime);
if (playTimeInSeconds > THRESHOLD_EASY && currentDifficulty.equals(getResources().getString(R.string.easyValue)))
{
playTimeInSeconds = THRESHOLD_EASY;
}
else if (playTimeInSeconds > THRESHOLD_ALL)
{
playTimeInSeconds = THRESHOLD_ALL;
}
GameEvent gameEvent = new GameEvent(game_id,user_id,hit,miss,0,totalPoints,(double)hit/(hit+miss),totalspeed/TotalRounds,playTimeInSeconds,menuDifficulty,startTime,endTime);
gameEventViewModel.insertGameEvent(gameEvent);
userViewModel.updatestatsTest(user_id,game_id);
shopPopUp();
}
else {
RoundTimer.start();
replayTutorial.setClickable(false);
replayTutorial.setAlpha(0.5f);
}
hidebuttonsdisplayMsgs();
}
});
rightButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//textQuestion.setText("Η αριστερή πλευρά είναι Μικρότερη από την δεξία.");
endspeed = new Timestamp(System.currentTimeMillis());
long speedtime = endspeed.getTime() - startspeed.getTime();
double speedTimeInSeconds = TimeUnit.MILLISECONDS.toSeconds(speedtime);
totalspeed +=speedTimeInSeconds;
choice = 1;
checkRound();
disableButtons();
if (RoundsCounter>TotalRounds)
{
endTime = new Timestamp(System.currentTimeMillis());
long playtime = endTime.getTime() - startTime.getTime();
double playTimeInSeconds = TimeUnit.MILLISECONDS.toSeconds(playtime);
if (playTimeInSeconds > THRESHOLD_EASY && currentDifficulty.equals(getResources().getString(R.string.easyValue)))
{
playTimeInSeconds = THRESHOLD_EASY;
}
else if (playTimeInSeconds > THRESHOLD_ALL)
{
playTimeInSeconds = THRESHOLD_ALL;
}
GameEvent gameEvent = new GameEvent(game_id,user_id,hit,miss,0,totalPoints,(double)hit/(hit+miss),totalspeed/TotalRounds,playTimeInSeconds,menuDifficulty,startTime,endTime);
gameEventViewModel.insertGameEvent(gameEvent);
userViewModel.updatestatsTest(user_id,game_id);
shopPopUp();
}
else {
RoundTimer.start();
replayTutorial.setClickable(false);
replayTutorial.setAlpha(0.5f);
}
hidebuttonsdisplayMsgs();
}
});
equalButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//textQuestion.setText("Οι δύο πλευρές είναι ίσες.");
endspeed = new Timestamp(System.currentTimeMillis());
long speedtime = endspeed.getTime() - startspeed.getTime();
double speedTimeInSeconds = TimeUnit.MILLISECONDS.toSeconds(speedtime);
totalspeed +=speedTimeInSeconds;
choice = 0;
checkRound();
disableButtons();
if (RoundsCounter>TotalRounds)
{
endTime = new Timestamp(System.currentTimeMillis());
long playtime = endTime.getTime() - startTime.getTime();
double playTimeInSeconds = TimeUnit.MILLISECONDS.toSeconds(playtime);
if (playTimeInSeconds > THRESHOLD_EASY && currentDifficulty.equals(getResources().getString(R.string.easyValue)))
{
playTimeInSeconds = THRESHOLD_EASY;
}
else if (playTimeInSeconds > THRESHOLD_ALL)
{
playTimeInSeconds = THRESHOLD_ALL;
}
GameEvent gameEvent = new GameEvent(game_id,user_id,hit,miss,0,totalPoints,(double)hit/(hit+miss),totalspeed/TotalRounds,playTimeInSeconds,menuDifficulty,startTime,endTime);
gameEventViewModel.insertGameEvent(gameEvent);
userViewModel.updatestatsTest(user_id,game_id);
shopPopUp();
}
else {
RoundTimer.start();
replayTutorial.setClickable(false);
replayTutorial.setAlpha(0.5f);
}
hidebuttonsdisplayMsgs();
}
});
}
@Override
protected void onResume() {
super.onResume();
exit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onbackAndExitCode();
}
});
replayTutorial.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showTutorialPopUp();
}
});
}
private void onbackAndExitCode(){
if (RoundTimer != null) {
RoundTimer.cancel();
}
if (RoundsCounter == 1)
{
startTime = new Timestamp(System.currentTimeMillis());
endTime = new Timestamp(System.currentTimeMillis());
GameEvent gameEvent = new GameEvent(game_id, user_id, 0, 0, 1, 0, 0, 0, 0, menuDifficulty, startTime, endTime);
gameEventViewModel.insertGameEvent(gameEvent);
userViewModel.updatestatsTest(user_id, game_id);
finish();
}
else
{
endTime = new Timestamp(System.currentTimeMillis());
long longTime = endTime.getTime() - startTime.getTime();
float totalPlayInSeconds = TimeUnit.MILLISECONDS.toSeconds(longTime);
if (totalPlayInSeconds > THRESHOLD_EASY && currentDifficulty.equals(getResources().getString(R.string.easyValue)))
{
totalPlayInSeconds = THRESHOLD_EASY;
}
else if (totalPlayInSeconds > THRESHOLD_ALL)
{
totalPlayInSeconds = THRESHOLD_ALL;
}
GameEvent gameEvent = new GameEvent(game_id, user_id, hit, miss, 1, totalPoints, (double) hit / TotalRounds, totalspeed / RoundsCounter, totalPlayInSeconds, menuDifficulty, startTime, endTime);
gameEventViewModel.insertGameEvent(gameEvent);
userViewModel.updatestatsTest(user_id, game_id);
finish();
}
}
@Override
public void onBackPressed() {
onbackAndExitCode();
}
public void disableButtons()
{
leftButton.setEnabled(false);
leftButton.setAlpha(0.5f);
equalButton.setEnabled(false);
equalButton.setAlpha(0.5f);
rightButton.setEnabled(false);
rightButton.setAlpha(0.5f);
}
public void enableButtons()
{
leftButton.setEnabled(true);
leftButton.setAlpha(1f);
equalButton.setEnabled(true);
equalButton.setAlpha(1f);
rightButton.setEnabled(true);
rightButton.setAlpha(1f);
}
public void initializeDivideNumbers()
{
divideNumbers.put(4,2);
divideNumbers.put(6,2);
divideNumbers.put(6,3);
divideNumbers.put(8,4);
divideNumbers.put(8,2);
divideNumbers.put(9,3);
divideNumbers.put(10,2);
divideNumbers.put(12,2);
divideNumbers.put(15,3);
divideNumbers.put(16,2);
divideNumbers.put(18,2);
divideNumbers.put(20,2);
divideNumbers.put(20,5);
divideNumbers.put(22,2);
divideNumbers.put(24,2);
divideNumbers.put(26,2);
divideNumbers.put(28,2);
divideNumbers.put(30,2);
divideNumbers.put(30,3);
divideNumbers.put(32,2);
divideNumbers.put(38,2);
divideNumbers.put(40,2);
divideNumbers.put(40,5);
divideNumbers.put(40,8);
divideNumbers.put(40,10);
divideNumbers.put(48,2);
divideNumbers.put(50,5);
divideNumbers.put(50,10);
divideNumbers.put(60,2);
divideNumbers.put(60,3);
divideNumbers.put(60,10);
divideNumbers.put(70,2);
divideNumbers.put(70,10);
divideNumbers.put(80,2);
divideNumbers.put(80,8);
divideNumbers.put(80,10);
divideNumbers.put(80,20);
divideNumbers.put(90,2);
divideNumbers.put(90,3);
divideNumbers.put(90,10);
}
public void createRound()
{
textQuestion.setText("Η αριστερή πλευρά είναι __________ από την δεξιά.");
boolean mediumLeft = false;
boolean mediumRight = false;
if (RoundsCounter>TotalRounds)
{
textRounds.setText("Τέλος");
}
else
{
textRounds.setText(RoundsCounter +" / "+TotalRounds);
}
//gia na proxwrhsoun oi dyskolies
if (menuDifficulty.equals("ALL"))
{
if (RoundsCounter == 1) {
currentDifficulty = "EASY";
}
else if (RoundsCounter >1 && RoundsCounter <=3)
{
currentDifficulty = "MEDIUM";
}
else
{
currentDifficulty = "ADVANCED";
}
}
if (menuDifficulty.equals("EASYtoMEDIUM"))
{
if (RoundsCounter<=2)
{
currentDifficulty = "EASY";
}
else
{
currentDifficulty = "MEDIUM";
}
}
textQuestion.setTextColor(Color.BLACK);
Random r = new Random();
if (currentDifficulty.equals("EASY"))
{
leftNumber = r.nextInt((99 - 1) + 1) + 1;
rightNumber = r.nextInt((99 - 1) + 1) + 1;
leftText.setText(String.valueOf(leftNumber));
rightText.setText(String.valueOf(rightNumber));
result = calculateCorrectResult();
}
else if (currentDifficulty.equals("MEDIUM"))
{
int mediumMode;
mediumMode = r.nextInt((2 - 1) + 1) + 1;
//travaw tyxaia to 1 h to 2 apo to hashmap me ta symbola
//dhladh + or -
int randomSymbol = r.nextInt((2 - 1) + 1) + 1;
char mediumSymbol = symbols.get(randomSymbol);
if (mediumMode==1)
{
int leftNumber1;
int leftNumber2;
if (mediumSymbol=='+')
{
leftNumber1 = r.nextInt((99 - 1) + 1) + 1;
//panta to prwto noumero na einai megalytero gia na einai pio eykolh h prosthesh
//kai antistoixa h afairesh na mhn vgazei arnhtiko
do {
leftNumber2 = r.nextInt((99 - 1) + 1) + 1;
} while (leftNumber2 > leftNumber1);
leftNumber = leftNumber1 + leftNumber2;
leftText.setText(leftNumber1 + " + " +leftNumber2);
rightNumber = r.nextInt((99 - 1) + 1) + 1;
rightText.setText(String.valueOf(rightNumber));
}
else if (mediumSymbol=='-')
{
leftNumber1 = r.nextInt((99 - 1) + 1) + 1;
do {
leftNumber2 = r.nextInt((99 - 1) + 1) + 1;
} while (leftNumber2 > leftNumber1);
leftNumber = leftNumber1 - leftNumber2;
leftText.setText(leftNumber1 + " - " +leftNumber2);
rightNumber = r.nextInt((99 - 1) + 1) + 1;
rightText.setText(String.valueOf(rightNumber));
}
}
else if (mediumMode==2)
{
int rightNumber1;
int rightNumber2;
if (mediumSymbol=='+')
{
rightNumber1 = r.nextInt((99 - 1) + 1) + 1;
do {
rightNumber2 = r.nextInt((99 - 1) + 1) + 1;
} while (rightNumber2 > rightNumber1);
rightNumber = rightNumber1 + rightNumber2;
rightText.setText(rightNumber1 + " + " +rightNumber2);
leftNumber = r.nextInt((99 - 1) + 1) + 1;
leftText.setText(String.valueOf(leftNumber));
}
else if (mediumSymbol=='-')
{
rightNumber1 = r.nextInt((99 - 1) + 1) + 1;
do {
rightNumber2 = r.nextInt((99 - 1) + 1) + 1;
} while (rightNumber2 > rightNumber1);
rightNumber = rightNumber1 - rightNumber2;
rightText.setText(rightNumber1 + " - " +rightNumber2);
leftNumber = r.nextInt((99 - 1) + 1) + 1;
leftText.setText(String.valueOf(leftNumber));
}
}
result = calculateCorrectResult();
}
else if (currentDifficulty.equals("ADVANCED"))
{
int advancedMode;
advancedMode = r.nextInt((2 - 1) + 1) + 1;
//travaw tyxaia to 3 h to 4 apo to hashmap me ta symbola
//dhladh x or /
int randomSymbol = r.nextInt((4 - 3) + 1) + 3;
char advancedSymbol = symbols.get(randomSymbol);
//travaw tyxaia to 1 h to 2 apo to hashmap me ta symbola
//dhladh + or -
int randomMediumSymbol = r.nextInt((2 - 1) + 1) + 1;
char mediumSymbol = symbols.get(randomMediumSymbol);
int leftNumber1;
int leftNumber2;
leftNumber1 = r.nextInt((99 - 1) + 1) + 1;
//panta to prwto noumero na einai megalytero gia na einai pio eykolh h prosthesh
//kai antistoixa h afairesh na mhn vgazei arnhtiko
do {
leftNumber2 = r.nextInt((99 - 1) + 1) + 1;
} while (leftNumber2 > leftNumber1);
int rightNumber1;
int rightNumber2;
rightNumber1 = r.nextInt((99 - 1) + 1) + 1;
//panta to prwto noumero na einai megalytero gia na einai pio eykolh h prosthesh
//kai antistoixa h afairesh na mhn vgazei arnhtiko
do {
rightNumber2 = r.nextInt((99 - 1) + 1) + 1;
} while (rightNumber2 > rightNumber1);
if (advancedMode==1)
{
if (advancedSymbol=='×')
{
//eidikoi arithmoi mexri to 11 gia ton pollaplasiasmo
int specialNumber1 = r.nextInt((11 - 1) + 1) + 1;
int specialNumber2;
do {
specialNumber2 = r.nextInt((11 - 1) + 1) + 1;
} while (specialNumber2 > specialNumber1);
leftNumber = specialNumber1 * specialNumber2;
//ston pollaplasiasmo vazw prwta ton mikro arithmo gia na einai pio eukolh h praksh
leftText.setText(specialNumber2 + " x " +specialNumber1);
if (mediumSymbol=='+')
{
rightNumber = rightNumber1 + rightNumber2;
rightText.setText(rightNumber1 + " + " +rightNumber2);
}
else if (mediumSymbol=='-')
{
rightNumber = rightNumber1 - rightNumber2;
rightText.setText(rightNumber1 + " - " +rightNumber2);
}
}
else if (advancedSymbol=='÷')
{
int divideNumber1;
int divideNumber2;
Random generator = new Random();
Object[] keys = divideNumbers.keySet().toArray();
int randomKey = (int) keys[generator.nextInt(keys.length)];
divideNumber1 = randomKey;
divideNumber2 = divideNumbers.get(randomKey);
leftNumber = divideNumber1 / divideNumber2;
leftText.setText(divideNumber1 + " ÷ " +divideNumber2);
if (mediumSymbol=='+')
{
rightNumber = rightNumber1 + rightNumber2;
rightText.setText(rightNumber1 + " + " +rightNumber2);
}
else if (mediumSymbol=='-')
{
rightNumber = rightNumber1 - rightNumber2;
rightText.setText(rightNumber1 + " - " +rightNumber2);
}
}
}
else if (advancedMode==2)
{
if (advancedSymbol=='×')
{
int specialNumber1 = r.nextInt((11 - 1) + 1) + 1;
int specialNumber2;
do {
specialNumber2 = r.nextInt((11 - 1) + 1) + 1;
} while (specialNumber2 > specialNumber1);
rightNumber = specialNumber1 * specialNumber2;
//ston pollaplasiasmo vazw prwta ton mikro arithmo gia na einai pio eukolh h praksh
rightText.setText(specialNumber2 + " x " +specialNumber1);
if (mediumSymbol=='+')
{
leftNumber = leftNumber1 + leftNumber2;
leftText.setText(leftNumber1 + " + " +leftNumber2);
}
else if (mediumSymbol=='-')
{
leftNumber = leftNumber1 - leftNumber2;
leftText.setText(leftNumber1 + " - " +leftNumber2);
}
}
else if (advancedSymbol=='÷')
{
int divideNumber1;
int divideNumber2;
Random generator = new Random();
Object[] keys = divideNumbers.keySet().toArray();
int randomKey = (int) keys[generator.nextInt(keys.length)];
divideNumber1 = randomKey;
divideNumber2 = divideNumbers.get(randomKey);
rightNumber = divideNumber1 / divideNumber2;
rightText.setText(divideNumber1 + " ÷ " +divideNumber2);
if (mediumSymbol=='+')
{
leftNumber = leftNumber1 + leftNumber2;
leftText.setText(leftNumber1 + " + " +leftNumber2);
}
else if (mediumSymbol=='-')
{
leftNumber = leftNumber1 - leftNumber2;
leftText.setText(leftNumber1 + " - " +leftNumber2);
}
}
}
result = calculateCorrectResult();
}
startspeed = new Timestamp(System.currentTimeMillis());
RoundsCounter++;
}
public int calculateCorrectResult()
{
int res;
if (leftNumber>rightNumber)
{
res = -1;
rightResult = "Η αριστερή πλευρά είναι ΜΕΓΑΛΥΤΕΡΗ από την δεξιά.";
}
else if (rightNumber>leftNumber)
{
res = 1;
rightResult = "Η αριστερή πλευρά είναι ΜΙΚΡΟΤΕΡΗ από την δεξιά.";
}
else
{
res = 0;
rightResult = "Οι δύο πλευρές είναι ίσες.";
}
return res;
}
public void checkRound()
{
if (result==choice)
{
hit++;
missPoints=false;
trueCounter++;
textQuestion.setText(CORRECT+rightResult);
//tsekare prasinaki
textQuestion.setTextColor(Color.parseColor("#00CC00"));
}
else
{
miss++;
missPoints=true;
textQuestion.setText(WRONG+rightResult);
textQuestion.setTextColor(Color.RED);
}
countPoints();
}
private void countPoints() {
int currentPoints = 0;
if (!missPoints && trueCounter == 1) {
currentPoints += 10;
currentPoints += pointsHashMap.get(currentDifficulty);
textMsg.setText(R.string.win);
} else if (!missPoints && trueCounter == 2) {
currentPoints += 20;
currentPoints += pointsHashMap.get(currentDifficulty);
textMsg.setText(R.string.win1);
} else if (!missPoints && trueCounter >= 3) {
currentPoints += 30;
currentPoints += pointsHashMap.get(currentDifficulty);
textMsg.setText(R.string.win2);
} else if (missPoints) {
currentPoints += 0;
trueCounter = 0;
missPoints = false;
textMsg.setText(R.string.lose);
}
totalPoints += currentPoints;
// animPointsText.setText("+ " + currentPoints);
// if (currentPoints == 0) {
// animPointsText.setTextColor(Color.RED);
// } else
// animPointsText.setTextColor(Color.GREEN);
}
private void hidebuttonsdisplayMsgs(){
if (RoundsCounter>TotalRounds)
{
textMsgTime.setText("");
}
textMsg.setTextColor(getResources().getColor(R.color.greenStrong));
textsLinear.setVisibility(View.VISIBLE);
leftButton.setVisibility(View.INVISIBLE);
rightButton.setVisibility(View.INVISIBLE);
equalButton.setVisibility(View.INVISIBLE);
}
private void hideMsgDisplayButtons(){
textsLinear.setVisibility(View.INVISIBLE);
leftButton.setVisibility(View.VISIBLE);
rightButton.setVisibility(View.VISIBLE);
equalButton.setVisibility(View.VISIBLE);
}
private void showTutorialPopUp(){
DialogFragment dialogFragment = new Tutorial(ScalingGame.this,R.raw.tutorial_scalinggame,getPackageName());
dialogFragment.show(getSupportFragmentManager(),"TutorialScalingGame");
}
public void shopPopUp() {
DialogFragment newFragment = new DialogMsg(user_id,ScalingGame.this,hit,totalPoints);
newFragment.show(getSupportFragmentManager(), "ScalingGame");
}
}
|
zAnastasios/NewDiplwm
|
app/src/main/java/com/example/newdiplwm/ScalingGame.java
| 7,237
|
//textQuestion.setText("Η αριστερή πλευρά είναι Μεγαλύτερη από την δεξία.");
|
line_comment
|
el
|
package com.example.newdiplwm;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProviders;
import com.google.android.material.button.MaterialButton;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class ScalingGame extends AppCompatActivity {
private static final int THRESHOLD_EASY = 120;
private static final int THRESHOLD_ALL = 180;
MaterialButton startButton,leftButton,rightButton,equalButton;//na ginoyn material buttons
ImageView exit , replayTutorial;
private LinearLayout logoLinear, textsLinear;
TextView leftText, rightText,textRounds , textMsg , textMsgTime;
TextView textQuestion;
int leftNumber,rightNumber,result,choice;
int RoundsCounter = 1, TotalRounds = 0;
String menuDifficulty,currentDifficulty;
HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
HashMap<Integer,Character> symbols = new HashMap<Integer, Character>();
HashMap<Integer,Integer> divideNumbers = new HashMap<Integer, Integer>();
HashMap<String, Integer> pointsHashMap = new HashMap<String, Integer>();
CountDownTimer RoundTimer;
int game_id = -1;
int user_id = -1;
private static final String WRONG = "Λάθος! ";
private static final String CORRECT = "Σωστά! ";
private String rightResult = "";
private Timestamp startTime;
private Timestamp endTime;
private Timestamp startspeed;
private Timestamp endspeed;
private double totalspeed=0;
private int hit = 0, miss = 0, totalPoints=0, trueCounter=0;
private boolean missPoints = false;
private GameEventViewModel gameEventViewModel;
private UserViewModel userViewModel;
private Session session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scaling_game);
session = new Session(getApplicationContext());
if (!session.getPlayAgainVideo() && RoundsCounter == 1) {
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
showTutorialPopUp();
}
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("TutorialScalingGame");
if (prev != null) {
fragmentTransaction.remove(prev);
fragmentTransaction.commit();
fm.popBackStack();
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_USER);
}
game_id = session.getGameIdSession();
user_id = session.getUserIdSession();
menuDifficulty = session.getModeSession();
startButton = findViewById(R.id.startButtonScalling);
leftButton = findViewById(R.id.buttonLeft);
leftButton.setBackgroundColor(getResources().getColor(R.color.yellow));
rightButton = findViewById(R.id.buttonRight);
rightButton.setBackgroundColor(getResources().getColor(R.color.yellow));
equalButton = findViewById(R.id.buttonEqual);
equalButton.setBackgroundColor(getResources().getColor(R.color.yellow));
exit = findViewById(R.id.ExitScalGame);
replayTutorial = findViewById(R.id.ReplayTutorialSCG);
textMsgTime = findViewById(R.id.msgScaling1);
textMsg = findViewById(R.id.msgScaling);
textsLinear = findViewById(R.id.textsScaling);
leftText = findViewById(R.id.textLeft);
rightText = findViewById(R.id.textRight);
logoLinear = findViewById(R.id.imageLogoDisplaySCG);
textRounds = findViewById(R.id.textRoundsScaling);
textQuestion = findViewById(R.id.calcution_TextQuestion);
gameEventViewModel = ViewModelProviders.of(this).get(GameEventViewModel.class);
userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
disableButtons();
hashMap.put("EASY", 3);
hashMap.put("MEDIUM", 4);
hashMap.put("ADVANCED", 5);
pointsHashMap.put("EASY",0);
pointsHashMap.put("MEDIUM",5);
pointsHashMap.put("ADVANCED",10);
symbols.put(1,'+');
symbols.put(2,'-');
symbols.put(3,'×');
symbols.put(4,'÷');
if (menuDifficulty.equals("ALL"))
{
TotalRounds = 5;
//ksekinaei apo easy
currentDifficulty = "EASY";
initializeDivideNumbers();
}
else if (menuDifficulty.equals("EASY"))
{
TotalRounds = 3;
currentDifficulty = "EASY";
}
else if (menuDifficulty.equals("MEDIUM"))
{
TotalRounds = 3;
currentDifficulty = "MEDIUM";
}
else if (menuDifficulty.equals("ADVANCED"))
{
TotalRounds = 3;
currentDifficulty = "ADVANCED";
initializeDivideNumbers();
}
else if (menuDifficulty.equals("EASYtoMEDIUM"))
{
TotalRounds = 4;
currentDifficulty = "EASY";
}
RoundTimer = new CountDownTimer(6000, 1000) {
public void onTick(long millisUntilFinished) {
textMsgTime.setText(getResources().getString(R.string.nextRound)+millisUntilFinished/1000);
//roundTimerIsOn =true;
}
public void onFinish() {
//roundTimerIsOn =false;
textMsgTime.setText("-");
createRound();
enableButtons();
hideMsgDisplayButtons();
replayTutorial.setClickable(true);
replayTutorial.setAlpha(1f);
}
};
//mia fora tha treksei auto
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
logoLinear.setVisibility(View.GONE);
rightButton.setVisibility(View.VISIBLE);
leftButton.setVisibility(View.VISIBLE);
equalButton.setVisibility(View.VISIBLE);
rightText.setVisibility(View.VISIBLE);
leftText.setVisibility(View.VISIBLE);
startTime = new Timestamp(System.currentTimeMillis());
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("TutorialScalingGame");
if (prev != null) {
fragmentTransaction.remove(prev);
fragmentTransaction.commit();
fm.popBackStack();
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_USER);
}
enableButtons();
createRound();
//kalutera na mhn feugei to button ekkinisis ΚΑΛΥΤΕΡΑ View.INVISIBLE
startButton.setVisibility(View.GONE);
}
});
leftButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//textQuestion.setText("Η αριστερή<SUF>
endspeed = new Timestamp(System.currentTimeMillis());
long speedtime = endspeed.getTime() - startspeed.getTime();
double speedTimeInSeconds = TimeUnit.MILLISECONDS.toSeconds(speedtime);
totalspeed +=speedTimeInSeconds;
choice = -1;
checkRound();
disableButtons();
if (RoundsCounter>TotalRounds)
{
endTime = new Timestamp(System.currentTimeMillis());
long playtime = endTime.getTime() - startTime.getTime();
double playTimeInSeconds = TimeUnit.MILLISECONDS.toSeconds(playtime);
if (playTimeInSeconds > THRESHOLD_EASY && currentDifficulty.equals(getResources().getString(R.string.easyValue)))
{
playTimeInSeconds = THRESHOLD_EASY;
}
else if (playTimeInSeconds > THRESHOLD_ALL)
{
playTimeInSeconds = THRESHOLD_ALL;
}
GameEvent gameEvent = new GameEvent(game_id,user_id,hit,miss,0,totalPoints,(double)hit/(hit+miss),totalspeed/TotalRounds,playTimeInSeconds,menuDifficulty,startTime,endTime);
gameEventViewModel.insertGameEvent(gameEvent);
userViewModel.updatestatsTest(user_id,game_id);
shopPopUp();
}
else {
RoundTimer.start();
replayTutorial.setClickable(false);
replayTutorial.setAlpha(0.5f);
}
hidebuttonsdisplayMsgs();
}
});
rightButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//textQuestion.setText("Η αριστερή πλευρά είναι Μικρότερη από την δεξία.");
endspeed = new Timestamp(System.currentTimeMillis());
long speedtime = endspeed.getTime() - startspeed.getTime();
double speedTimeInSeconds = TimeUnit.MILLISECONDS.toSeconds(speedtime);
totalspeed +=speedTimeInSeconds;
choice = 1;
checkRound();
disableButtons();
if (RoundsCounter>TotalRounds)
{
endTime = new Timestamp(System.currentTimeMillis());
long playtime = endTime.getTime() - startTime.getTime();
double playTimeInSeconds = TimeUnit.MILLISECONDS.toSeconds(playtime);
if (playTimeInSeconds > THRESHOLD_EASY && currentDifficulty.equals(getResources().getString(R.string.easyValue)))
{
playTimeInSeconds = THRESHOLD_EASY;
}
else if (playTimeInSeconds > THRESHOLD_ALL)
{
playTimeInSeconds = THRESHOLD_ALL;
}
GameEvent gameEvent = new GameEvent(game_id,user_id,hit,miss,0,totalPoints,(double)hit/(hit+miss),totalspeed/TotalRounds,playTimeInSeconds,menuDifficulty,startTime,endTime);
gameEventViewModel.insertGameEvent(gameEvent);
userViewModel.updatestatsTest(user_id,game_id);
shopPopUp();
}
else {
RoundTimer.start();
replayTutorial.setClickable(false);
replayTutorial.setAlpha(0.5f);
}
hidebuttonsdisplayMsgs();
}
});
equalButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//textQuestion.setText("Οι δύο πλευρές είναι ίσες.");
endspeed = new Timestamp(System.currentTimeMillis());
long speedtime = endspeed.getTime() - startspeed.getTime();
double speedTimeInSeconds = TimeUnit.MILLISECONDS.toSeconds(speedtime);
totalspeed +=speedTimeInSeconds;
choice = 0;
checkRound();
disableButtons();
if (RoundsCounter>TotalRounds)
{
endTime = new Timestamp(System.currentTimeMillis());
long playtime = endTime.getTime() - startTime.getTime();
double playTimeInSeconds = TimeUnit.MILLISECONDS.toSeconds(playtime);
if (playTimeInSeconds > THRESHOLD_EASY && currentDifficulty.equals(getResources().getString(R.string.easyValue)))
{
playTimeInSeconds = THRESHOLD_EASY;
}
else if (playTimeInSeconds > THRESHOLD_ALL)
{
playTimeInSeconds = THRESHOLD_ALL;
}
GameEvent gameEvent = new GameEvent(game_id,user_id,hit,miss,0,totalPoints,(double)hit/(hit+miss),totalspeed/TotalRounds,playTimeInSeconds,menuDifficulty,startTime,endTime);
gameEventViewModel.insertGameEvent(gameEvent);
userViewModel.updatestatsTest(user_id,game_id);
shopPopUp();
}
else {
RoundTimer.start();
replayTutorial.setClickable(false);
replayTutorial.setAlpha(0.5f);
}
hidebuttonsdisplayMsgs();
}
});
}
@Override
protected void onResume() {
super.onResume();
exit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onbackAndExitCode();
}
});
replayTutorial.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showTutorialPopUp();
}
});
}
private void onbackAndExitCode(){
if (RoundTimer != null) {
RoundTimer.cancel();
}
if (RoundsCounter == 1)
{
startTime = new Timestamp(System.currentTimeMillis());
endTime = new Timestamp(System.currentTimeMillis());
GameEvent gameEvent = new GameEvent(game_id, user_id, 0, 0, 1, 0, 0, 0, 0, menuDifficulty, startTime, endTime);
gameEventViewModel.insertGameEvent(gameEvent);
userViewModel.updatestatsTest(user_id, game_id);
finish();
}
else
{
endTime = new Timestamp(System.currentTimeMillis());
long longTime = endTime.getTime() - startTime.getTime();
float totalPlayInSeconds = TimeUnit.MILLISECONDS.toSeconds(longTime);
if (totalPlayInSeconds > THRESHOLD_EASY && currentDifficulty.equals(getResources().getString(R.string.easyValue)))
{
totalPlayInSeconds = THRESHOLD_EASY;
}
else if (totalPlayInSeconds > THRESHOLD_ALL)
{
totalPlayInSeconds = THRESHOLD_ALL;
}
GameEvent gameEvent = new GameEvent(game_id, user_id, hit, miss, 1, totalPoints, (double) hit / TotalRounds, totalspeed / RoundsCounter, totalPlayInSeconds, menuDifficulty, startTime, endTime);
gameEventViewModel.insertGameEvent(gameEvent);
userViewModel.updatestatsTest(user_id, game_id);
finish();
}
}
@Override
public void onBackPressed() {
onbackAndExitCode();
}
public void disableButtons()
{
leftButton.setEnabled(false);
leftButton.setAlpha(0.5f);
equalButton.setEnabled(false);
equalButton.setAlpha(0.5f);
rightButton.setEnabled(false);
rightButton.setAlpha(0.5f);
}
public void enableButtons()
{
leftButton.setEnabled(true);
leftButton.setAlpha(1f);
equalButton.setEnabled(true);
equalButton.setAlpha(1f);
rightButton.setEnabled(true);
rightButton.setAlpha(1f);
}
public void initializeDivideNumbers()
{
divideNumbers.put(4,2);
divideNumbers.put(6,2);
divideNumbers.put(6,3);
divideNumbers.put(8,4);
divideNumbers.put(8,2);
divideNumbers.put(9,3);
divideNumbers.put(10,2);
divideNumbers.put(12,2);
divideNumbers.put(15,3);
divideNumbers.put(16,2);
divideNumbers.put(18,2);
divideNumbers.put(20,2);
divideNumbers.put(20,5);
divideNumbers.put(22,2);
divideNumbers.put(24,2);
divideNumbers.put(26,2);
divideNumbers.put(28,2);
divideNumbers.put(30,2);
divideNumbers.put(30,3);
divideNumbers.put(32,2);
divideNumbers.put(38,2);
divideNumbers.put(40,2);
divideNumbers.put(40,5);
divideNumbers.put(40,8);
divideNumbers.put(40,10);
divideNumbers.put(48,2);
divideNumbers.put(50,5);
divideNumbers.put(50,10);
divideNumbers.put(60,2);
divideNumbers.put(60,3);
divideNumbers.put(60,10);
divideNumbers.put(70,2);
divideNumbers.put(70,10);
divideNumbers.put(80,2);
divideNumbers.put(80,8);
divideNumbers.put(80,10);
divideNumbers.put(80,20);
divideNumbers.put(90,2);
divideNumbers.put(90,3);
divideNumbers.put(90,10);
}
public void createRound()
{
textQuestion.setText("Η αριστερή πλευρά είναι __________ από την δεξιά.");
boolean mediumLeft = false;
boolean mediumRight = false;
if (RoundsCounter>TotalRounds)
{
textRounds.setText("Τέλος");
}
else
{
textRounds.setText(RoundsCounter +" / "+TotalRounds);
}
//gia na proxwrhsoun oi dyskolies
if (menuDifficulty.equals("ALL"))
{
if (RoundsCounter == 1) {
currentDifficulty = "EASY";
}
else if (RoundsCounter >1 && RoundsCounter <=3)
{
currentDifficulty = "MEDIUM";
}
else
{
currentDifficulty = "ADVANCED";
}
}
if (menuDifficulty.equals("EASYtoMEDIUM"))
{
if (RoundsCounter<=2)
{
currentDifficulty = "EASY";
}
else
{
currentDifficulty = "MEDIUM";
}
}
textQuestion.setTextColor(Color.BLACK);
Random r = new Random();
if (currentDifficulty.equals("EASY"))
{
leftNumber = r.nextInt((99 - 1) + 1) + 1;
rightNumber = r.nextInt((99 - 1) + 1) + 1;
leftText.setText(String.valueOf(leftNumber));
rightText.setText(String.valueOf(rightNumber));
result = calculateCorrectResult();
}
else if (currentDifficulty.equals("MEDIUM"))
{
int mediumMode;
mediumMode = r.nextInt((2 - 1) + 1) + 1;
//travaw tyxaia to 1 h to 2 apo to hashmap me ta symbola
//dhladh + or -
int randomSymbol = r.nextInt((2 - 1) + 1) + 1;
char mediumSymbol = symbols.get(randomSymbol);
if (mediumMode==1)
{
int leftNumber1;
int leftNumber2;
if (mediumSymbol=='+')
{
leftNumber1 = r.nextInt((99 - 1) + 1) + 1;
//panta to prwto noumero na einai megalytero gia na einai pio eykolh h prosthesh
//kai antistoixa h afairesh na mhn vgazei arnhtiko
do {
leftNumber2 = r.nextInt((99 - 1) + 1) + 1;
} while (leftNumber2 > leftNumber1);
leftNumber = leftNumber1 + leftNumber2;
leftText.setText(leftNumber1 + " + " +leftNumber2);
rightNumber = r.nextInt((99 - 1) + 1) + 1;
rightText.setText(String.valueOf(rightNumber));
}
else if (mediumSymbol=='-')
{
leftNumber1 = r.nextInt((99 - 1) + 1) + 1;
do {
leftNumber2 = r.nextInt((99 - 1) + 1) + 1;
} while (leftNumber2 > leftNumber1);
leftNumber = leftNumber1 - leftNumber2;
leftText.setText(leftNumber1 + " - " +leftNumber2);
rightNumber = r.nextInt((99 - 1) + 1) + 1;
rightText.setText(String.valueOf(rightNumber));
}
}
else if (mediumMode==2)
{
int rightNumber1;
int rightNumber2;
if (mediumSymbol=='+')
{
rightNumber1 = r.nextInt((99 - 1) + 1) + 1;
do {
rightNumber2 = r.nextInt((99 - 1) + 1) + 1;
} while (rightNumber2 > rightNumber1);
rightNumber = rightNumber1 + rightNumber2;
rightText.setText(rightNumber1 + " + " +rightNumber2);
leftNumber = r.nextInt((99 - 1) + 1) + 1;
leftText.setText(String.valueOf(leftNumber));
}
else if (mediumSymbol=='-')
{
rightNumber1 = r.nextInt((99 - 1) + 1) + 1;
do {
rightNumber2 = r.nextInt((99 - 1) + 1) + 1;
} while (rightNumber2 > rightNumber1);
rightNumber = rightNumber1 - rightNumber2;
rightText.setText(rightNumber1 + " - " +rightNumber2);
leftNumber = r.nextInt((99 - 1) + 1) + 1;
leftText.setText(String.valueOf(leftNumber));
}
}
result = calculateCorrectResult();
}
else if (currentDifficulty.equals("ADVANCED"))
{
int advancedMode;
advancedMode = r.nextInt((2 - 1) + 1) + 1;
//travaw tyxaia to 3 h to 4 apo to hashmap me ta symbola
//dhladh x or /
int randomSymbol = r.nextInt((4 - 3) + 1) + 3;
char advancedSymbol = symbols.get(randomSymbol);
//travaw tyxaia to 1 h to 2 apo to hashmap me ta symbola
//dhladh + or -
int randomMediumSymbol = r.nextInt((2 - 1) + 1) + 1;
char mediumSymbol = symbols.get(randomMediumSymbol);
int leftNumber1;
int leftNumber2;
leftNumber1 = r.nextInt((99 - 1) + 1) + 1;
//panta to prwto noumero na einai megalytero gia na einai pio eykolh h prosthesh
//kai antistoixa h afairesh na mhn vgazei arnhtiko
do {
leftNumber2 = r.nextInt((99 - 1) + 1) + 1;
} while (leftNumber2 > leftNumber1);
int rightNumber1;
int rightNumber2;
rightNumber1 = r.nextInt((99 - 1) + 1) + 1;
//panta to prwto noumero na einai megalytero gia na einai pio eykolh h prosthesh
//kai antistoixa h afairesh na mhn vgazei arnhtiko
do {
rightNumber2 = r.nextInt((99 - 1) + 1) + 1;
} while (rightNumber2 > rightNumber1);
if (advancedMode==1)
{
if (advancedSymbol=='×')
{
//eidikoi arithmoi mexri to 11 gia ton pollaplasiasmo
int specialNumber1 = r.nextInt((11 - 1) + 1) + 1;
int specialNumber2;
do {
specialNumber2 = r.nextInt((11 - 1) + 1) + 1;
} while (specialNumber2 > specialNumber1);
leftNumber = specialNumber1 * specialNumber2;
//ston pollaplasiasmo vazw prwta ton mikro arithmo gia na einai pio eukolh h praksh
leftText.setText(specialNumber2 + " x " +specialNumber1);
if (mediumSymbol=='+')
{
rightNumber = rightNumber1 + rightNumber2;
rightText.setText(rightNumber1 + " + " +rightNumber2);
}
else if (mediumSymbol=='-')
{
rightNumber = rightNumber1 - rightNumber2;
rightText.setText(rightNumber1 + " - " +rightNumber2);
}
}
else if (advancedSymbol=='÷')
{
int divideNumber1;
int divideNumber2;
Random generator = new Random();
Object[] keys = divideNumbers.keySet().toArray();
int randomKey = (int) keys[generator.nextInt(keys.length)];
divideNumber1 = randomKey;
divideNumber2 = divideNumbers.get(randomKey);
leftNumber = divideNumber1 / divideNumber2;
leftText.setText(divideNumber1 + " ÷ " +divideNumber2);
if (mediumSymbol=='+')
{
rightNumber = rightNumber1 + rightNumber2;
rightText.setText(rightNumber1 + " + " +rightNumber2);
}
else if (mediumSymbol=='-')
{
rightNumber = rightNumber1 - rightNumber2;
rightText.setText(rightNumber1 + " - " +rightNumber2);
}
}
}
else if (advancedMode==2)
{
if (advancedSymbol=='×')
{
int specialNumber1 = r.nextInt((11 - 1) + 1) + 1;
int specialNumber2;
do {
specialNumber2 = r.nextInt((11 - 1) + 1) + 1;
} while (specialNumber2 > specialNumber1);
rightNumber = specialNumber1 * specialNumber2;
//ston pollaplasiasmo vazw prwta ton mikro arithmo gia na einai pio eukolh h praksh
rightText.setText(specialNumber2 + " x " +specialNumber1);
if (mediumSymbol=='+')
{
leftNumber = leftNumber1 + leftNumber2;
leftText.setText(leftNumber1 + " + " +leftNumber2);
}
else if (mediumSymbol=='-')
{
leftNumber = leftNumber1 - leftNumber2;
leftText.setText(leftNumber1 + " - " +leftNumber2);
}
}
else if (advancedSymbol=='÷')
{
int divideNumber1;
int divideNumber2;
Random generator = new Random();
Object[] keys = divideNumbers.keySet().toArray();
int randomKey = (int) keys[generator.nextInt(keys.length)];
divideNumber1 = randomKey;
divideNumber2 = divideNumbers.get(randomKey);
rightNumber = divideNumber1 / divideNumber2;
rightText.setText(divideNumber1 + " ÷ " +divideNumber2);
if (mediumSymbol=='+')
{
leftNumber = leftNumber1 + leftNumber2;
leftText.setText(leftNumber1 + " + " +leftNumber2);
}
else if (mediumSymbol=='-')
{
leftNumber = leftNumber1 - leftNumber2;
leftText.setText(leftNumber1 + " - " +leftNumber2);
}
}
}
result = calculateCorrectResult();
}
startspeed = new Timestamp(System.currentTimeMillis());
RoundsCounter++;
}
public int calculateCorrectResult()
{
int res;
if (leftNumber>rightNumber)
{
res = -1;
rightResult = "Η αριστερή πλευρά είναι ΜΕΓΑΛΥΤΕΡΗ από την δεξιά.";
}
else if (rightNumber>leftNumber)
{
res = 1;
rightResult = "Η αριστερή πλευρά είναι ΜΙΚΡΟΤΕΡΗ από την δεξιά.";
}
else
{
res = 0;
rightResult = "Οι δύο πλευρές είναι ίσες.";
}
return res;
}
public void checkRound()
{
if (result==choice)
{
hit++;
missPoints=false;
trueCounter++;
textQuestion.setText(CORRECT+rightResult);
//tsekare prasinaki
textQuestion.setTextColor(Color.parseColor("#00CC00"));
}
else
{
miss++;
missPoints=true;
textQuestion.setText(WRONG+rightResult);
textQuestion.setTextColor(Color.RED);
}
countPoints();
}
private void countPoints() {
int currentPoints = 0;
if (!missPoints && trueCounter == 1) {
currentPoints += 10;
currentPoints += pointsHashMap.get(currentDifficulty);
textMsg.setText(R.string.win);
} else if (!missPoints && trueCounter == 2) {
currentPoints += 20;
currentPoints += pointsHashMap.get(currentDifficulty);
textMsg.setText(R.string.win1);
} else if (!missPoints && trueCounter >= 3) {
currentPoints += 30;
currentPoints += pointsHashMap.get(currentDifficulty);
textMsg.setText(R.string.win2);
} else if (missPoints) {
currentPoints += 0;
trueCounter = 0;
missPoints = false;
textMsg.setText(R.string.lose);
}
totalPoints += currentPoints;
// animPointsText.setText("+ " + currentPoints);
// if (currentPoints == 0) {
// animPointsText.setTextColor(Color.RED);
// } else
// animPointsText.setTextColor(Color.GREEN);
}
private void hidebuttonsdisplayMsgs(){
if (RoundsCounter>TotalRounds)
{
textMsgTime.setText("");
}
textMsg.setTextColor(getResources().getColor(R.color.greenStrong));
textsLinear.setVisibility(View.VISIBLE);
leftButton.setVisibility(View.INVISIBLE);
rightButton.setVisibility(View.INVISIBLE);
equalButton.setVisibility(View.INVISIBLE);
}
private void hideMsgDisplayButtons(){
textsLinear.setVisibility(View.INVISIBLE);
leftButton.setVisibility(View.VISIBLE);
rightButton.setVisibility(View.VISIBLE);
equalButton.setVisibility(View.VISIBLE);
}
private void showTutorialPopUp(){
DialogFragment dialogFragment = new Tutorial(ScalingGame.this,R.raw.tutorial_scalinggame,getPackageName());
dialogFragment.show(getSupportFragmentManager(),"TutorialScalingGame");
}
public void shopPopUp() {
DialogFragment newFragment = new DialogMsg(user_id,ScalingGame.this,hit,totalPoints);
newFragment.show(getSupportFragmentManager(), "ScalingGame");
}
}
|
1785_0
|
package api;
import api.Media.Category;
import api.Media.Content;
import java.io.Serializable;
import java.util.ArrayList;
/**
* Κλάση που υλοποιεί την αναζήτηση ενός μέσου και από τους δύο τύπους χρηστών.
* Δημιουργεί ένα αντικείμενο με τα κριτήρια που επέλεξε ο χρήστης και επιστρέφει τα αντίστοιχα αποτελέσματα μέσω μιας λίστας.
*/
public class Search implements Serializable {
private String title;
private String type;
private String ageRestriction;
private String stars;
private Category category;
private Double rating;
private Data data;
private boolean titleCheck;
private boolean typeCheck;
private boolean ageCheck;
private boolean starsCheck;
private boolean categoryCheck;
private boolean ratingCheck;
private ArrayList<Content> content;
/**
* Κατασκευαστής που δημιουργεί το αντικείμενο αναζήτησης και αρχικοποιεί όλα τα μέλη του
* @param data η βάση δεδομένων
* @param title ο τίτλος που δήλωσε ο χρήστης (μπορεί να μη δηλώσει)
* @param type ο τύπος του μέσου που δήλωσε ο χρήστης (μπορεί να μη δηλώσει)
* @param ageRestriction ο περιορισμός της ηλικίας που δήλωσε ο χρήστης (μπορεί να μη δηλώσει)
* @param stars ο πρωταγωνιστής που δήλωσε ο χρήστης (μπορεί να μη δηλώσει)
* @param category η κατηγορία του μέσου που δήλωσε ο χρήστης (μπορεί να μη δηλώσει)
* @param rating η ελάχιστη μέση βαθμολογία αξιολογήσεων του μέσου που δήλωσε ο χρήστης (μπορεί να μη δηλώσει)
*/
public Search(Data data,String title,String type,String ageRestriction,String stars,Category category,Double rating) {
this.title = title;
this.type = type;
this.ageRestriction = ageRestriction;
this.stars = stars;
this.category = category;
this.rating = rating;
this.data = data;
content = new ArrayList<>();
content.addAll(data.getMovies());
content.addAll(data.getSeries());
titleCheck = typeCheck = ageCheck = starsCheck = categoryCheck = ratingCheck = false;
}
/**
* Μέθοδος που υλοποιεί την αναζήτηση των μέσων με βάση τα κριτήρια που έδωσε ο χρήστης.
* @return Μια λίστα με τα αποτελέσματα. Αν δε δοθεί κάποιο κριτήριο επιστρέφονται όλα τα μέσα.
*/
public ArrayList<Content> results() {
ArrayList<Content> searchResults = new ArrayList<>();
for (Content media : content) {
titleCheck = typeCheck = ageCheck = starsCheck = categoryCheck = ratingCheck = false;
if (title.equals("") || media.getTitle().equalsIgnoreCase(title)) titleCheck = true;
if (type == null) {
typeCheck = true;
} else if (type.equals(media.getType())) {
typeCheck =true;
}
if (ageRestriction == null) {
ageCheck = true;
} else if (ageRestriction.equals(media.getAgeRestriction())) {
ageCheck = true;
}
if (stars.isEmpty()) {
starsCheck = true;
} else {
for (String star : media.getStars().split(",")) {
if (stars.equalsIgnoreCase(star)) {
starsCheck = true;
break;
}
}
}
if (category == null) {
categoryCheck = true;
} else if (category == media.getCategory()) {
categoryCheck = true;
}
if (rating == null) {
ratingCheck = true;
} else if (Double.compare(rating,-1)==0 || Double.compare(rating, media.AverageRating())<0) {
ratingCheck = true;
}
if (titleCheck && typeCheck && ageCheck && starsCheck && categoryCheck && ratingCheck) {
searchResults.add(media);
}
}
return searchResults;
}
}
|
zaxlois/streaming-tv-platform
|
src/api/Search.java
| 1,432
|
/**
* Κλάση που υλοποιεί την αναζήτηση ενός μέσου και από τους δύο τύπους χρηστών.
* Δημιουργεί ένα αντικείμενο με τα κριτήρια που επέλεξε ο χρήστης και επιστρέφει τα αντίστοιχα αποτελέσματα μέσω μιας λίστας.
*/
|
block_comment
|
el
|
package api;
import api.Media.Category;
import api.Media.Content;
import java.io.Serializable;
import java.util.ArrayList;
/**
* Κλάση που υλοποιεί<SUF>*/
public class Search implements Serializable {
private String title;
private String type;
private String ageRestriction;
private String stars;
private Category category;
private Double rating;
private Data data;
private boolean titleCheck;
private boolean typeCheck;
private boolean ageCheck;
private boolean starsCheck;
private boolean categoryCheck;
private boolean ratingCheck;
private ArrayList<Content> content;
/**
* Κατασκευαστής που δημιουργεί το αντικείμενο αναζήτησης και αρχικοποιεί όλα τα μέλη του
* @param data η βάση δεδομένων
* @param title ο τίτλος που δήλωσε ο χρήστης (μπορεί να μη δηλώσει)
* @param type ο τύπος του μέσου που δήλωσε ο χρήστης (μπορεί να μη δηλώσει)
* @param ageRestriction ο περιορισμός της ηλικίας που δήλωσε ο χρήστης (μπορεί να μη δηλώσει)
* @param stars ο πρωταγωνιστής που δήλωσε ο χρήστης (μπορεί να μη δηλώσει)
* @param category η κατηγορία του μέσου που δήλωσε ο χρήστης (μπορεί να μη δηλώσει)
* @param rating η ελάχιστη μέση βαθμολογία αξιολογήσεων του μέσου που δήλωσε ο χρήστης (μπορεί να μη δηλώσει)
*/
public Search(Data data,String title,String type,String ageRestriction,String stars,Category category,Double rating) {
this.title = title;
this.type = type;
this.ageRestriction = ageRestriction;
this.stars = stars;
this.category = category;
this.rating = rating;
this.data = data;
content = new ArrayList<>();
content.addAll(data.getMovies());
content.addAll(data.getSeries());
titleCheck = typeCheck = ageCheck = starsCheck = categoryCheck = ratingCheck = false;
}
/**
* Μέθοδος που υλοποιεί την αναζήτηση των μέσων με βάση τα κριτήρια που έδωσε ο χρήστης.
* @return Μια λίστα με τα αποτελέσματα. Αν δε δοθεί κάποιο κριτήριο επιστρέφονται όλα τα μέσα.
*/
public ArrayList<Content> results() {
ArrayList<Content> searchResults = new ArrayList<>();
for (Content media : content) {
titleCheck = typeCheck = ageCheck = starsCheck = categoryCheck = ratingCheck = false;
if (title.equals("") || media.getTitle().equalsIgnoreCase(title)) titleCheck = true;
if (type == null) {
typeCheck = true;
} else if (type.equals(media.getType())) {
typeCheck =true;
}
if (ageRestriction == null) {
ageCheck = true;
} else if (ageRestriction.equals(media.getAgeRestriction())) {
ageCheck = true;
}
if (stars.isEmpty()) {
starsCheck = true;
} else {
for (String star : media.getStars().split(",")) {
if (stars.equalsIgnoreCase(star)) {
starsCheck = true;
break;
}
}
}
if (category == null) {
categoryCheck = true;
} else if (category == media.getCategory()) {
categoryCheck = true;
}
if (rating == null) {
ratingCheck = true;
} else if (Double.compare(rating,-1)==0 || Double.compare(rating, media.AverageRating())<0) {
ratingCheck = true;
}
if (titleCheck && typeCheck && ageCheck && starsCheck && categoryCheck && ratingCheck) {
searchResults.add(media);
}
}
return searchResults;
}
}
|
20401_0
|
package com.vavylona.roadnation;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void registrationCredentials(View view){
Intent intent = new Intent(this, RegistrationCredentials.class);
intent.putExtra("DRIVER_OR_CLIENT", view.getId());
startActivity(intent);
}
public void clientLogin(View view){
Intent intent = new Intent(this, ClientLogin.class);
startActivity(intent);
}
public void driverLogin(View view){
Intent intent = new Intent(this, DriverLogin.class);
startActivity(intent);
}
@Override
public void onBackPressed() {
finishAndRemoveTask();
//super.onBackPressed(); //Βγαινει απο την εφαρμογη
}
}
|
zenkodr/Road-Nation
|
Road Nation/RoadNation/app/src/main/java/com/vavylona/roadnation/MainActivity.java
| 248
|
//super.onBackPressed(); //Βγαινει απο την εφαρμογη
|
line_comment
|
el
|
package com.vavylona.roadnation;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void registrationCredentials(View view){
Intent intent = new Intent(this, RegistrationCredentials.class);
intent.putExtra("DRIVER_OR_CLIENT", view.getId());
startActivity(intent);
}
public void clientLogin(View view){
Intent intent = new Intent(this, ClientLogin.class);
startActivity(intent);
}
public void driverLogin(View view){
Intent intent = new Intent(this, DriverLogin.class);
startActivity(intent);
}
@Override
public void onBackPressed() {
finishAndRemoveTask();
//super.onBackPressed(); //Βγαινει<SUF>
}
}
|
2637_0
|
package gr.aueb.cf.projects10;
/**
* Βρίσκει τον υπο-πίνακα με το μεγαλύτερο άθροισμα.
* Θεωρούμε πως έχουμε ένα τοπικό μέγιστο άθροισμα καθώς διατρέχουμε τον πίνακα.
* Προσθέτουμε το τοπικό μέγιστο με το επόμενο στοιχείου του πίνακα.
* Εάν το νέο τοπικό μέγιστο είναι μεγαλύτερο ή ίσο του στοιχείου αυτού, τότε το τοπικό μέγιστο ισούται με το στοιχείο
* αυτό και θεωρούμε πως ο υποπίνακας ξεκινά από εκεί (με την μεταβλητή from).
* Εάν το νέο πια τοπικό μέγιστο είναι μεγαλύτερο ή ίσο του γενικού μέγίστου, τότε γενικό μέγιστο ιστούται με το
* τοπικό μέγιστο και θεωρούμε πως ο υποπίνακας φτάνει μέχρι εκεί (με την μεταβλητή to)
*/
public class Project6 {
public static void main(String[] args) {
int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int localMaximum = arr[0], globalMaximum = arr[0];
int from = 0, to = 0;
for(int i = 1; i < arr.length; i++) { // πολυπλοκότητα O(n) - n : στοιχεία του πίνακα
localMaximum += arr[i];
if(arr[i] >= localMaximum) {
localMaximum = arr[i];
from = i;
}
if(localMaximum >= globalMaximum) {
globalMaximum = localMaximum;
to = i;
}
}
System.out.println("Maximum sum subarray is:");
System.out.printf("{%d", arr[from]);
for(int i = from + 1; i <= to; i++) {
System.out.printf(", %d", arr[i]);
}
System.out.println("}");
System.out.printf("with sum = %d\n", globalMaximum);
}
}
|
zzikoulis/java-projects
|
functional-projects/Project6.java
| 814
|
/**
* Βρίσκει τον υπο-πίνακα με το μεγαλύτερο άθροισμα.
* Θεωρούμε πως έχουμε ένα τοπικό μέγιστο άθροισμα καθώς διατρέχουμε τον πίνακα.
* Προσθέτουμε το τοπικό μέγιστο με το επόμενο στοιχείου του πίνακα.
* Εάν το νέο τοπικό μέγιστο είναι μεγαλύτερο ή ίσο του στοιχείου αυτού, τότε το τοπικό μέγιστο ισούται με το στοιχείο
* αυτό και θεωρούμε πως ο υποπίνακας ξεκινά από εκεί (με την μεταβλητή from).
* Εάν το νέο πια τοπικό μέγιστο είναι μεγαλύτερο ή ίσο του γενικού μέγίστου, τότε γενικό μέγιστο ιστούται με το
* τοπικό μέγιστο και θεωρούμε πως ο υποπίνακας φτάνει μέχρι εκεί (με την μεταβλητή to)
*/
|
block_comment
|
el
|
package gr.aueb.cf.projects10;
/**
* Βρίσκει τον υπο-πίνακα<SUF>*/
public class Project6 {
public static void main(String[] args) {
int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int localMaximum = arr[0], globalMaximum = arr[0];
int from = 0, to = 0;
for(int i = 1; i < arr.length; i++) { // πολυπλοκότητα O(n) - n : στοιχεία του πίνακα
localMaximum += arr[i];
if(arr[i] >= localMaximum) {
localMaximum = arr[i];
from = i;
}
if(localMaximum >= globalMaximum) {
globalMaximum = localMaximum;
to = i;
}
}
System.out.println("Maximum sum subarray is:");
System.out.printf("{%d", arr[from]);
for(int i = from + 1; i <= to; i++) {
System.out.printf(", %d", arr[i]);
}
System.out.println("}");
System.out.printf("with sum = %d\n", globalMaximum);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.