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
193_14
package com.unipi.vnikolis.unipismartalert; import android.annotation.SuppressLint; import android.app.DatePickerDialog; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.DatePicker; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.unipi.vnikolis.unipismartalert.internettracker.CheckInternetConnection; import com.unipi.vnikolis.unipismartalert.model.Values; import com.unipi.vnikolis.unipismartalert.adapter.ItemsAdapter; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; /** * The backend code for Statistics Activity */ public class ShowStatistics extends AppCompatActivity implements AdapterView.OnItemClickListener { FirebaseDatabase firebaseDatabase; DatabaseReference possiblyDanger, bigDanger, lightDanger, speedDanger, dropDanger; Spinner mDangerSpinner, mSortDateSpinner; String dangerSelect, dateSelect, twoDigitMonth, twoDigitDay, dateToCompare, dateToView; TextView dateView; DatePickerDialog.OnDateSetListener mDateSetListener; ArrayList<Values> dangerList = new ArrayList<>(); boolean dateIsSelected, sortDatesIsSelected, dangerIsSelected; static boolean isItemsButtonClicked; ArrayAdapter<String> myAdapter2, myAdapter; ItemsAdapter adapter; ListView mUserList; Values v; int firstTime; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_statistics); firebaseDatabase = FirebaseDatabase.getInstance(); possiblyDanger = firebaseDatabase.getReference("PossiblyDanger"); bigDanger = firebaseDatabase.getReference("BigDanger"); lightDanger = possiblyDanger.child("LightDanger"); speedDanger = possiblyDanger.child("SpeedDanger"); dropDanger = possiblyDanger.child("DropDanger"); mUserList = findViewById(R.id.listView); try { if (CheckInternetConnection.isConnected(ShowStatistics.this) && CheckInternetConnection.isConnectedFast(ShowStatistics.this)) { //ελεγχος εαν υπάρχει σύνδεση Internet calendarPicker(); dangerPicker(); datePicker(); dangerSelect(); }else{ Toast.makeText(ShowStatistics.this, "Δεν υπάρχει σύνδεση στο Internet, προσπάθησε ξανά", Toast.LENGTH_LONG).show(); } }catch (Exception e){ e.printStackTrace(); Log.e("SOS", "Something went wrong"); } } /** * Κατασκεύη ημερολογίου και * Επιλογή ημερομηνίας */ public void calendarPicker(){ try { //create the calendar date picker dateView = findViewById(R.id.dateView); dateView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dateIsSelected = true; Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); DatePickerDialog dialog = new DatePickerDialog(ShowStatistics.this, mDateSetListener, year, month, day); dialog.show(); } }); mDateSetListener = new DatePickerDialog.OnDateSetListener() { @SuppressLint("SetTextI18n") @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { firstTime++; if (firstTime > 1) { //για να μην κρασαρει την πρωτη φορα που ανοιγει η εφαρμογη επιλεγοντας πρωτα την ημερομηνια mDangerSpinner.setAdapter(myAdapter); adapter.clear(); } if (firstTime == 1 && dangerIsSelected) { //για να μην κρασαρει την πρωτη φορα που ανοιγει η εφαρμογη επιλεγοντας πρωτα την ημερομηνια mDangerSpinner.setAdapter(myAdapter); adapter.clear(); } month++; // οι μήνες ξεκινάνε από το 0 οπότε προσθέτουμε 1 // Τωρα θα τα μετατρέψω σε 2 digit format γιατί έτσι είναι αποθηκευμένα στη βάση // ώστε να κάνω σύγκριση if (month < 10) { twoDigitMonth = "0" + month; } else { twoDigitMonth = String.valueOf(month); } if (dayOfMonth < 10) { twoDigitDay = "0" + dayOfMonth; } else { twoDigitDay = String.valueOf(dayOfMonth); } dateToCompare = year + "/" + twoDigitMonth + "/" + twoDigitDay; dateToView = twoDigitDay + "/" + twoDigitMonth + "/" + year; dateView.setText(dateToView); } }; }catch (Exception e){ Toast.makeText(ShowStatistics.this, "Κάτι πήγε στραβά, προσπάθησε ξανά", Toast.LENGTH_LONG).show(); } } /** * Επιλογή κινδύνου από το dropDown Menu */ public void dangerPicker(){ try { //τραβάει τα δεδομένα από το dropdown menu ανα κατηγορια συμβαντος mDangerSpinner = findViewById(R.id.spinner); myAdapter = new ArrayAdapter<String>(ShowStatistics.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.spinnerItems)) { @Override public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { tv.setVisibility(View.GONE); } else { //τοποθετηση χρώματος tv.setVisibility(View.VISIBLE); if (position % 2 == 1) { tv.setBackgroundColor(Color.parseColor("#FFF9A600")); } else { tv.setBackgroundColor(Color.parseColor("#FFE49200")); } } return view; } }; myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mDangerSpinner.setPrompt("Choose Danger Category"); mDangerSpinner.setAdapter(myAdapter); }catch (Exception e){ Toast.makeText(ShowStatistics.this, "Κάτι πήγε στραβά, προσπάθησε ξανά", Toast.LENGTH_LONG).show(); } } /** * Επιλογή ταξινόμισης από το dropDown Menu */ public void datePicker(){ mSortDateSpinner = findViewById(R.id.spinner2); myAdapter2 = new ArrayAdapter<String>(ShowStatistics.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.spinnerItems2)){ @SuppressLint("SetTextI18n") @Override public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent){ sortDatesIsSelected = true; View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if(position == 0) { tv.setVisibility(View.GONE); } else{ //τοποθετηση χρώματος tv.setVisibility(View.VISIBLE); if(position%2==1) { tv.setBackgroundColor(Color.parseColor("#FFF9A600")); } else{ tv.setBackgroundColor(Color.parseColor("#FFE49200")); } } return view; } }; myAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mSortDateSpinner.setPrompt("Choose to Sort by Date"); mSortDateSpinner.setAdapter(myAdapter2); } /** * Ανάλογα με την επιλογή κινδύνου που θα γίνει * θα τραβήξει και τα αντίστοιχα αποτελέσματα */ public void dangerSelect() { try { mDangerSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { dangerSelect = mDangerSpinner.getSelectedItem().toString(); switch (dangerSelect) { case "Drop Danger": dangerIsSelected = true; //επιλογή κινδύνου dangerSelector(dropDanger); //επιλογή ταξινόμισης sortDateSelector(dropDanger, mSortDateSpinner); break; case "Speed Danger": dangerIsSelected = true; dangerSelector(speedDanger); sortDateSelector(speedDanger, mSortDateSpinner); break; case "Light Danger": dangerIsSelected = true; dangerSelector(lightDanger); sortDateSelector(lightDanger, mSortDateSpinner); break; case "Possibly Danger": dangerIsSelected = true; dangerSelector(possiblyDanger); sortDateSelector(possiblyDanger, mSortDateSpinner); break; case "Big Danger": dangerIsSelected = true; dangerSelector(bigDanger); sortDateSelector(bigDanger, mSortDateSpinner); break; } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); }catch (Exception e){ e.printStackTrace(); Log.e("SOS", "Something went wrong"); } } /** * Συλλογή δεδομένων από την FireBase * ταξινόμηση εαν χρειάζεται και τοποθέτηση * των δεομένων στο ListView για την εμφάνιση των αποτελεσμάτων * @param keys Μεταβλητή Iterable τύπου DataSnapshot για την καταλληλότερη * αναζήτηση αποτελεσμάτων */ @SuppressLint("SetTextI18n") private void collectDangers(Iterable<DataSnapshot> keys) { try { dangerList.clear(); adapter = new ItemsAdapter(this, dangerList); mUserList.setAdapter(adapter); mUserList.setOnItemClickListener(this); String compareDate; if (dangerSelect.equals("Possibly Danger")) { for (DataSnapshot i : keys) { for (DataSnapshot j : i.getChildren()) { v = j.getValue(Values.class); //εαν υπάρχει διαθέσιμη ημερομηνία από το ημερολόγιο για σύγκριση... κάνε την σύγκριση if (dateToCompare != null) { assert v != null; compareDate = v.getDate().substring(0, 10); //πάρε μονο ένα κομάτι από την συμβολοσειρά της ημερομηνίας που είναι αποθηκευμένη στη βάση if (compareDate.equals(dateToCompare)) { //και συγκρινέ αυτήν με την ημερομηνία που έχει επιλεγεί από το ημερολόγιο adapter.add(v); //γέμισε την λίστα } } else { adapter.add(v); //εδω γεμίζει η list } } } } else if (dangerSelect.equals("Big Danger") || dangerSelect.equals("Light Danger") || dangerSelect.equals("Speed Danger") || dangerSelect.equals("Drop Danger")) { for (DataSnapshot i : keys) { v = i.getValue(Values.class); if (dateToCompare != null) { assert v != null; compareDate = v.getDate().substring(0, 10); if (compareDate.equals(dateToCompare)) { adapter.add(v); } } else { adapter.add(v); //εδω γεμίζει η list } } } //εαν εχει επιλεγει η ταξινομιση κάνε την κατα άυξουσα η φθίνουσα σειρά if (dateSelect != null) { if (dateSelect.equals("Ascending")) { //ταξινόμιση βαση ημερομηνιας κατα αυξουσα Collections.sort(dangerList, new Comparator<Values>() { @Override public int compare(Values o1, Values o2) { return o1.getDate().compareTo(o2.getDate()); } }); } else if (dateSelect.equals("Descending")) { //ταξινόμηση βαση ημερομηνιας κατα φθινουσα Collections.sort(dangerList, Collections.reverseOrder(new Comparator<Values>() { @Override public int compare(Values o1, Values o2) { return o1.getDate().compareTo(o2.getDate()); } })); } } dateView.setText("Pick Date"); dateToCompare = null; mSortDateSpinner.setAdapter(myAdapter2); }catch (Exception e){ e.printStackTrace(); Log.e("SOS", "Something went wrong"); } } /** * Σε κάθε αλλάγη της FireBase καλεί την μέδοδο collectDangers * @param kindOfDanger To Reference της FireBase */ private void dangerSelector(DatabaseReference kindOfDanger){ kindOfDanger.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) //εαν υπάρχει κάτι σε αυτον τον πίνακα { collectDangers(dataSnapshot.getChildren()); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Toast.makeText(ShowStatistics.this, "Αποτυχία Ανάγνωσης από τη Βάση", Toast.LENGTH_LONG).show(); } }); } /** * Επιλογή ταξινόμησης κατα άυξουσα η φθίνουσα σειρά * @param kindOfDanger To Reference της FireBase * @param selectorToSort Ο Spinner που θέλουμε */ // private void sortDateSelector(final DatabaseReference kindOfDanger, Spinner selectorToSort){ selectorToSort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { dateSelect = mSortDateSpinner.getSelectedItem().toString(); switch (dateSelect){ case "Ascending": //ταξινόμιση κατα άυξουσα dangerSelector(kindOfDanger); break; //ταξινόμιση κατα φθίνουσα case "Descending": dangerSelector(kindOfDanger); break; } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } /** * Μετάβαση στους χάρτες για έυρεση της συγκεκριμένης * τοποθεσίας από το ListView * @param parent .. * @param view .. * @param position .. * @param id .. */ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { isItemsButtonClicked = true; MainActivity.isMapsButtonPressed = false; Values o =(Values) mUserList.getItemAtPosition(position); Intent maps = new Intent(ShowStatistics.this, MapsActivity.class); maps.putExtra("latitude", o.getLatitude()); maps.putExtra("longitude", o.getLongitude()); maps.putExtra("date", o.CorrectDate()); startActivity(maps); } }
3ngk1sha/DangerDetect
app/src/main/java/com/unipi/vnikolis/unipismartalert/ShowStatistics.java
4,658
//εαν υπάρχει διαθέσιμη ημερομηνία από το ημερολόγιο για σύγκριση... κάνε την σύγκριση
line_comment
el
package com.unipi.vnikolis.unipismartalert; import android.annotation.SuppressLint; import android.app.DatePickerDialog; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.DatePicker; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.unipi.vnikolis.unipismartalert.internettracker.CheckInternetConnection; import com.unipi.vnikolis.unipismartalert.model.Values; import com.unipi.vnikolis.unipismartalert.adapter.ItemsAdapter; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; /** * The backend code for Statistics Activity */ public class ShowStatistics extends AppCompatActivity implements AdapterView.OnItemClickListener { FirebaseDatabase firebaseDatabase; DatabaseReference possiblyDanger, bigDanger, lightDanger, speedDanger, dropDanger; Spinner mDangerSpinner, mSortDateSpinner; String dangerSelect, dateSelect, twoDigitMonth, twoDigitDay, dateToCompare, dateToView; TextView dateView; DatePickerDialog.OnDateSetListener mDateSetListener; ArrayList<Values> dangerList = new ArrayList<>(); boolean dateIsSelected, sortDatesIsSelected, dangerIsSelected; static boolean isItemsButtonClicked; ArrayAdapter<String> myAdapter2, myAdapter; ItemsAdapter adapter; ListView mUserList; Values v; int firstTime; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_statistics); firebaseDatabase = FirebaseDatabase.getInstance(); possiblyDanger = firebaseDatabase.getReference("PossiblyDanger"); bigDanger = firebaseDatabase.getReference("BigDanger"); lightDanger = possiblyDanger.child("LightDanger"); speedDanger = possiblyDanger.child("SpeedDanger"); dropDanger = possiblyDanger.child("DropDanger"); mUserList = findViewById(R.id.listView); try { if (CheckInternetConnection.isConnected(ShowStatistics.this) && CheckInternetConnection.isConnectedFast(ShowStatistics.this)) { //ελεγχος εαν υπάρχει σύνδεση Internet calendarPicker(); dangerPicker(); datePicker(); dangerSelect(); }else{ Toast.makeText(ShowStatistics.this, "Δεν υπάρχει σύνδεση στο Internet, προσπάθησε ξανά", Toast.LENGTH_LONG).show(); } }catch (Exception e){ e.printStackTrace(); Log.e("SOS", "Something went wrong"); } } /** * Κατασκεύη ημερολογίου και * Επιλογή ημερομηνίας */ public void calendarPicker(){ try { //create the calendar date picker dateView = findViewById(R.id.dateView); dateView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dateIsSelected = true; Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); DatePickerDialog dialog = new DatePickerDialog(ShowStatistics.this, mDateSetListener, year, month, day); dialog.show(); } }); mDateSetListener = new DatePickerDialog.OnDateSetListener() { @SuppressLint("SetTextI18n") @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { firstTime++; if (firstTime > 1) { //για να μην κρασαρει την πρωτη φορα που ανοιγει η εφαρμογη επιλεγοντας πρωτα την ημερομηνια mDangerSpinner.setAdapter(myAdapter); adapter.clear(); } if (firstTime == 1 && dangerIsSelected) { //για να μην κρασαρει την πρωτη φορα που ανοιγει η εφαρμογη επιλεγοντας πρωτα την ημερομηνια mDangerSpinner.setAdapter(myAdapter); adapter.clear(); } month++; // οι μήνες ξεκινάνε από το 0 οπότε προσθέτουμε 1 // Τωρα θα τα μετατρέψω σε 2 digit format γιατί έτσι είναι αποθηκευμένα στη βάση // ώστε να κάνω σύγκριση if (month < 10) { twoDigitMonth = "0" + month; } else { twoDigitMonth = String.valueOf(month); } if (dayOfMonth < 10) { twoDigitDay = "0" + dayOfMonth; } else { twoDigitDay = String.valueOf(dayOfMonth); } dateToCompare = year + "/" + twoDigitMonth + "/" + twoDigitDay; dateToView = twoDigitDay + "/" + twoDigitMonth + "/" + year; dateView.setText(dateToView); } }; }catch (Exception e){ Toast.makeText(ShowStatistics.this, "Κάτι πήγε στραβά, προσπάθησε ξανά", Toast.LENGTH_LONG).show(); } } /** * Επιλογή κινδύνου από το dropDown Menu */ public void dangerPicker(){ try { //τραβάει τα δεδομένα από το dropdown menu ανα κατηγορια συμβαντος mDangerSpinner = findViewById(R.id.spinner); myAdapter = new ArrayAdapter<String>(ShowStatistics.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.spinnerItems)) { @Override public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) { View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if (position == 0) { tv.setVisibility(View.GONE); } else { //τοποθετηση χρώματος tv.setVisibility(View.VISIBLE); if (position % 2 == 1) { tv.setBackgroundColor(Color.parseColor("#FFF9A600")); } else { tv.setBackgroundColor(Color.parseColor("#FFE49200")); } } return view; } }; myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mDangerSpinner.setPrompt("Choose Danger Category"); mDangerSpinner.setAdapter(myAdapter); }catch (Exception e){ Toast.makeText(ShowStatistics.this, "Κάτι πήγε στραβά, προσπάθησε ξανά", Toast.LENGTH_LONG).show(); } } /** * Επιλογή ταξινόμισης από το dropDown Menu */ public void datePicker(){ mSortDateSpinner = findViewById(R.id.spinner2); myAdapter2 = new ArrayAdapter<String>(ShowStatistics.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.spinnerItems2)){ @SuppressLint("SetTextI18n") @Override public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent){ sortDatesIsSelected = true; View view = super.getDropDownView(position, convertView, parent); TextView tv = (TextView) view; if(position == 0) { tv.setVisibility(View.GONE); } else{ //τοποθετηση χρώματος tv.setVisibility(View.VISIBLE); if(position%2==1) { tv.setBackgroundColor(Color.parseColor("#FFF9A600")); } else{ tv.setBackgroundColor(Color.parseColor("#FFE49200")); } } return view; } }; myAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mSortDateSpinner.setPrompt("Choose to Sort by Date"); mSortDateSpinner.setAdapter(myAdapter2); } /** * Ανάλογα με την επιλογή κινδύνου που θα γίνει * θα τραβήξει και τα αντίστοιχα αποτελέσματα */ public void dangerSelect() { try { mDangerSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { dangerSelect = mDangerSpinner.getSelectedItem().toString(); switch (dangerSelect) { case "Drop Danger": dangerIsSelected = true; //επιλογή κινδύνου dangerSelector(dropDanger); //επιλογή ταξινόμισης sortDateSelector(dropDanger, mSortDateSpinner); break; case "Speed Danger": dangerIsSelected = true; dangerSelector(speedDanger); sortDateSelector(speedDanger, mSortDateSpinner); break; case "Light Danger": dangerIsSelected = true; dangerSelector(lightDanger); sortDateSelector(lightDanger, mSortDateSpinner); break; case "Possibly Danger": dangerIsSelected = true; dangerSelector(possiblyDanger); sortDateSelector(possiblyDanger, mSortDateSpinner); break; case "Big Danger": dangerIsSelected = true; dangerSelector(bigDanger); sortDateSelector(bigDanger, mSortDateSpinner); break; } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); }catch (Exception e){ e.printStackTrace(); Log.e("SOS", "Something went wrong"); } } /** * Συλλογή δεδομένων από την FireBase * ταξινόμηση εαν χρειάζεται και τοποθέτηση * των δεομένων στο ListView για την εμφάνιση των αποτελεσμάτων * @param keys Μεταβλητή Iterable τύπου DataSnapshot για την καταλληλότερη * αναζήτηση αποτελεσμάτων */ @SuppressLint("SetTextI18n") private void collectDangers(Iterable<DataSnapshot> keys) { try { dangerList.clear(); adapter = new ItemsAdapter(this, dangerList); mUserList.setAdapter(adapter); mUserList.setOnItemClickListener(this); String compareDate; if (dangerSelect.equals("Possibly Danger")) { for (DataSnapshot i : keys) { for (DataSnapshot j : i.getChildren()) { v = j.getValue(Values.class); //εαν υπάρχει<SUF> if (dateToCompare != null) { assert v != null; compareDate = v.getDate().substring(0, 10); //πάρε μονο ένα κομάτι από την συμβολοσειρά της ημερομηνίας που είναι αποθηκευμένη στη βάση if (compareDate.equals(dateToCompare)) { //και συγκρινέ αυτήν με την ημερομηνία που έχει επιλεγεί από το ημερολόγιο adapter.add(v); //γέμισε την λίστα } } else { adapter.add(v); //εδω γεμίζει η list } } } } else if (dangerSelect.equals("Big Danger") || dangerSelect.equals("Light Danger") || dangerSelect.equals("Speed Danger") || dangerSelect.equals("Drop Danger")) { for (DataSnapshot i : keys) { v = i.getValue(Values.class); if (dateToCompare != null) { assert v != null; compareDate = v.getDate().substring(0, 10); if (compareDate.equals(dateToCompare)) { adapter.add(v); } } else { adapter.add(v); //εδω γεμίζει η list } } } //εαν εχει επιλεγει η ταξινομιση κάνε την κατα άυξουσα η φθίνουσα σειρά if (dateSelect != null) { if (dateSelect.equals("Ascending")) { //ταξινόμιση βαση ημερομηνιας κατα αυξουσα Collections.sort(dangerList, new Comparator<Values>() { @Override public int compare(Values o1, Values o2) { return o1.getDate().compareTo(o2.getDate()); } }); } else if (dateSelect.equals("Descending")) { //ταξινόμηση βαση ημερομηνιας κατα φθινουσα Collections.sort(dangerList, Collections.reverseOrder(new Comparator<Values>() { @Override public int compare(Values o1, Values o2) { return o1.getDate().compareTo(o2.getDate()); } })); } } dateView.setText("Pick Date"); dateToCompare = null; mSortDateSpinner.setAdapter(myAdapter2); }catch (Exception e){ e.printStackTrace(); Log.e("SOS", "Something went wrong"); } } /** * Σε κάθε αλλάγη της FireBase καλεί την μέδοδο collectDangers * @param kindOfDanger To Reference της FireBase */ private void dangerSelector(DatabaseReference kindOfDanger){ kindOfDanger.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) //εαν υπάρχει κάτι σε αυτον τον πίνακα { collectDangers(dataSnapshot.getChildren()); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Toast.makeText(ShowStatistics.this, "Αποτυχία Ανάγνωσης από τη Βάση", Toast.LENGTH_LONG).show(); } }); } /** * Επιλογή ταξινόμησης κατα άυξουσα η φθίνουσα σειρά * @param kindOfDanger To Reference της FireBase * @param selectorToSort Ο Spinner που θέλουμε */ // private void sortDateSelector(final DatabaseReference kindOfDanger, Spinner selectorToSort){ selectorToSort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { dateSelect = mSortDateSpinner.getSelectedItem().toString(); switch (dateSelect){ case "Ascending": //ταξινόμιση κατα άυξουσα dangerSelector(kindOfDanger); break; //ταξινόμιση κατα φθίνουσα case "Descending": dangerSelector(kindOfDanger); break; } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } /** * Μετάβαση στους χάρτες για έυρεση της συγκεκριμένης * τοποθεσίας από το ListView * @param parent .. * @param view .. * @param position .. * @param id .. */ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { isItemsButtonClicked = true; MainActivity.isMapsButtonPressed = false; Values o =(Values) mUserList.getItemAtPosition(position); Intent maps = new Intent(ShowStatistics.this, MapsActivity.class); maps.putExtra("latitude", o.getLatitude()); maps.putExtra("longitude", o.getLongitude()); maps.putExtra("date", o.CorrectDate()); startActivity(maps); } }
6196_34
package info.android_angel.navigationdrawer.activity_tv; /** * Created by ANGELOS on 2017. * */ import android.content.Intent; import android.os.Bundle; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.ads.AdView; import java.util.List; import info.android_angel.navigationdrawer.R; import info.android_angel.navigationdrawer.activity_movies.SearchActivity; import info.android_angel.navigationdrawer.activity_movies.Show_Movie_Details_ID; import info.android_angel.navigationdrawer.adapter.TVAdapter; import info.android_angel.navigationdrawer.model.TV; import info.android_angel.navigationdrawer.model.TVResponse; import info.android_angel.navigationdrawer.package_recycler_touch_listener.RecyclerTouchListener; import info.android_angel.navigationdrawer.rest.ApiClient; import info.android_angel.navigationdrawer.rest.ApiInterface; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class Top_Rated_TV extends AppCompatActivity { private final static String page_2 = "2"; private final static String page_3 = "3"; /** 2017 ads**/ private AdView mAdView; private static final String TAG = Top_Rated_TV.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.nav_tv_get_airing_today); getSupportActionBar().setDisplayHomeAsUpEnabled(true); if (getResources().getString(R.string.API_KEY).isEmpty()) { Toast.makeText(getApplicationContext(), "Please obtain your API KEY from themoviedb.org first!", Toast.LENGTH_LONG).show(); return; } final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.tvs_recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class); /** 2017 AdView mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder() .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) // Check the LogCat to get your test device ID .addTestDevice("C04B1BFFB0774708339BC273F8A43708") .build(); mAdView.setAdListener(new AdListener() { @Override public void onAdLoaded() { } @Override public void onAdClosed() { Toast.makeText(getApplicationContext(), "Ad is closed!", Toast.LENGTH_SHORT).show(); } @Override public void onAdFailedToLoad(int errorCode) { Toast.makeText(getApplicationContext(), "Ad failed to load! error code: " + errorCode, Toast.LENGTH_SHORT).show(); } @Override public void onAdLeftApplication() { Toast.makeText(getApplicationContext(), "Ad left application!", Toast.LENGTH_SHORT).show(); } @Override public void onAdOpened() { super.onAdOpened(); } }); mAdView.loadAd(adRequest);**/ /**END 2017 AdView **/ /** Προσοχή εδώ η αλλάγή............. **/ Call<TVResponse> call = apiService.getTopRatedTv(getResources().getString(R.string.API_KEY)); call.enqueue(new Callback<TVResponse>() { @Override public void onResponse(Call<TVResponse> call, Response<TVResponse> response) { if (!response.isSuccessful()) { System.out.println("Error"); } if(response.isSuccessful()) { List<TV> tvs = response.body().getResults(); recyclerView.setAdapter(new TVAdapter(tvs, R.layout.nav_tv_get_airing_today_list_item, getApplicationContext())); }else{ int statusCode = response.code(); switch(statusCode){ case 401: Toast.makeText(getApplicationContext(),"Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show(); case 404: Toast.makeText(getApplicationContext(),"The resource you requested could not be found.", Toast.LENGTH_SHORT).show(); } } /** recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() { @Override public void onClick(View view, int position) { // on selecting a single album // TrackListActivity will be launched to show tracks inside the album Intent i = new Intent(getApplicationContext(), Show_TV_Details_ID.class); String tv_id = ((TextView) view.findViewById(R.id.tv_id)).getText().toString(); i.putExtra("tv_id", tv_id); //i.putExtra(KEY_MOVIE_ID, movies_response.get(position).getId()); //Toast.makeText(getApplicationContext(),tv_id, Toast.LENGTH_SHORT).show(); startActivity(i); } @Override public void onLongClick(View view, int position) { } })); **/ } @Override public void onFailure(Call<TVResponse> call, Throwable t) { // Log error here since request failed Log.e(TAG, t.toString()); } }); /** PAGE = 2 **/ final RecyclerView recyclerView_2 = (RecyclerView) findViewById(R.id.tvs_recycler_view_page_2); recyclerView_2.setLayoutManager(new LinearLayoutManager(this)); Call<TVResponse> call_2 = apiService.getTopRatedTv_2(getResources().getString(R.string.API_KEY), page_2); call_2.enqueue(new Callback<TVResponse>() { @Override public void onResponse(Call<TVResponse> call_2, final Response<TVResponse> response) { if (!response.isSuccessful()) { //System.out.println("Error"); } if(response.isSuccessful()) { final List<TV> tvs = response.body().getResults(); recyclerView_2.setAdapter(new TVAdapter(tvs, R.layout.nav_tv_get_airing_today_list_item, getApplicationContext())); }else{ int statusCode = response.code(); switch(statusCode){ case 401: //Toast.makeText(getApplicationContext(),"Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show(); case 404: //Toast.makeText(getApplicationContext(),"The resource you requested could not be found.", Toast.LENGTH_SHORT).show(); } } recyclerView_2.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView_2, new RecyclerTouchListener.ClickListener() { @Override public void onClick(View view, int position) { // on selecting a single album // TrackListActivity will be launched to show tracks inside the album Intent i = new Intent(getApplicationContext(), Show_Movie_Details_ID.class); String movie_id = ((TextView) view.findViewById(R.id.movie_id)).getText().toString(); i.putExtra("movie_id", movie_id); //i.putExtra(KEY_MOVIE_ID, movies_response.get(position).getId()); //Toast.makeText(getApplicationContext(),movie_id, Toast.LENGTH_SHORT).show(); startActivity(i); } @Override public void onLongClick(View view, int position) { // on selecting a single album // TrackListActivity will be launched to show tracks inside the album //Intent i = new Intent(getApplicationContext(), Show_Movie_Details_ID.class); // send album id to tracklist activity to get list of songs under that album //String movie_id = ((TextView) view.findViewById(R.id.movie_id)).getText().toString(); //i.putExtra("movie_id", movie_id); //startActivity(i); } })); } @Override public void onFailure(Call<TVResponse> call_2, Throwable t) { // Log error here since request failed //Log.e(TAG, t.toString()); } }); /** PAGE = 3 **/ final RecyclerView recyclerView_3 = (RecyclerView) findViewById(R.id.tvs_recycler_view_page_3); recyclerView_3.setLayoutManager(new LinearLayoutManager(this)); Call<TVResponse> call_3 = apiService.getTopRatedTv_2(getResources().getString(R.string.API_KEY), page_3); call_3.enqueue(new Callback<TVResponse>() { @Override public void onResponse(Call<TVResponse> call_3, final Response<TVResponse> response) { if (!response.isSuccessful()) { //System.out.println("Error"); } if(response.isSuccessful()) { final List<TV> tvs = response.body().getResults(); recyclerView_3.setAdapter(new TVAdapter(tvs, R.layout.nav_tv_get_airing_today_list_item, getApplicationContext())); }else{ int statusCode = response.code(); switch(statusCode){ case 401: //Toast.makeText(getApplicationContext(),"Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show(); case 404: //Toast.makeText(getApplicationContext(),"The resource you requested could not be found.", Toast.LENGTH_SHORT).show(); } } recyclerView_3.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView_3, new RecyclerTouchListener.ClickListener() { @Override public void onClick(View view, int position) { // on selecting a single album // TrackListActivity will be launched to show tracks inside the album Intent i = new Intent(getApplicationContext(), Show_Movie_Details_ID.class); String movie_id = ((TextView) view.findViewById(R.id.movie_id)).getText().toString(); i.putExtra("movie_id", movie_id); //i.putExtra(KEY_MOVIE_ID, movies_response.get(position).getId()); //Toast.makeText(getApplicationContext(),movie_id, Toast.LENGTH_SHORT).show(); startActivity(i); } @Override public void onLongClick(View view, int position) { // on selecting a single album // TrackListActivity will be launched to show tracks inside the album //Intent i = new Intent(getApplicationContext(), Show_Movie_Details_ID.class); // send album id to tracklist activity to get list of songs under that album //String movie_id = ((TextView) view.findViewById(R.id.movie_id)).getText().toString(); //i.putExtra("movie_id", movie_id); //startActivity(i); } })); } @Override public void onFailure(Call<TVResponse> call_3, Throwable t) { // Log error here since request failed //Log.e(TAG, t.toString()); } }); } /** SEARCH **/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); MenuItem search = menu.findItem(R.id.search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(search); search(searchView); return true; } /** SEARCH **/ private void search(SearchView searchView) { searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { //Toast.makeText(Popular_Movie.this, "Search is Selected", Toast.LENGTH_SHORT).show(); Intent i = new Intent(Top_Rated_TV.this,SearchActivity.class); String api_key_search = query.toString(); i.putExtra("api_key_search", api_key_search); /**switch_key_activity for SearchActivity **/ String switch_key_activity = "Top_Rated_TV"; i.putExtra("switch_key_activity", switch_key_activity); //Toast.makeText(MainActivity.this, api_key_search, Toast.LENGTH_SHORT).show(); //String api_key_search = ((TextView) menu.findItem(R.id.search)).getText().toString(); //i.putExtra("api_key_search", api_key_search); startActivity(i); return true; } @Override public boolean onQueryTextChange(final String newText) { return false; } }); } /** Για το βέλος που μας πηγαίνει στο αρχικό μενού **/ @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == android.R.id.home) { // finish the activity onBackPressed(); return true; } return super.onOptionsItemSelected(item); } /** 2017 ads @Override public void onPause() { if (mAdView != null) { mAdView.pause(); } super.onPause(); } @Override public void onResume() { super.onResume(); if (mAdView != null) { mAdView.resume(); } } @Override public void onDestroy() { if (mAdView != null) { mAdView.destroy(); } super.onDestroy(); } **/ }
ANGELOS-TSILAFAKIS/NavigationDrawerPublic
app/src/main/java/info/android_angel/navigationdrawer/activity_tv/Top_Rated_TV.java
3,356
/** Για το βέλος που μας πηγαίνει στο αρχικό μενού **/
block_comment
el
package info.android_angel.navigationdrawer.activity_tv; /** * Created by ANGELOS on 2017. * */ import android.content.Intent; import android.os.Bundle; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.ads.AdView; import java.util.List; import info.android_angel.navigationdrawer.R; import info.android_angel.navigationdrawer.activity_movies.SearchActivity; import info.android_angel.navigationdrawer.activity_movies.Show_Movie_Details_ID; import info.android_angel.navigationdrawer.adapter.TVAdapter; import info.android_angel.navigationdrawer.model.TV; import info.android_angel.navigationdrawer.model.TVResponse; import info.android_angel.navigationdrawer.package_recycler_touch_listener.RecyclerTouchListener; import info.android_angel.navigationdrawer.rest.ApiClient; import info.android_angel.navigationdrawer.rest.ApiInterface; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class Top_Rated_TV extends AppCompatActivity { private final static String page_2 = "2"; private final static String page_3 = "3"; /** 2017 ads**/ private AdView mAdView; private static final String TAG = Top_Rated_TV.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.nav_tv_get_airing_today); getSupportActionBar().setDisplayHomeAsUpEnabled(true); if (getResources().getString(R.string.API_KEY).isEmpty()) { Toast.makeText(getApplicationContext(), "Please obtain your API KEY from themoviedb.org first!", Toast.LENGTH_LONG).show(); return; } final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.tvs_recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class); /** 2017 AdView mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder() .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) // Check the LogCat to get your test device ID .addTestDevice("C04B1BFFB0774708339BC273F8A43708") .build(); mAdView.setAdListener(new AdListener() { @Override public void onAdLoaded() { } @Override public void onAdClosed() { Toast.makeText(getApplicationContext(), "Ad is closed!", Toast.LENGTH_SHORT).show(); } @Override public void onAdFailedToLoad(int errorCode) { Toast.makeText(getApplicationContext(), "Ad failed to load! error code: " + errorCode, Toast.LENGTH_SHORT).show(); } @Override public void onAdLeftApplication() { Toast.makeText(getApplicationContext(), "Ad left application!", Toast.LENGTH_SHORT).show(); } @Override public void onAdOpened() { super.onAdOpened(); } }); mAdView.loadAd(adRequest);**/ /**END 2017 AdView **/ /** Προσοχή εδώ η αλλάγή............. **/ Call<TVResponse> call = apiService.getTopRatedTv(getResources().getString(R.string.API_KEY)); call.enqueue(new Callback<TVResponse>() { @Override public void onResponse(Call<TVResponse> call, Response<TVResponse> response) { if (!response.isSuccessful()) { System.out.println("Error"); } if(response.isSuccessful()) { List<TV> tvs = response.body().getResults(); recyclerView.setAdapter(new TVAdapter(tvs, R.layout.nav_tv_get_airing_today_list_item, getApplicationContext())); }else{ int statusCode = response.code(); switch(statusCode){ case 401: Toast.makeText(getApplicationContext(),"Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show(); case 404: Toast.makeText(getApplicationContext(),"The resource you requested could not be found.", Toast.LENGTH_SHORT).show(); } } /** recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() { @Override public void onClick(View view, int position) { // on selecting a single album // TrackListActivity will be launched to show tracks inside the album Intent i = new Intent(getApplicationContext(), Show_TV_Details_ID.class); String tv_id = ((TextView) view.findViewById(R.id.tv_id)).getText().toString(); i.putExtra("tv_id", tv_id); //i.putExtra(KEY_MOVIE_ID, movies_response.get(position).getId()); //Toast.makeText(getApplicationContext(),tv_id, Toast.LENGTH_SHORT).show(); startActivity(i); } @Override public void onLongClick(View view, int position) { } })); **/ } @Override public void onFailure(Call<TVResponse> call, Throwable t) { // Log error here since request failed Log.e(TAG, t.toString()); } }); /** PAGE = 2 **/ final RecyclerView recyclerView_2 = (RecyclerView) findViewById(R.id.tvs_recycler_view_page_2); recyclerView_2.setLayoutManager(new LinearLayoutManager(this)); Call<TVResponse> call_2 = apiService.getTopRatedTv_2(getResources().getString(R.string.API_KEY), page_2); call_2.enqueue(new Callback<TVResponse>() { @Override public void onResponse(Call<TVResponse> call_2, final Response<TVResponse> response) { if (!response.isSuccessful()) { //System.out.println("Error"); } if(response.isSuccessful()) { final List<TV> tvs = response.body().getResults(); recyclerView_2.setAdapter(new TVAdapter(tvs, R.layout.nav_tv_get_airing_today_list_item, getApplicationContext())); }else{ int statusCode = response.code(); switch(statusCode){ case 401: //Toast.makeText(getApplicationContext(),"Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show(); case 404: //Toast.makeText(getApplicationContext(),"The resource you requested could not be found.", Toast.LENGTH_SHORT).show(); } } recyclerView_2.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView_2, new RecyclerTouchListener.ClickListener() { @Override public void onClick(View view, int position) { // on selecting a single album // TrackListActivity will be launched to show tracks inside the album Intent i = new Intent(getApplicationContext(), Show_Movie_Details_ID.class); String movie_id = ((TextView) view.findViewById(R.id.movie_id)).getText().toString(); i.putExtra("movie_id", movie_id); //i.putExtra(KEY_MOVIE_ID, movies_response.get(position).getId()); //Toast.makeText(getApplicationContext(),movie_id, Toast.LENGTH_SHORT).show(); startActivity(i); } @Override public void onLongClick(View view, int position) { // on selecting a single album // TrackListActivity will be launched to show tracks inside the album //Intent i = new Intent(getApplicationContext(), Show_Movie_Details_ID.class); // send album id to tracklist activity to get list of songs under that album //String movie_id = ((TextView) view.findViewById(R.id.movie_id)).getText().toString(); //i.putExtra("movie_id", movie_id); //startActivity(i); } })); } @Override public void onFailure(Call<TVResponse> call_2, Throwable t) { // Log error here since request failed //Log.e(TAG, t.toString()); } }); /** PAGE = 3 **/ final RecyclerView recyclerView_3 = (RecyclerView) findViewById(R.id.tvs_recycler_view_page_3); recyclerView_3.setLayoutManager(new LinearLayoutManager(this)); Call<TVResponse> call_3 = apiService.getTopRatedTv_2(getResources().getString(R.string.API_KEY), page_3); call_3.enqueue(new Callback<TVResponse>() { @Override public void onResponse(Call<TVResponse> call_3, final Response<TVResponse> response) { if (!response.isSuccessful()) { //System.out.println("Error"); } if(response.isSuccessful()) { final List<TV> tvs = response.body().getResults(); recyclerView_3.setAdapter(new TVAdapter(tvs, R.layout.nav_tv_get_airing_today_list_item, getApplicationContext())); }else{ int statusCode = response.code(); switch(statusCode){ case 401: //Toast.makeText(getApplicationContext(),"Invalid API key: You must be granted a valid key.", Toast.LENGTH_SHORT).show(); case 404: //Toast.makeText(getApplicationContext(),"The resource you requested could not be found.", Toast.LENGTH_SHORT).show(); } } recyclerView_3.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView_3, new RecyclerTouchListener.ClickListener() { @Override public void onClick(View view, int position) { // on selecting a single album // TrackListActivity will be launched to show tracks inside the album Intent i = new Intent(getApplicationContext(), Show_Movie_Details_ID.class); String movie_id = ((TextView) view.findViewById(R.id.movie_id)).getText().toString(); i.putExtra("movie_id", movie_id); //i.putExtra(KEY_MOVIE_ID, movies_response.get(position).getId()); //Toast.makeText(getApplicationContext(),movie_id, Toast.LENGTH_SHORT).show(); startActivity(i); } @Override public void onLongClick(View view, int position) { // on selecting a single album // TrackListActivity will be launched to show tracks inside the album //Intent i = new Intent(getApplicationContext(), Show_Movie_Details_ID.class); // send album id to tracklist activity to get list of songs under that album //String movie_id = ((TextView) view.findViewById(R.id.movie_id)).getText().toString(); //i.putExtra("movie_id", movie_id); //startActivity(i); } })); } @Override public void onFailure(Call<TVResponse> call_3, Throwable t) { // Log error here since request failed //Log.e(TAG, t.toString()); } }); } /** SEARCH **/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); MenuItem search = menu.findItem(R.id.search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(search); search(searchView); return true; } /** SEARCH **/ private void search(SearchView searchView) { searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { //Toast.makeText(Popular_Movie.this, "Search is Selected", Toast.LENGTH_SHORT).show(); Intent i = new Intent(Top_Rated_TV.this,SearchActivity.class); String api_key_search = query.toString(); i.putExtra("api_key_search", api_key_search); /**switch_key_activity for SearchActivity **/ String switch_key_activity = "Top_Rated_TV"; i.putExtra("switch_key_activity", switch_key_activity); //Toast.makeText(MainActivity.this, api_key_search, Toast.LENGTH_SHORT).show(); //String api_key_search = ((TextView) menu.findItem(R.id.search)).getText().toString(); //i.putExtra("api_key_search", api_key_search); startActivity(i); return true; } @Override public boolean onQueryTextChange(final String newText) { return false; } }); } /** Για το βέλος<SUF>*/ @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == android.R.id.home) { // finish the activity onBackPressed(); return true; } return super.onOptionsItemSelected(item); } /** 2017 ads @Override public void onPause() { if (mAdView != null) { mAdView.pause(); } super.onPause(); } @Override public void onResume() { super.onResume(); if (mAdView != null) { mAdView.resume(); } } @Override public void onDestroy() { if (mAdView != null) { mAdView.destroy(); } super.onDestroy(); } **/ }
11039_7
package gr.rambou.myicarus; import android.util.Log; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.ClientContext; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.io.Serializable; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.X509TrustManager; public class Icarus implements Serializable { private final String Username, Password; public Map<String, String> Cookies; private String StudentFullName, ID, StudentName, Surname; //private Document Page; private ArrayList<Lesson> Succeed_Lessons, All_Lessons, Exams_Lessons; public Icarus(String username, String password) { this.Username = username; this.Password = password; this.StudentFullName = null; this.Cookies = null; } public boolean login() { try { //ενεργοποιούμε το SSL enableSSLSocket(); //Εκτελέμε ερώτημα GET μέσω της JSoup για να συνδεθούμε Connection.Response res = Jsoup .connect("https://icarus-icsd.aegean.gr/authentication.php") .timeout(10 * 1000) .data("username", Username, "pwd", Password) .method(Connection.Method.POST) .execute(); //Παίρνουμε τα cookies Cookies = res.cookies(); //Αποθηκεύουμε το περιεχόμενο της σελίδας Document Page = res.parse(); //Ελέγχουμε αν συνδεθήκαμε Elements name = Page.select("div#header_login").select("u"); if (name.hasText()) { //Παίρνουμε το ονοματεπώνυμο του φοιτητή StudentFullName = name.html(); //Παίρνουμε τον Αριθμό Μητρώου του φοιτητή Pattern r = Pattern.compile("[0-9-/-]{5,16}"); String line = Page.select("div[id=\"stylized\"]").get(1).select("h2").text().trim(); Matcher m = r.matcher(line); if (m.find()) { ID = m.group(0); } //Παίρνουμε τους βαθμούς του φοιτητή LoadMarks(Page); return true; } } catch (IOException | KeyManagementException | NoSuchAlgorithmException ex) { Log.v("Icarus Class", ex.toString()); } return false; } public boolean SendRequest(String fatherName, Integer cemester, String address, String phone, String send_address, SendType sendtype, String[] papers) { if (papers.length != 11) { return false; } String sendmethod; if (sendtype.equals(SendType.FAX)) { sendmethod = "με τηλεομοιοτυπία (fax) στο τηλέφωνο:"; } else if (sendtype.equals(SendType.COURIER)) { sendmethod = "με courier, με χρέωση παραλήπτη, στη διεύθυνση:"; } else { sendmethod = "από την Γραμματεία του Τμήματος, την επομένη της αίτησης"; } //We create the Data to be Send MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create(); mpEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addTextBody("aitisi_student_id", getID()); mpEntity.addTextBody("aitisi_surname", getSurname()); mpEntity.addTextBody("aitisi_name", getStudentName()); mpEntity.addTextBody("aitisi_father", fatherName); mpEntity.addTextBody("aitisi_semester", cemester.toString()); mpEntity.addTextBody("aitisi_address", address); mpEntity.addTextBody("aitisi_phone", phone); mpEntity.addTextBody("aitisi_send_method", sendmethod); mpEntity.addTextBody("aitisi_send_address", send_address); mpEntity.addTextBody("prints_no[]", papers[0]); mpEntity.addTextBody("prints_no[]", papers[1]); mpEntity.addTextBody("prints_no[]", papers[2]); mpEntity.addTextBody("prints_no[]", papers[3]); mpEntity.addTextBody("prints_no[]", papers[4]); mpEntity.addTextBody("prints_no[]", papers[5]); mpEntity.addTextBody("prints_no[]", papers[6]); mpEntity.addTextBody("prints_no[]", papers[7]); mpEntity.addTextBody("prints_no[]", papers[8]); mpEntity.addTextBody("prints_no[]", papers[9]); mpEntity.addTextBody("aitisi_allo", papers[10]); mpEntity.addTextBody("send", ""); HttpEntity entity = mpEntity.build(); //We send the request HttpPost post = new HttpPost("https://icarus-icsd.aegean.gr/student_aitisi.php"); post.setEntity(entity); HttpClient client = HttpClientBuilder.create().build(); //Gets new/old cookies and set them in store and store to CTX CookieStore Store = new BasicCookieStore(); BasicClientCookie cookie = new BasicClientCookie("PHPSESSID", Cookies.get("PHPSESSID")); cookie.setPath("//"); cookie.setDomain("icarus-icsd.aegean.gr"); Store.addCookie(cookie); HttpContext CTX = new BasicHttpContext(); CTX.setAttribute(ClientContext.COOKIE_STORE, Store); HttpResponse response = null; try { response = client.execute(post, CTX); } catch (IOException ex) { Log.v(Icarus.class.getName().toString(), ex.toString()); } //Check if user credentials are ok if (response == null) { return false; } int responseCode = response.getStatusLine().getStatusCode(); if (responseCode != 200) { return false; } try { String html = EntityUtils.toString(response.getEntity(), "ISO-8859-7"); Document res = Jsoup.parse(html); if (res.getElementsByClass("success").isEmpty()) { return false; } } catch (IOException | org.apache.http.ParseException ex) { return false; } return true; } public void LoadMarks(Document response) { All_Lessons = new ArrayList<>(); Succeed_Lessons = new ArrayList<>(); Exams_Lessons = new ArrayList<>(); if (response == null) { try { //We send the request response = Jsoup .connect("https://icarus-icsd.aegean.gr/student_main.php") .cookies(Cookies) .get(); } catch (IOException ex) { Log.v(Icarus.class.getName().toString(), ex.toString()); return; } } //Start Catching Lessons Elements sGrades = response.getElementById("succeeded_grades").select("tr"); Elements aGrades = response.getElementById("analytic_grades").select("tr"); Elements eGrades = response.getElementById("exetastiki_grades").select("tr"); for (Element a : sGrades) { if (!a.select("td").isEmpty()) { Succeed_Lessons.add(getLesson(a)); } } for (Element a : eGrades) { if (!a.select("td").isEmpty()) { Exams_Lessons.add(getLesson(a)); if (a.select("td").get(6).text().trim().compareTo("") != 0) All_Lessons.add(getLesson(a)); } } for (Element a : aGrades) { if (!a.select("td").isEmpty()) { All_Lessons.add(getLesson(a)); } } } private Lesson getLesson(Element a) { DateFormat formatter = new SimpleDateFormat("dd-MM-yy"); String ID = a.select("td").get(1).text(); String Title = a.select("td").get(2).text(); Double Mark = 0.0; try { Mark = Double.valueOf(a.select("td").get(3).text()); } catch (Exception ex) { } String Cemester = a.select("td").get(4).text(); Date Statement = null, Exam = null; try { Statement = formatter.parse(a.select("td").get(5).text().trim()); Exam = formatter.parse(a.select("td").get(6).text().trim()); } catch (ParseException ex) { } Lesson.LessonStatus Status; switch (a.select("td").get(7).text().trim()) { case "Επιτυχία": Status = Lesson.LessonStatus.PASSED; break; case "Αποτυχία": Status = Lesson.LessonStatus.FAILED; break; case "Ακύρωση": Status = Lesson.LessonStatus.CANCELLED; break; default: Status = Lesson.LessonStatus.NOT_GIVEN; break; } return new Lesson(ID, Title, Mark, Cemester, Statement, Exam, Status); } public ArrayList<Lesson> getSucceed_Lessons() { return Succeed_Lessons; } public ArrayList<Lesson> getAll_Lessons() { return All_Lessons; } public Object[] getAll_Lessons_array() { return All_Lessons.toArray(); } public ArrayList<Lesson> getExams_Lessons() { return Exams_Lessons; } public String getStudentFullName() { return StudentFullName; } public String getID() { return ID; } public String getStudentName() { return StudentFullName.split(" ")[0]; } public String getSurname() { return StudentFullName.split(" ")[1]; } private void enableSSLSocket() throws KeyManagementException, NoSuchAlgorithmException { //HttpsURLConnection.setDefaultHostnameVerifier((String hostname, SSLSession session) -> true); SSLContext context; context = SSLContext.getInstance("TLS"); context.init(null, new X509TrustManager[]{new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }}, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory()); } public enum SendType { OFFICE, COURIER, FAX } public enum PaperType { bebewsh_spoudwn, analutikh_ba8mologia, analutikh_ba8mologia_ptuxio_me_ba8mo, analutikh_ba8mologia_ptuxio_xwris_ba8mo, stratologia, diagrafh, antigrafo_ptuxiou, plhrw_proupo8eseis_apokthseis_ptuxiou, praktikh_askhsh, stegastiko_epidoma, allo } }
AegeanHawks/MobileIcarus
app/src/main/java/gr/rambou/myicarus/Icarus.java
3,246
//Παίρνουμε τον Αριθμό Μητρώου του φοιτητή
line_comment
el
package gr.rambou.myicarus; import android.util.Log; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.ClientContext; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.io.Serializable; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.X509TrustManager; public class Icarus implements Serializable { private final String Username, Password; public Map<String, String> Cookies; private String StudentFullName, ID, StudentName, Surname; //private Document Page; private ArrayList<Lesson> Succeed_Lessons, All_Lessons, Exams_Lessons; public Icarus(String username, String password) { this.Username = username; this.Password = password; this.StudentFullName = null; this.Cookies = null; } public boolean login() { try { //ενεργοποιούμε το SSL enableSSLSocket(); //Εκτελέμε ερώτημα GET μέσω της JSoup για να συνδεθούμε Connection.Response res = Jsoup .connect("https://icarus-icsd.aegean.gr/authentication.php") .timeout(10 * 1000) .data("username", Username, "pwd", Password) .method(Connection.Method.POST) .execute(); //Παίρνουμε τα cookies Cookies = res.cookies(); //Αποθηκεύουμε το περιεχόμενο της σελίδας Document Page = res.parse(); //Ελέγχουμε αν συνδεθήκαμε Elements name = Page.select("div#header_login").select("u"); if (name.hasText()) { //Παίρνουμε το ονοματεπώνυμο του φοιτητή StudentFullName = name.html(); //Παίρνουμε τον<SUF> Pattern r = Pattern.compile("[0-9-/-]{5,16}"); String line = Page.select("div[id=\"stylized\"]").get(1).select("h2").text().trim(); Matcher m = r.matcher(line); if (m.find()) { ID = m.group(0); } //Παίρνουμε τους βαθμούς του φοιτητή LoadMarks(Page); return true; } } catch (IOException | KeyManagementException | NoSuchAlgorithmException ex) { Log.v("Icarus Class", ex.toString()); } return false; } public boolean SendRequest(String fatherName, Integer cemester, String address, String phone, String send_address, SendType sendtype, String[] papers) { if (papers.length != 11) { return false; } String sendmethod; if (sendtype.equals(SendType.FAX)) { sendmethod = "με τηλεομοιοτυπία (fax) στο τηλέφωνο:"; } else if (sendtype.equals(SendType.COURIER)) { sendmethod = "με courier, με χρέωση παραλήπτη, στη διεύθυνση:"; } else { sendmethod = "από την Γραμματεία του Τμήματος, την επομένη της αίτησης"; } //We create the Data to be Send MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create(); mpEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addTextBody("aitisi_student_id", getID()); mpEntity.addTextBody("aitisi_surname", getSurname()); mpEntity.addTextBody("aitisi_name", getStudentName()); mpEntity.addTextBody("aitisi_father", fatherName); mpEntity.addTextBody("aitisi_semester", cemester.toString()); mpEntity.addTextBody("aitisi_address", address); mpEntity.addTextBody("aitisi_phone", phone); mpEntity.addTextBody("aitisi_send_method", sendmethod); mpEntity.addTextBody("aitisi_send_address", send_address); mpEntity.addTextBody("prints_no[]", papers[0]); mpEntity.addTextBody("prints_no[]", papers[1]); mpEntity.addTextBody("prints_no[]", papers[2]); mpEntity.addTextBody("prints_no[]", papers[3]); mpEntity.addTextBody("prints_no[]", papers[4]); mpEntity.addTextBody("prints_no[]", papers[5]); mpEntity.addTextBody("prints_no[]", papers[6]); mpEntity.addTextBody("prints_no[]", papers[7]); mpEntity.addTextBody("prints_no[]", papers[8]); mpEntity.addTextBody("prints_no[]", papers[9]); mpEntity.addTextBody("aitisi_allo", papers[10]); mpEntity.addTextBody("send", ""); HttpEntity entity = mpEntity.build(); //We send the request HttpPost post = new HttpPost("https://icarus-icsd.aegean.gr/student_aitisi.php"); post.setEntity(entity); HttpClient client = HttpClientBuilder.create().build(); //Gets new/old cookies and set them in store and store to CTX CookieStore Store = new BasicCookieStore(); BasicClientCookie cookie = new BasicClientCookie("PHPSESSID", Cookies.get("PHPSESSID")); cookie.setPath("//"); cookie.setDomain("icarus-icsd.aegean.gr"); Store.addCookie(cookie); HttpContext CTX = new BasicHttpContext(); CTX.setAttribute(ClientContext.COOKIE_STORE, Store); HttpResponse response = null; try { response = client.execute(post, CTX); } catch (IOException ex) { Log.v(Icarus.class.getName().toString(), ex.toString()); } //Check if user credentials are ok if (response == null) { return false; } int responseCode = response.getStatusLine().getStatusCode(); if (responseCode != 200) { return false; } try { String html = EntityUtils.toString(response.getEntity(), "ISO-8859-7"); Document res = Jsoup.parse(html); if (res.getElementsByClass("success").isEmpty()) { return false; } } catch (IOException | org.apache.http.ParseException ex) { return false; } return true; } public void LoadMarks(Document response) { All_Lessons = new ArrayList<>(); Succeed_Lessons = new ArrayList<>(); Exams_Lessons = new ArrayList<>(); if (response == null) { try { //We send the request response = Jsoup .connect("https://icarus-icsd.aegean.gr/student_main.php") .cookies(Cookies) .get(); } catch (IOException ex) { Log.v(Icarus.class.getName().toString(), ex.toString()); return; } } //Start Catching Lessons Elements sGrades = response.getElementById("succeeded_grades").select("tr"); Elements aGrades = response.getElementById("analytic_grades").select("tr"); Elements eGrades = response.getElementById("exetastiki_grades").select("tr"); for (Element a : sGrades) { if (!a.select("td").isEmpty()) { Succeed_Lessons.add(getLesson(a)); } } for (Element a : eGrades) { if (!a.select("td").isEmpty()) { Exams_Lessons.add(getLesson(a)); if (a.select("td").get(6).text().trim().compareTo("") != 0) All_Lessons.add(getLesson(a)); } } for (Element a : aGrades) { if (!a.select("td").isEmpty()) { All_Lessons.add(getLesson(a)); } } } private Lesson getLesson(Element a) { DateFormat formatter = new SimpleDateFormat("dd-MM-yy"); String ID = a.select("td").get(1).text(); String Title = a.select("td").get(2).text(); Double Mark = 0.0; try { Mark = Double.valueOf(a.select("td").get(3).text()); } catch (Exception ex) { } String Cemester = a.select("td").get(4).text(); Date Statement = null, Exam = null; try { Statement = formatter.parse(a.select("td").get(5).text().trim()); Exam = formatter.parse(a.select("td").get(6).text().trim()); } catch (ParseException ex) { } Lesson.LessonStatus Status; switch (a.select("td").get(7).text().trim()) { case "Επιτυχία": Status = Lesson.LessonStatus.PASSED; break; case "Αποτυχία": Status = Lesson.LessonStatus.FAILED; break; case "Ακύρωση": Status = Lesson.LessonStatus.CANCELLED; break; default: Status = Lesson.LessonStatus.NOT_GIVEN; break; } return new Lesson(ID, Title, Mark, Cemester, Statement, Exam, Status); } public ArrayList<Lesson> getSucceed_Lessons() { return Succeed_Lessons; } public ArrayList<Lesson> getAll_Lessons() { return All_Lessons; } public Object[] getAll_Lessons_array() { return All_Lessons.toArray(); } public ArrayList<Lesson> getExams_Lessons() { return Exams_Lessons; } public String getStudentFullName() { return StudentFullName; } public String getID() { return ID; } public String getStudentName() { return StudentFullName.split(" ")[0]; } public String getSurname() { return StudentFullName.split(" ")[1]; } private void enableSSLSocket() throws KeyManagementException, NoSuchAlgorithmException { //HttpsURLConnection.setDefaultHostnameVerifier((String hostname, SSLSession session) -> true); SSLContext context; context = SSLContext.getInstance("TLS"); context.init(null, new X509TrustManager[]{new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }}, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory()); } public enum SendType { OFFICE, COURIER, FAX } public enum PaperType { bebewsh_spoudwn, analutikh_ba8mologia, analutikh_ba8mologia_ptuxio_me_ba8mo, analutikh_ba8mologia_ptuxio_xwris_ba8mo, stratologia, diagrafh, antigrafo_ptuxiou, plhrw_proupo8eseis_apokthseis_ptuxiou, praktikh_askhsh, stegastiko_epidoma, allo } }
32051_2
package com.kospeac.smartgreecealert; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.CountDownTimer; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.format.DateFormat; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Locale; public class MainActivity extends AppCompatActivity implements View.OnClickListener { static Activity mainActivity; UsbService mUsbService = new UsbService(); FirebaseService mFirebaseService; String type; Button sosBtn; Button fireBtn; Button abortBtn; public TextView mainTitle; public TextView sosTitle; CountDownTimer countDownTimer; CountDownTimer countDownSOS; boolean countDownTimerIsRunning = false; boolean sosStatus = false; private FallDetectionHandler falldetection; private SeismicDetectionHandler seismicdetection; private final static int REQUESTCODE = 325; LocationManager mLocationManager; Uri notification; Ringtone r; private LocationListener locationService; private Boolean prevStatus; Double longitude, latitude; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mainActivity = this; mFirebaseService = FirebaseService.getInstance(); mFirebaseService.getFCMToken(); // generate FCM token - Firebase Messaging mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationService = new LocationService(); sosBtn = findViewById(R.id.btn_sos); fireBtn = findViewById(R.id.btn_fire); abortBtn = findViewById(R.id.btn_abort); mainTitle = findViewById(R.id.main_title); sosTitle = findViewById(R.id.sos_text); sosBtn.setOnClickListener(this); fireBtn.setOnClickListener(this); abortBtn.setOnClickListener(this); checkPermissions(); try { notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); r = RingtoneManager.getRingtone(getApplicationContext(), notification); } catch (Exception e) { e.printStackTrace(); } this.registerReceiver(mUsbService,new IntentFilter("android.hardware.usb.action.USB_STATE")); mUsbService.setOnUsbServiceStatusListener(new OnUsbServiseStatusListener() { @Override public void onStatusChanged(boolean newStatus) { if(newStatus){ if(prevStatus == null || prevStatus != newStatus ) { prevStatus = newStatus; type = "earthquakeEventDetected"; if (falldetection != null && FallDetectionHandler.getListenerStatus()) { falldetection.unregisterListener(); } mainTitle.setText(R.string.main_title2); setupEarthquakeDetection(); // EarthquakeDetection } }else { if(prevStatus == null || prevStatus != newStatus ) { prevStatus = newStatus; type = "fallDetectionEvent"; if (seismicdetection != null && SeismicDetectionHandler.getListenerStatus()) { System.out.println(seismicdetection); seismicdetection.unregisterListener(); } mainTitle.setText(R.string.main_title1); setupFallDetection(); // FallDetection } } } }); } @Override protected void onPause() { super.onPause(); } @Override public void onDestroy() { // Κανουμε unregister τον broadcaster οταν φευγουμε απο το activity super.onDestroy(); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.btn_sos: // SOS sosStatus = true; sosTitle.setText(R.string.sos_title); countDownSOS = new CountDownTimer(20000, 1000) { public void onTick(long millisUntilFinished) { } public void onFinish() { sosTitle.setText(""); sosStatus = false; } }.start(); handleEvent("SOS"); break; case R.id.btn_fire: // FIRE button sosTitle.setText(R.string.fire_title); countDownSOS = new CountDownTimer(20000, 1000) { public void onTick(long millisUntilFinished) { } public void onFinish() { sosTitle.setText(""); sosStatus = false; } }.start(); handleEvent("FIRE"); break; case R.id.btn_abort: // κουμπι Abort if(type == "fallDetectionEvent" && countDownTimerIsRunning) { cancelTimer(); Toast.makeText(this, "Aborted", Toast.LENGTH_LONG).show(); mainTitle.setText(R.string.main_title1); falldetection.registerListener(); } else if(sosStatus){ // αμα το sosStatus ειναι ενεργο δηλαδη εχει πατηθει το SOS button και δεν εχουν περασει τα 5 λεπτα που εχει ο χρηστης για να κανει ακυρωση cancelSOSTimer(); handleEvent("AbortEvent"); } break; } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.topbar, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_statistics: Intent goToStatistics = new Intent(this,Statistics.class); startActivity(goToStatistics); // Νεο acitvity Statistics return true; case R.id.menu_contacts: Intent goToContacts = new Intent(this,ContactsActivity.class); startActivity(goToContacts); // Νεο acitvity Contacts return true; default: return super.onOptionsItemSelected(item); } } private void checkPermissions() { List<String> PERMISSIONS = new ArrayList<>(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){ PERMISSIONS.add(Manifest.permission.ACCESS_FINE_LOCATION); }else{ System.out.println("GPS ENABLED"); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationService); } if (ActivityCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) { PERMISSIONS.add(Manifest.permission.SEND_SMS); } if(!PERMISSIONS.isEmpty()){ String[] array = PERMISSIONS.toArray(new String[PERMISSIONS.size()]); ActivityCompat.requestPermissions(this, array, REQUESTCODE); } } //get location from the GPS service provider. Needs permission. protected void getLocation() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); List<String> providers = mLocationManager.getProviders(true); Location location = null; for(String provider : providers){ Location l = mLocationManager.getLastKnownLocation(provider); location = l; if(location != null){ latitude = location.getLatitude(); longitude = location.getLongitude(); break; } } if (location == null) { latitude = -1.0; longitude = -1.0; } } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); for (String permission : permissions) { if (ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED) { if (permission.equals(Manifest.permission.ACCESS_FINE_LOCATION)) { mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationService); getLocation(); } } } } /* setupFallDetection * Create object and listener (from device accelerometer) when we are in fallDetection state. * When status is true we have a user fall and we deactivate/unregister the listener * and we enable a CountDownTimer of 30 secs in order to abort event. * */ private void setupFallDetection() { falldetection = new FallDetectionHandler(this); falldetection.setFallDetectionListener(new FallDetectionListener() { @Override public void onStatusChanged(boolean fallDetectionStatus) { if(fallDetectionStatus) { falldetection.unregisterListener(); countDownTimerIsRunning = true; countDownTimer = new CountDownTimer(30000, 1000) { public void onTick(long millisUntilFinished) { // καθε δευτερολεπτο αλλαζουμε το UI για να εμφανιζεται η αντιστροφη μετρηση r.play(); mainTitle.setText(Long.toString(millisUntilFinished / 1000)); } public void onFinish() { // οταν τελειωσει ο timer ξανακανουμε register τον listener και γινεται διαχεριση του event countDownTimerIsRunning = false; r.stop(); mainTitle.setText(R.string.main_title1); falldetection.registerListener(); handleEvent("fallDetectionEvent"); } }.start(); } } }); } private void cancelTimer(){ //ακυρωση timer για το fall detection countDownTimer.cancel(); r.stop(); } private void cancelSOSTimer(){ //ακυρωση timer για το SOS button countDownSOS.onFinish(); countDownSOS.cancel(); } // setupEarthquakeDetection private void setupEarthquakeDetection() { seismicdetection = new SeismicDetectionHandler(this); seismicdetection.setSeismicDetectionListener(new SeismicDetectionListener() { @Override public void onStatusChanged(boolean seismicDetectionStatus) { if(seismicDetectionStatus) { seismicdetection.unregisterListener(); // Κανουμε unregistrer τον listener μεχρι να γινει η καταγραφη στην βαση και να δουμε αν ειναι οντως σεισμος handleEvent("earthquakeEventDetected"); //καταγραφουμε στην βαση με type earthquakeDetection ωστε να κανουμε αναζητηση και σε αλλους χρηστες με το ιδιο type } } }); } // handleEvent private void handleEvent( String type){ String eventType = type; final double latd,lond; //check current location from LocationChange, if that doesn't work get manually the current location from the GPS service provider if(LocationService.latitude !=0 & LocationService.longitude!=0) { latd = LocationService.latitude; lond = LocationService.latitude; } else { getLocation(); latd = latitude; lond = longitude; } String lat = Double.toString(latd); String lon = Double.toString(lond); final long timestamp = System.currentTimeMillis(); Calendar cal = Calendar.getInstance(Locale.ENGLISH); cal.setTimeInMillis(timestamp); String date = DateFormat.format("dd-MM-yyyy HH:mm", cal).toString(); mFirebaseService.insertEvent(new EventModel(eventType, latd,lond,timestamp,date)); // Εγγραφη στην Firebase Database if((eventType != "earthquakeEventDetected") && (eventType != "earthquakeTakingPlace")) { //Στελνουμε μηνυμα σε καθε περιπτωση εκτος απο την περιπτωση της ανιχνευσης σεισμου Notification notification = new Notification(mainActivity); notification.sendNotification(type, lat, lon, date); // αποστολη SMS } if(eventType == "earthquakeEventDetected"){ // Στην περιπτωση που εχουμε ανιχνευση σεισμου, γινεται ελεγχος της βασης για να βρεθει και αλλος χρηστης σε κοντινη αποσταση που ειχε ιδιο event mFirebaseService.getEvents(); mFirebaseService.setFirebaseListener(new FirebaseListener() { @Override public void onStatusChanged(String newStatus) { // οταν η getEvents() ολοκληρωθει και εχει φερει ολα τα events τοτε το newStatus θα ειναι allEvents. if(newStatus.equals("allEvents")){ List<EventModel> events = EventModel.filterEarthquakeDetectionEvents(mFirebaseService.eventsList); //φιλτρουμε απο ολα τα events μονο τα earthquakedetection boolean seismicStatus = seismicdetection.seismicStatus(events, timestamp,latd,lond); if(seismicStatus){ handleEvent("earthquakeTakingPlace"); // εγγραφη του event στην βαση new AlertDialog.Builder(MainActivity.mainActivity) // ειδοποιση χρηστη και και ενεργοποιηση του listener otan πατησει το οκ .setTitle("Earthquake!") .setMessage("An Earthquake is taking place, please seek help!!") .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if( FallDetectionHandler.getListenerStatus() == null || FallDetectionHandler.getListenerStatus() ==false ){ seismicdetection.registerListener(); } } }) .setIcon(android.R.drawable.ic_dialog_alert) .show(); }else { //αμα δεν υπαρχει αλλος κοντινος χρηστης τοτε δεν γινεται event earthquake if(FallDetectionHandler.getListenerStatus() == null || FallDetectionHandler.getListenerStatus() ==false ){ seismicdetection.registerListener(); } } } } }); } } }
Afrodith/SmartAlertGreece
app/src/main/java/com/kospeac/smartgreecealert/MainActivity.java
3,938
// αμα το sosStatus ειναι ενεργο δηλαδη εχει πατηθει το SOS button και δεν εχουν περασει τα 5 λεπτα που εχει ο χρηστης για να κανει ακυρωση
line_comment
el
package com.kospeac.smartgreecealert; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.CountDownTimer; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.format.DateFormat; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Locale; public class MainActivity extends AppCompatActivity implements View.OnClickListener { static Activity mainActivity; UsbService mUsbService = new UsbService(); FirebaseService mFirebaseService; String type; Button sosBtn; Button fireBtn; Button abortBtn; public TextView mainTitle; public TextView sosTitle; CountDownTimer countDownTimer; CountDownTimer countDownSOS; boolean countDownTimerIsRunning = false; boolean sosStatus = false; private FallDetectionHandler falldetection; private SeismicDetectionHandler seismicdetection; private final static int REQUESTCODE = 325; LocationManager mLocationManager; Uri notification; Ringtone r; private LocationListener locationService; private Boolean prevStatus; Double longitude, latitude; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mainActivity = this; mFirebaseService = FirebaseService.getInstance(); mFirebaseService.getFCMToken(); // generate FCM token - Firebase Messaging mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationService = new LocationService(); sosBtn = findViewById(R.id.btn_sos); fireBtn = findViewById(R.id.btn_fire); abortBtn = findViewById(R.id.btn_abort); mainTitle = findViewById(R.id.main_title); sosTitle = findViewById(R.id.sos_text); sosBtn.setOnClickListener(this); fireBtn.setOnClickListener(this); abortBtn.setOnClickListener(this); checkPermissions(); try { notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); r = RingtoneManager.getRingtone(getApplicationContext(), notification); } catch (Exception e) { e.printStackTrace(); } this.registerReceiver(mUsbService,new IntentFilter("android.hardware.usb.action.USB_STATE")); mUsbService.setOnUsbServiceStatusListener(new OnUsbServiseStatusListener() { @Override public void onStatusChanged(boolean newStatus) { if(newStatus){ if(prevStatus == null || prevStatus != newStatus ) { prevStatus = newStatus; type = "earthquakeEventDetected"; if (falldetection != null && FallDetectionHandler.getListenerStatus()) { falldetection.unregisterListener(); } mainTitle.setText(R.string.main_title2); setupEarthquakeDetection(); // EarthquakeDetection } }else { if(prevStatus == null || prevStatus != newStatus ) { prevStatus = newStatus; type = "fallDetectionEvent"; if (seismicdetection != null && SeismicDetectionHandler.getListenerStatus()) { System.out.println(seismicdetection); seismicdetection.unregisterListener(); } mainTitle.setText(R.string.main_title1); setupFallDetection(); // FallDetection } } } }); } @Override protected void onPause() { super.onPause(); } @Override public void onDestroy() { // Κανουμε unregister τον broadcaster οταν φευγουμε απο το activity super.onDestroy(); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.btn_sos: // SOS sosStatus = true; sosTitle.setText(R.string.sos_title); countDownSOS = new CountDownTimer(20000, 1000) { public void onTick(long millisUntilFinished) { } public void onFinish() { sosTitle.setText(""); sosStatus = false; } }.start(); handleEvent("SOS"); break; case R.id.btn_fire: // FIRE button sosTitle.setText(R.string.fire_title); countDownSOS = new CountDownTimer(20000, 1000) { public void onTick(long millisUntilFinished) { } public void onFinish() { sosTitle.setText(""); sosStatus = false; } }.start(); handleEvent("FIRE"); break; case R.id.btn_abort: // κουμπι Abort if(type == "fallDetectionEvent" && countDownTimerIsRunning) { cancelTimer(); Toast.makeText(this, "Aborted", Toast.LENGTH_LONG).show(); mainTitle.setText(R.string.main_title1); falldetection.registerListener(); } else if(sosStatus){ // αμα το<SUF> cancelSOSTimer(); handleEvent("AbortEvent"); } break; } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.topbar, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_statistics: Intent goToStatistics = new Intent(this,Statistics.class); startActivity(goToStatistics); // Νεο acitvity Statistics return true; case R.id.menu_contacts: Intent goToContacts = new Intent(this,ContactsActivity.class); startActivity(goToContacts); // Νεο acitvity Contacts return true; default: return super.onOptionsItemSelected(item); } } private void checkPermissions() { List<String> PERMISSIONS = new ArrayList<>(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){ PERMISSIONS.add(Manifest.permission.ACCESS_FINE_LOCATION); }else{ System.out.println("GPS ENABLED"); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationService); } if (ActivityCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) { PERMISSIONS.add(Manifest.permission.SEND_SMS); } if(!PERMISSIONS.isEmpty()){ String[] array = PERMISSIONS.toArray(new String[PERMISSIONS.size()]); ActivityCompat.requestPermissions(this, array, REQUESTCODE); } } //get location from the GPS service provider. Needs permission. protected void getLocation() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); List<String> providers = mLocationManager.getProviders(true); Location location = null; for(String provider : providers){ Location l = mLocationManager.getLastKnownLocation(provider); location = l; if(location != null){ latitude = location.getLatitude(); longitude = location.getLongitude(); break; } } if (location == null) { latitude = -1.0; longitude = -1.0; } } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); for (String permission : permissions) { if (ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED) { if (permission.equals(Manifest.permission.ACCESS_FINE_LOCATION)) { mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationService); getLocation(); } } } } /* setupFallDetection * Create object and listener (from device accelerometer) when we are in fallDetection state. * When status is true we have a user fall and we deactivate/unregister the listener * and we enable a CountDownTimer of 30 secs in order to abort event. * */ private void setupFallDetection() { falldetection = new FallDetectionHandler(this); falldetection.setFallDetectionListener(new FallDetectionListener() { @Override public void onStatusChanged(boolean fallDetectionStatus) { if(fallDetectionStatus) { falldetection.unregisterListener(); countDownTimerIsRunning = true; countDownTimer = new CountDownTimer(30000, 1000) { public void onTick(long millisUntilFinished) { // καθε δευτερολεπτο αλλαζουμε το UI για να εμφανιζεται η αντιστροφη μετρηση r.play(); mainTitle.setText(Long.toString(millisUntilFinished / 1000)); } public void onFinish() { // οταν τελειωσει ο timer ξανακανουμε register τον listener και γινεται διαχεριση του event countDownTimerIsRunning = false; r.stop(); mainTitle.setText(R.string.main_title1); falldetection.registerListener(); handleEvent("fallDetectionEvent"); } }.start(); } } }); } private void cancelTimer(){ //ακυρωση timer για το fall detection countDownTimer.cancel(); r.stop(); } private void cancelSOSTimer(){ //ακυρωση timer για το SOS button countDownSOS.onFinish(); countDownSOS.cancel(); } // setupEarthquakeDetection private void setupEarthquakeDetection() { seismicdetection = new SeismicDetectionHandler(this); seismicdetection.setSeismicDetectionListener(new SeismicDetectionListener() { @Override public void onStatusChanged(boolean seismicDetectionStatus) { if(seismicDetectionStatus) { seismicdetection.unregisterListener(); // Κανουμε unregistrer τον listener μεχρι να γινει η καταγραφη στην βαση και να δουμε αν ειναι οντως σεισμος handleEvent("earthquakeEventDetected"); //καταγραφουμε στην βαση με type earthquakeDetection ωστε να κανουμε αναζητηση και σε αλλους χρηστες με το ιδιο type } } }); } // handleEvent private void handleEvent( String type){ String eventType = type; final double latd,lond; //check current location from LocationChange, if that doesn't work get manually the current location from the GPS service provider if(LocationService.latitude !=0 & LocationService.longitude!=0) { latd = LocationService.latitude; lond = LocationService.latitude; } else { getLocation(); latd = latitude; lond = longitude; } String lat = Double.toString(latd); String lon = Double.toString(lond); final long timestamp = System.currentTimeMillis(); Calendar cal = Calendar.getInstance(Locale.ENGLISH); cal.setTimeInMillis(timestamp); String date = DateFormat.format("dd-MM-yyyy HH:mm", cal).toString(); mFirebaseService.insertEvent(new EventModel(eventType, latd,lond,timestamp,date)); // Εγγραφη στην Firebase Database if((eventType != "earthquakeEventDetected") && (eventType != "earthquakeTakingPlace")) { //Στελνουμε μηνυμα σε καθε περιπτωση εκτος απο την περιπτωση της ανιχνευσης σεισμου Notification notification = new Notification(mainActivity); notification.sendNotification(type, lat, lon, date); // αποστολη SMS } if(eventType == "earthquakeEventDetected"){ // Στην περιπτωση που εχουμε ανιχνευση σεισμου, γινεται ελεγχος της βασης για να βρεθει και αλλος χρηστης σε κοντινη αποσταση που ειχε ιδιο event mFirebaseService.getEvents(); mFirebaseService.setFirebaseListener(new FirebaseListener() { @Override public void onStatusChanged(String newStatus) { // οταν η getEvents() ολοκληρωθει και εχει φερει ολα τα events τοτε το newStatus θα ειναι allEvents. if(newStatus.equals("allEvents")){ List<EventModel> events = EventModel.filterEarthquakeDetectionEvents(mFirebaseService.eventsList); //φιλτρουμε απο ολα τα events μονο τα earthquakedetection boolean seismicStatus = seismicdetection.seismicStatus(events, timestamp,latd,lond); if(seismicStatus){ handleEvent("earthquakeTakingPlace"); // εγγραφη του event στην βαση new AlertDialog.Builder(MainActivity.mainActivity) // ειδοποιση χρηστη και και ενεργοποιηση του listener otan πατησει το οκ .setTitle("Earthquake!") .setMessage("An Earthquake is taking place, please seek help!!") .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if( FallDetectionHandler.getListenerStatus() == null || FallDetectionHandler.getListenerStatus() ==false ){ seismicdetection.registerListener(); } } }) .setIcon(android.R.drawable.ic_dialog_alert) .show(); }else { //αμα δεν υπαρχει αλλος κοντινος χρηστης τοτε δεν γινεται event earthquake if(FallDetectionHandler.getListenerStatus() == null || FallDetectionHandler.getListenerStatus() ==false ){ seismicdetection.registerListener(); } } } } }); } } }
2452_3
package gr.aueb; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class LoginFrame extends JFrame implements ActionListener { static String username; JFrame frm = new JFrame("Filmbro"); JLabel welcomeMess = new JLabel("Hello, log in to your account."); Container container = getContentPane(); JLabel userLabel = new JLabel("Username:"); JLabel passwordLabel = new JLabel("Password:"); JTextField userTextField = new JTextField(" e.g. Username"); JPasswordField passwordField = new JPasswordField(); DarkButton loginButton = new DarkButton("LOGIN"); DarkButton backButton = new DarkButton("BACK"); JCheckBox showPassword = new JCheckBox("Show Password"); JLabel picLabel = new JLabel(new ImageIcon("logo.png")); // an theloume na baloyme eikona JMenuBar mb = new JMenuBar(); LoginFrame() { initComponents(); } private void initComponents() { setTitle("Java"); setBounds(10, 10, 600, 600); frm.setJMenuBar(mb); setLocationRelativeTo(null); // center the application window setVisible(true); setLayoutManager(); setLocationAndSize(); addComponentsToContainer(); addActionEvent(); setBackground(20,20,20); setFont(); addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { resizeComponents(); } }); } public void setLayoutManager() { container.setLayout(null); } private void setBackground(int a, int b, int c) { container.setBackground(new Color(a, b, c)); showPassword.setBackground(new Color(a, b, c)); } private void setFont() { welcomeMess.setFont(new Font("Tahoma", 0, 16)); welcomeMess.setForeground(new Color(230, 120, 50)); userLabel.setForeground(new Color(230, 120, 50)); passwordLabel.setForeground(new Color(230, 120, 50)); showPassword.setForeground(new Color(230, 120, 50)); } public void setLocationAndSize() { userLabel.setBounds(50, 150, 100, 30); passwordLabel.setBounds(50, 200, 100, 30); userTextField.setBounds(150, 150, 150, 30); passwordField.setBounds(150, 200, 150, 30); showPassword.setBounds(150, 240, 150, 30); loginButton.setBounds(125, 300, 100, 30); welcomeMess.setBounds(70, 50, 230, 150); picLabel.setBounds(100, 10, 150, 90); backButton.setBounds(20, 490, 80, 30); } public void addComponentsToContainer() { container.add(userLabel); container.add(welcomeMess); container.add(passwordLabel); container.add(userTextField); container.add(passwordField); container.add(showPassword); container.add(loginButton); container.add(picLabel); container.add(backButton); } public void addActionEvent() { loginButton.addActionListener(this); showPassword.addActionListener(this); backButton.addActionListener(this); userTextField.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { userTextField.setText(""); } }); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == backButton) { MenuBar m = new MenuBar(new MenuFrame()); dispose(); } if (e.getSource() == showPassword) { if (showPassword.isSelected()) { passwordField.setEchoChar((char) 0); }else { passwordField.setEchoChar('*'); } } } public void resizeComponents() { int width = this.getWidth(); int centerOffset = width / 4; // Προσαρμόζετε τον παράγοντα ανάλογα με την πόσο πρέπει να μετακινηθούν τα στοιχεία. userLabel.setBounds(centerOffset, 150, 100, 30); passwordLabel.setBounds(centerOffset, 200, 100, 30); userTextField.setBounds(centerOffset + 100, 150, 150, 30); passwordField.setBounds(centerOffset + 100, 200, 150, 30); showPassword.setBounds(centerOffset + 100, 240, 150, 30); loginButton.setBounds(centerOffset +85, 300, 140, 30); // Προσαρμόστε ανάλογα για την ευθυγράμμιση. welcomeMess.setBounds(centerOffset, 50, 230, 150); picLabel.setBounds(centerOffset + 50, 10, 150, 90); backButton.setBounds(20, 490, 80, 30); } }
Aglag257/Java2_AIApp
app/src/unused_code/LoginFrame.java
1,431
// Προσαρμόστε ανάλογα για την ευθυγράμμιση.
line_comment
el
package gr.aueb; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class LoginFrame extends JFrame implements ActionListener { static String username; JFrame frm = new JFrame("Filmbro"); JLabel welcomeMess = new JLabel("Hello, log in to your account."); Container container = getContentPane(); JLabel userLabel = new JLabel("Username:"); JLabel passwordLabel = new JLabel("Password:"); JTextField userTextField = new JTextField(" e.g. Username"); JPasswordField passwordField = new JPasswordField(); DarkButton loginButton = new DarkButton("LOGIN"); DarkButton backButton = new DarkButton("BACK"); JCheckBox showPassword = new JCheckBox("Show Password"); JLabel picLabel = new JLabel(new ImageIcon("logo.png")); // an theloume na baloyme eikona JMenuBar mb = new JMenuBar(); LoginFrame() { initComponents(); } private void initComponents() { setTitle("Java"); setBounds(10, 10, 600, 600); frm.setJMenuBar(mb); setLocationRelativeTo(null); // center the application window setVisible(true); setLayoutManager(); setLocationAndSize(); addComponentsToContainer(); addActionEvent(); setBackground(20,20,20); setFont(); addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { resizeComponents(); } }); } public void setLayoutManager() { container.setLayout(null); } private void setBackground(int a, int b, int c) { container.setBackground(new Color(a, b, c)); showPassword.setBackground(new Color(a, b, c)); } private void setFont() { welcomeMess.setFont(new Font("Tahoma", 0, 16)); welcomeMess.setForeground(new Color(230, 120, 50)); userLabel.setForeground(new Color(230, 120, 50)); passwordLabel.setForeground(new Color(230, 120, 50)); showPassword.setForeground(new Color(230, 120, 50)); } public void setLocationAndSize() { userLabel.setBounds(50, 150, 100, 30); passwordLabel.setBounds(50, 200, 100, 30); userTextField.setBounds(150, 150, 150, 30); passwordField.setBounds(150, 200, 150, 30); showPassword.setBounds(150, 240, 150, 30); loginButton.setBounds(125, 300, 100, 30); welcomeMess.setBounds(70, 50, 230, 150); picLabel.setBounds(100, 10, 150, 90); backButton.setBounds(20, 490, 80, 30); } public void addComponentsToContainer() { container.add(userLabel); container.add(welcomeMess); container.add(passwordLabel); container.add(userTextField); container.add(passwordField); container.add(showPassword); container.add(loginButton); container.add(picLabel); container.add(backButton); } public void addActionEvent() { loginButton.addActionListener(this); showPassword.addActionListener(this); backButton.addActionListener(this); userTextField.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { userTextField.setText(""); } }); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == backButton) { MenuBar m = new MenuBar(new MenuFrame()); dispose(); } if (e.getSource() == showPassword) { if (showPassword.isSelected()) { passwordField.setEchoChar((char) 0); }else { passwordField.setEchoChar('*'); } } } public void resizeComponents() { int width = this.getWidth(); int centerOffset = width / 4; // Προσαρμόζετε τον παράγοντα ανάλογα με την πόσο πρέπει να μετακινηθούν τα στοιχεία. userLabel.setBounds(centerOffset, 150, 100, 30); passwordLabel.setBounds(centerOffset, 200, 100, 30); userTextField.setBounds(centerOffset + 100, 150, 150, 30); passwordField.setBounds(centerOffset + 100, 200, 150, 30); showPassword.setBounds(centerOffset + 100, 240, 150, 30); loginButton.setBounds(centerOffset +85, 300, 140, 30); // Προσαρμόστε ανάλογα<SUF> welcomeMess.setBounds(centerOffset, 50, 230, 150); picLabel.setBounds(centerOffset + 50, 10, 150, 90); backButton.setBounds(20, 490, 80, 30); } }
10206_24
package com.example.hangmangame; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.stage.Stage; import java.io.*; import java.util.*; import static com.example.hangmangame.LoadDictionary.*; public class Controller { public static boolean Playing; @FXML private Label AvailableWordsLabel; @FXML private Label Dictionary; @FXML private ImageView ImageView; @FXML private Label Possible_Letters_Label; @FXML private HBox word_hbox; @FXML private Label TotalPoints; @FXML private Label Success_Rate; @FXML private void open_up_add_dictionary(ActionEvent event) { try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("add_dictionary.fxml")); Scene scene = new Scene(fxmlLoader.load(), 630, 400); Stage stage = new Stage(); stage.setTitle("Dictionary Settings"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening add_dictionary Scene"); } } @FXML private void open_up_load_dictionary(ActionEvent event) { try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("load_dictionary.fxml")); Scene scene = new Scene(fxmlLoader.load(), 630, 400); Stage stage = new Stage(); stage.setTitle("Load Dictionary"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening Load Dictionary Scene"); } } @FXML private void solution_dialog(){ Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Solution"); alert.setHeaderText(null); if(Playing) alert.setContentText("Solution is " + game_word); else alert.setContentText("You are not playing !"); alert.showAndWait(); } public List<Button> word_buttons = new ArrayList<>(); public static String game_word; public int Number_of_Letters_left; public int lives; public List<Button> Invisible_Key_Buttons = new ArrayList<>(); public boolean initialise = false; @FXML public void start() { if(!initialise){ initialise_rounds(); } lives = 6; SetImage(lives); game_word = get_random_word(); Number_of_Letters_left = game_word.length(); Playing = true; Successful_Attempts = 0.0F; Total_Attempts = 0.0F; Success_Rate.setText("0%"); Available_Words(); if (game_word.equals("empty")) { Dictionary.setText("Load Dictionary!"); return; } //Reset Possible_letters.clear(); //Set invisible keys to visible if (!Invisible_Key_Buttons.isEmpty()) { for (Button invisible_key_button : Invisible_Key_Buttons) { invisible_key_button.setVisible(true); } } Dictionary.setText(title); System.out.println(title); //create a list of buttons word_hbox.getChildren().removeAll(word_buttons); word_buttons.clear(); for (int i = 0; i < game_word.length(); i++) { word_buttons.add(new Button("_")); //word_buttons.add(new Button(String.valueOf(game_word.charAt(i)))); word_hbox.getChildren().add(word_buttons.get(i)); word_buttons.get(i).setStyle("-fx-font-size: 2em; "); /* when clicked it should display the most common letters in the position of the letter in the Dictionary */ word_buttons.get(i).setOnAction(actionEvent -> { //... do something in here. }); } Same_length_stats(); } public List<String> Possible_letters = new ArrayList<>(); public List<Integer> Quantity_of_Letter = new ArrayList<>(); public Vector<String> same_length_words = new Vector<>(); public List<Element> elements = new ArrayList<Element>(); public void Same_length_stats() { /* Find words with equal length with game_word */ same_length_words.clear(); elements.clear(); for (String word : words) { if (word.length() == game_word.length() && !word.equals(game_word)) { same_length_words.add(word); } } // counter to keep track of how many int[][] CharCounter = new int[game_word.length()][26]; /* set all counters to zero */ // we have 26 counters for every letter of the game word for (int i = 0; i < game_word.length(); i++) { for (int z = 0; z < 26; z++) { CharCounter[i][z] = 0; } } // Now we count for (int i = 0; i < game_word.length(); i++) { for (String word : same_length_words) { int temp = (int) word.charAt(i) - 65; //Capital Letters CharCounter[i][temp]++; } } // add every counter to a List in order to keep track of them when we sort them for (int i = 0; i < game_word.length(); i++) { //i = position for (int z = 0; z < 26; z++) { //z = letter elements.add(new Element(i, z, CharCounter[i][z])); //System.out.println(CharCounter[i][z]); } } Collections.sort(elements); // reverse so we get the big numbers at front Collections.reverse(elements); for (int i = 0; i < game_word.length(); i++) { Possible_letters.add(""); System.out.println("---------LOOP " + String.valueOf(i) + "----------" ); System.out.println(i); for (Element element : elements) { if (element.position == i && element.quantity > 0) { //q>0 because we need P(q)>0 char letter = (char) (element.letter + 65); System.out.println(letter + " quantity :" + String.valueOf(element.quantity)); Possible_letters.set(i , Possible_letters.get(i) + String.valueOf(letter) + " "); } } int java_is_dumb = i; //lamda expressions need final expressions word_buttons.get(i).setOnAction(e -> {Possible_Letters_Label.setText(Possible_letters.get(java_is_dumb));}); System.out.println(Possible_letters.get(i)); } } public void Available_Words() { AvailableWordsLabel.setText(String.valueOf(words.size())); } public float Successful_Attempts; public float Total_Attempts; public void Success_Rate(){ if (Successful_Attempts == 0){ Success_Rate.setText("0%"); return; } else if (Successful_Attempts==Total_Attempts) { Success_Rate.setText("100%"); return; } float Success_rate = 100*Successful_Attempts/Total_Attempts;; String Success_Rate_Text = String.valueOf(Success_rate); String Label = ""; for (int i = 0; i < 4; i++) { Label += String.valueOf(Success_Rate_Text.charAt(i)); } Success_Rate.setText(Label+" %"); } public int Score = 0; public void Update_Score(int position){ int total_same_length_words = same_length_words.size(); int Element_letter = ((int) game_word.charAt(position)) - 65; //we have to convert it to the way we added it 26*i + z //int quantity_of_letter = elements.get(26*position + Element_letter).quantity; int quantity_of_letter = 0; for(Element element:elements){ if(element.letter == Element_letter && element.position==position){ quantity_of_letter = element.quantity; } } float percentage = (float)quantity_of_letter / (float) total_same_length_words; System.out.println("Total words, quantity of letter , percentage"); System.out.println(total_same_length_words); System.out.println(quantity_of_letter); System.out.println(percentage); //System.out.println(Element_letter+65); if(percentage >= 0.6) { Score += 5; } else if(percentage >= 0.4){ Score += 10; } else if(percentage >= 0.25){ Score += 15; } else Score += 30; } @FXML public void Try_this_Letter(Event event) { if (!Playing) { return; //If we ain't playing do nothing } System.out.println(event.getTarget()); Button btn = (Button) event.getSource(); //temp value String button_char = btn.getId(); System.out.println(btn.getId()); //get id btn.setVisible(false); Invisible_Key_Buttons.add(btn); /* ChecK if the character exist in the game word */ boolean success = false; Total_Attempts++; for (int i = 0; i < game_word.length(); i++) { if (button_char.equals(String.valueOf(game_word.charAt(i)))) { //reveal the letters that exist in the words success = true; Number_of_Letters_left--; word_buttons.get(i).setText(button_char); Update_Score(i); //we scored at position i TotalPoints.setText(String.valueOf(Score)); if (Number_of_Letters_left < 1) { System.out.println("Congratulations"); //win = true Update_Rounds(true); win_game(true); } } } if(!success){ lives--; SetImage(lives); //game_over(); if (lives < 1) { //win = false Playing = false; Update_Rounds(false); System.out.println("You lost :("); win_game(false); } } else Successful_Attempts++; Success_Rate(); } public void win_game(boolean win){ Alert alert = new Alert(Alert.AlertType.INFORMATION); if(win) { alert.setTitle("Congratulations"); alert.setHeaderText("You Won !"); alert.setContentText("Ready for the next one ?"); File myObj = new File("./images/win.png"); Image image = new Image(myObj.getAbsolutePath()); alert.setGraphic(new ImageView(image)); } else { alert.setTitle("Tough luck"); alert.setHeaderText("You Lost ..."); alert.setContentText("Want to try again ?"); File myObj = new File("./images/lost.png"); Image image = new Image(myObj.getAbsolutePath()); alert.setGraphic(new ImageView(image)); } ButtonType buttonTypeNextWord = new ButtonType("Next Word", ButtonBar.ButtonData.CANCEL_CLOSE); alert.getButtonTypes().setAll(buttonTypeNextWord); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == buttonTypeNextWord){ start(); } } public void SetImage(int lives) { File myObj = new File("./images/" + String.valueOf(lives) + ".jpg"); Image image = new Image(myObj.getAbsolutePath()); ImageView.setImage(image); } @FXML public void exit_app(){ Platform.exit(); } @FXML public void open_Dictionary_Details(ActionEvent event){ /*Dictionary: Μέσω ενός popup παραθύρου θα παρουσιάζει το ποσοστό των λέξεων του ενεργού λεξικού με 6 γράμματα, 7 έως 9 γράμματα και 10 ή περισσότερα γράμματα */ try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("dictionary_details.fxml")); Scene scene = new Scene(fxmlLoader.load(), 630, 400); Stage stage = new Stage(); stage.setTitle("Dictionary Details"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening Dictionary Details Scene"); } } public static Vector<String> gamewords_5 = new Vector<>(); public static Vector<String> results_5 = new Vector<>(); public static Vector<String> Attempts_per_gameword = new Vector<>(); public void initialise_rounds() { for (int i = 0; i < 5; i++) { gamewords_5.add("---"); results_5.add("---"); Attempts_per_gameword.add("---"); } initialise = true; } public void Update_Rounds(Boolean win) { //gamewords gamewords_5.remove(0); gamewords_5.add(game_word); //results results_5.remove(0); if(win){ results_5.add("Victory"); } else { results_5.add("Defeat"); } //attempts Attempts_per_gameword.remove(0); Attempts_per_gameword.add(String.valueOf((int) Total_Attempts)); } @FXML public void Instructions(){ try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("instructions.fxml")); Scene scene = new Scene(fxmlLoader.load()); Stage stage = new Stage(); stage.setTitle("Instructions"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening Instructions Scene"); } } @FXML public void Rounds(){ /*Rounds: Μέσω ενός popup παραθύρου θα παρουσιάζει για τα 5 τελευταία ολοκληρωμένα παιχνίδια τις παρακάτω πληροφορίες: επιλεγμένη λέξη, πλήθος προσπαθειών και νικητή (παίκτης ή υπολογιστής). */ try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("rounds.fxml")); Scene scene = new Scene(fxmlLoader.load(), 630, 400); Stage stage = new Stage(); stage.setTitle("Rounds Details"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening Rounds Scene"); } } }
Aglogallos/Hangman-Game-JavaFx
Hangman_Game/Hangman-Game/src/main/java/com/example/hangmangame/Controller.java
3,768
/*Rounds: Μέσω ενός popup παραθύρου θα παρουσιάζει για τα 5 τελευταία ολοκληρωμένα παιχνίδια τις παρακάτω πληροφορίες: επιλεγμένη λέξη, πλήθος προσπαθειών και νικητή (παίκτης ή υπολογιστής). */
block_comment
el
package com.example.hangmangame; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.stage.Stage; import java.io.*; import java.util.*; import static com.example.hangmangame.LoadDictionary.*; public class Controller { public static boolean Playing; @FXML private Label AvailableWordsLabel; @FXML private Label Dictionary; @FXML private ImageView ImageView; @FXML private Label Possible_Letters_Label; @FXML private HBox word_hbox; @FXML private Label TotalPoints; @FXML private Label Success_Rate; @FXML private void open_up_add_dictionary(ActionEvent event) { try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("add_dictionary.fxml")); Scene scene = new Scene(fxmlLoader.load(), 630, 400); Stage stage = new Stage(); stage.setTitle("Dictionary Settings"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening add_dictionary Scene"); } } @FXML private void open_up_load_dictionary(ActionEvent event) { try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("load_dictionary.fxml")); Scene scene = new Scene(fxmlLoader.load(), 630, 400); Stage stage = new Stage(); stage.setTitle("Load Dictionary"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening Load Dictionary Scene"); } } @FXML private void solution_dialog(){ Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Solution"); alert.setHeaderText(null); if(Playing) alert.setContentText("Solution is " + game_word); else alert.setContentText("You are not playing !"); alert.showAndWait(); } public List<Button> word_buttons = new ArrayList<>(); public static String game_word; public int Number_of_Letters_left; public int lives; public List<Button> Invisible_Key_Buttons = new ArrayList<>(); public boolean initialise = false; @FXML public void start() { if(!initialise){ initialise_rounds(); } lives = 6; SetImage(lives); game_word = get_random_word(); Number_of_Letters_left = game_word.length(); Playing = true; Successful_Attempts = 0.0F; Total_Attempts = 0.0F; Success_Rate.setText("0%"); Available_Words(); if (game_word.equals("empty")) { Dictionary.setText("Load Dictionary!"); return; } //Reset Possible_letters.clear(); //Set invisible keys to visible if (!Invisible_Key_Buttons.isEmpty()) { for (Button invisible_key_button : Invisible_Key_Buttons) { invisible_key_button.setVisible(true); } } Dictionary.setText(title); System.out.println(title); //create a list of buttons word_hbox.getChildren().removeAll(word_buttons); word_buttons.clear(); for (int i = 0; i < game_word.length(); i++) { word_buttons.add(new Button("_")); //word_buttons.add(new Button(String.valueOf(game_word.charAt(i)))); word_hbox.getChildren().add(word_buttons.get(i)); word_buttons.get(i).setStyle("-fx-font-size: 2em; "); /* when clicked it should display the most common letters in the position of the letter in the Dictionary */ word_buttons.get(i).setOnAction(actionEvent -> { //... do something in here. }); } Same_length_stats(); } public List<String> Possible_letters = new ArrayList<>(); public List<Integer> Quantity_of_Letter = new ArrayList<>(); public Vector<String> same_length_words = new Vector<>(); public List<Element> elements = new ArrayList<Element>(); public void Same_length_stats() { /* Find words with equal length with game_word */ same_length_words.clear(); elements.clear(); for (String word : words) { if (word.length() == game_word.length() && !word.equals(game_word)) { same_length_words.add(word); } } // counter to keep track of how many int[][] CharCounter = new int[game_word.length()][26]; /* set all counters to zero */ // we have 26 counters for every letter of the game word for (int i = 0; i < game_word.length(); i++) { for (int z = 0; z < 26; z++) { CharCounter[i][z] = 0; } } // Now we count for (int i = 0; i < game_word.length(); i++) { for (String word : same_length_words) { int temp = (int) word.charAt(i) - 65; //Capital Letters CharCounter[i][temp]++; } } // add every counter to a List in order to keep track of them when we sort them for (int i = 0; i < game_word.length(); i++) { //i = position for (int z = 0; z < 26; z++) { //z = letter elements.add(new Element(i, z, CharCounter[i][z])); //System.out.println(CharCounter[i][z]); } } Collections.sort(elements); // reverse so we get the big numbers at front Collections.reverse(elements); for (int i = 0; i < game_word.length(); i++) { Possible_letters.add(""); System.out.println("---------LOOP " + String.valueOf(i) + "----------" ); System.out.println(i); for (Element element : elements) { if (element.position == i && element.quantity > 0) { //q>0 because we need P(q)>0 char letter = (char) (element.letter + 65); System.out.println(letter + " quantity :" + String.valueOf(element.quantity)); Possible_letters.set(i , Possible_letters.get(i) + String.valueOf(letter) + " "); } } int java_is_dumb = i; //lamda expressions need final expressions word_buttons.get(i).setOnAction(e -> {Possible_Letters_Label.setText(Possible_letters.get(java_is_dumb));}); System.out.println(Possible_letters.get(i)); } } public void Available_Words() { AvailableWordsLabel.setText(String.valueOf(words.size())); } public float Successful_Attempts; public float Total_Attempts; public void Success_Rate(){ if (Successful_Attempts == 0){ Success_Rate.setText("0%"); return; } else if (Successful_Attempts==Total_Attempts) { Success_Rate.setText("100%"); return; } float Success_rate = 100*Successful_Attempts/Total_Attempts;; String Success_Rate_Text = String.valueOf(Success_rate); String Label = ""; for (int i = 0; i < 4; i++) { Label += String.valueOf(Success_Rate_Text.charAt(i)); } Success_Rate.setText(Label+" %"); } public int Score = 0; public void Update_Score(int position){ int total_same_length_words = same_length_words.size(); int Element_letter = ((int) game_word.charAt(position)) - 65; //we have to convert it to the way we added it 26*i + z //int quantity_of_letter = elements.get(26*position + Element_letter).quantity; int quantity_of_letter = 0; for(Element element:elements){ if(element.letter == Element_letter && element.position==position){ quantity_of_letter = element.quantity; } } float percentage = (float)quantity_of_letter / (float) total_same_length_words; System.out.println("Total words, quantity of letter , percentage"); System.out.println(total_same_length_words); System.out.println(quantity_of_letter); System.out.println(percentage); //System.out.println(Element_letter+65); if(percentage >= 0.6) { Score += 5; } else if(percentage >= 0.4){ Score += 10; } else if(percentage >= 0.25){ Score += 15; } else Score += 30; } @FXML public void Try_this_Letter(Event event) { if (!Playing) { return; //If we ain't playing do nothing } System.out.println(event.getTarget()); Button btn = (Button) event.getSource(); //temp value String button_char = btn.getId(); System.out.println(btn.getId()); //get id btn.setVisible(false); Invisible_Key_Buttons.add(btn); /* ChecK if the character exist in the game word */ boolean success = false; Total_Attempts++; for (int i = 0; i < game_word.length(); i++) { if (button_char.equals(String.valueOf(game_word.charAt(i)))) { //reveal the letters that exist in the words success = true; Number_of_Letters_left--; word_buttons.get(i).setText(button_char); Update_Score(i); //we scored at position i TotalPoints.setText(String.valueOf(Score)); if (Number_of_Letters_left < 1) { System.out.println("Congratulations"); //win = true Update_Rounds(true); win_game(true); } } } if(!success){ lives--; SetImage(lives); //game_over(); if (lives < 1) { //win = false Playing = false; Update_Rounds(false); System.out.println("You lost :("); win_game(false); } } else Successful_Attempts++; Success_Rate(); } public void win_game(boolean win){ Alert alert = new Alert(Alert.AlertType.INFORMATION); if(win) { alert.setTitle("Congratulations"); alert.setHeaderText("You Won !"); alert.setContentText("Ready for the next one ?"); File myObj = new File("./images/win.png"); Image image = new Image(myObj.getAbsolutePath()); alert.setGraphic(new ImageView(image)); } else { alert.setTitle("Tough luck"); alert.setHeaderText("You Lost ..."); alert.setContentText("Want to try again ?"); File myObj = new File("./images/lost.png"); Image image = new Image(myObj.getAbsolutePath()); alert.setGraphic(new ImageView(image)); } ButtonType buttonTypeNextWord = new ButtonType("Next Word", ButtonBar.ButtonData.CANCEL_CLOSE); alert.getButtonTypes().setAll(buttonTypeNextWord); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == buttonTypeNextWord){ start(); } } public void SetImage(int lives) { File myObj = new File("./images/" + String.valueOf(lives) + ".jpg"); Image image = new Image(myObj.getAbsolutePath()); ImageView.setImage(image); } @FXML public void exit_app(){ Platform.exit(); } @FXML public void open_Dictionary_Details(ActionEvent event){ /*Dictionary: Μέσω ενός popup παραθύρου θα παρουσιάζει το ποσοστό των λέξεων του ενεργού λεξικού με 6 γράμματα, 7 έως 9 γράμματα και 10 ή περισσότερα γράμματα */ try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("dictionary_details.fxml")); Scene scene = new Scene(fxmlLoader.load(), 630, 400); Stage stage = new Stage(); stage.setTitle("Dictionary Details"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening Dictionary Details Scene"); } } public static Vector<String> gamewords_5 = new Vector<>(); public static Vector<String> results_5 = new Vector<>(); public static Vector<String> Attempts_per_gameword = new Vector<>(); public void initialise_rounds() { for (int i = 0; i < 5; i++) { gamewords_5.add("---"); results_5.add("---"); Attempts_per_gameword.add("---"); } initialise = true; } public void Update_Rounds(Boolean win) { //gamewords gamewords_5.remove(0); gamewords_5.add(game_word); //results results_5.remove(0); if(win){ results_5.add("Victory"); } else { results_5.add("Defeat"); } //attempts Attempts_per_gameword.remove(0); Attempts_per_gameword.add(String.valueOf((int) Total_Attempts)); } @FXML public void Instructions(){ try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("instructions.fxml")); Scene scene = new Scene(fxmlLoader.load()); Stage stage = new Stage(); stage.setTitle("Instructions"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening Instructions Scene"); } } @FXML public void Rounds(){ /*Rounds: Μέσω ενός<SUF>*/ try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("rounds.fxml")); Scene scene = new Scene(fxmlLoader.load(), 630, 400); Stage stage = new Stage(); stage.setTitle("Rounds Details"); stage.setScene(scene); stage.show(); } catch (IOException e) { System.out.println("Error opening Rounds Scene"); } } }
6074_0
package booking; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; public class AvailabilityOfAccommodations implements Runnable{ private Map<String, ReservationDateRange> roomAvailability; @Override public void run() { // Εδώ μπορείτε να ορίσετε μια συνεχή λειτουργία που θα εκτελείται από το νήμα while (true) { // Προσθέστε τυχόν επιπλέον λειτουργίες που θέλετε να εκτελεστούν επανειλημμένα try { Thread.sleep(1000); // Περιμένει 1 δευτερόλεπτο πριν συνεχίσει } catch (InterruptedException e) { e.printStackTrace(); } } } public AvailabilityOfAccommodations() { this.roomAvailability = new HashMap<>(); } public Map<String, ReservationDateRange> getRoomAvailability() { return roomAvailability; } /** * Initial input to map from JSONfile * * @param path */ public void addRoomAsAvailableFromJSON(Path path) { AccommodationList accommodationList = new AccommodationList(path); for (int i = 0; i < accommodationList.getLengthOfAccommodationList(); i++) { roomAvailability.put(accommodationList.get(i).getRoomName(), new ReservationDateRange()); } } /** * From Manager input to map * * @param roomName * @param from * @param to */ public void addRoomAsAvailableFromManager(String roomName, ReservationDate from, ReservationDate to) { System.out.println("..................function: addRoomAsAvailableFromManager..............................."); boolean exist = false; for (String key : roomAvailability.keySet()) { if (key.equals(roomName)) { roomAvailability.put(roomName, new ReservationDateRange(from, to)); exist = true; } } if (exist) { System.out.println("The room " + roomName + " successfully inserted as available"); } else { System.out.println("The specific room " + roomName + " does not exist."); } } /** * booking of a room - client function * * @param roomName */ public synchronized void bookingOfRoom(String roomName) { System.out.println("..................function: bookingOfRoom..............................."); boolean booking = false; for (String key : roomAvailability.keySet()) { ReservationDateRange range = roomAvailability.get(key); if (key.equals(roomName)) if (range.isAvailable()) { range.setAvailable(false); booking = true; } } if (booking) { System.out.println("The " + roomName + " is successfully booked."); } else { System.out.println("The " + roomName + " is not available."); } } @Override public String toString() { return "Manager{" + "roomAvailability=" + roomAvailability + '}'; } public static void main(String[] args) { // Default gemisma tou list apo JSON file AccommodationList list = new AccommodationList(Path.of("src/main/java/booking/accommodations.json")); // object // Default gemisma tou map apo JSON file AvailabilityOfAccommodations availabilityOfAccommodations = new AvailabilityOfAccommodations(); // object ReservationDate from = new ReservationDate(20, 4, 2024); ReservationDate to = new ReservationDate(30, 4, 2024); availabilityOfAccommodations.addRoomAsAvailableFromJSON(Path.of("src/main/java/booking/accommodations.json")); // map availabilityOfAccommodations.addRoomAsAvailableFromManager("lala", from, to); // ta typwnei opws akrivws ta exei parei apo to JSON for (String key : availabilityOfAccommodations.getRoomAvailability().keySet()) { System.out.println(key + ": " +availabilityOfAccommodations.getRoomAvailability().get(key)); } // O manager allazei mia hmerominia gia th diathesimotita tou dwmatiou availabilityOfAccommodations.addRoomAsAvailableFromManager("130", from, to); for (String key : availabilityOfAccommodations.getRoomAvailability().keySet()) { System.out.println(key + ": " +availabilityOfAccommodations.getRoomAvailability().get(key)); } // booking of a room availabilityOfAccommodations.bookingOfRoom("235"); availabilityOfAccommodations.bookingOfRoom("500"); } }
AikVant/distributed_booking_2024
src/main/java/booking/AvailabilityOfAccommodations.java
1,206
// Εδώ μπορείτε να ορίσετε μια συνεχή λειτουργία που θα εκτελείται από το νήμα
line_comment
el
package booking; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; public class AvailabilityOfAccommodations implements Runnable{ private Map<String, ReservationDateRange> roomAvailability; @Override public void run() { // Εδώ μπορείτε<SUF> while (true) { // Προσθέστε τυχόν επιπλέον λειτουργίες που θέλετε να εκτελεστούν επανειλημμένα try { Thread.sleep(1000); // Περιμένει 1 δευτερόλεπτο πριν συνεχίσει } catch (InterruptedException e) { e.printStackTrace(); } } } public AvailabilityOfAccommodations() { this.roomAvailability = new HashMap<>(); } public Map<String, ReservationDateRange> getRoomAvailability() { return roomAvailability; } /** * Initial input to map from JSONfile * * @param path */ public void addRoomAsAvailableFromJSON(Path path) { AccommodationList accommodationList = new AccommodationList(path); for (int i = 0; i < accommodationList.getLengthOfAccommodationList(); i++) { roomAvailability.put(accommodationList.get(i).getRoomName(), new ReservationDateRange()); } } /** * From Manager input to map * * @param roomName * @param from * @param to */ public void addRoomAsAvailableFromManager(String roomName, ReservationDate from, ReservationDate to) { System.out.println("..................function: addRoomAsAvailableFromManager..............................."); boolean exist = false; for (String key : roomAvailability.keySet()) { if (key.equals(roomName)) { roomAvailability.put(roomName, new ReservationDateRange(from, to)); exist = true; } } if (exist) { System.out.println("The room " + roomName + " successfully inserted as available"); } else { System.out.println("The specific room " + roomName + " does not exist."); } } /** * booking of a room - client function * * @param roomName */ public synchronized void bookingOfRoom(String roomName) { System.out.println("..................function: bookingOfRoom..............................."); boolean booking = false; for (String key : roomAvailability.keySet()) { ReservationDateRange range = roomAvailability.get(key); if (key.equals(roomName)) if (range.isAvailable()) { range.setAvailable(false); booking = true; } } if (booking) { System.out.println("The " + roomName + " is successfully booked."); } else { System.out.println("The " + roomName + " is not available."); } } @Override public String toString() { return "Manager{" + "roomAvailability=" + roomAvailability + '}'; } public static void main(String[] args) { // Default gemisma tou list apo JSON file AccommodationList list = new AccommodationList(Path.of("src/main/java/booking/accommodations.json")); // object // Default gemisma tou map apo JSON file AvailabilityOfAccommodations availabilityOfAccommodations = new AvailabilityOfAccommodations(); // object ReservationDate from = new ReservationDate(20, 4, 2024); ReservationDate to = new ReservationDate(30, 4, 2024); availabilityOfAccommodations.addRoomAsAvailableFromJSON(Path.of("src/main/java/booking/accommodations.json")); // map availabilityOfAccommodations.addRoomAsAvailableFromManager("lala", from, to); // ta typwnei opws akrivws ta exei parei apo to JSON for (String key : availabilityOfAccommodations.getRoomAvailability().keySet()) { System.out.println(key + ": " +availabilityOfAccommodations.getRoomAvailability().get(key)); } // O manager allazei mia hmerominia gia th diathesimotita tou dwmatiou availabilityOfAccommodations.addRoomAsAvailableFromManager("130", from, to); for (String key : availabilityOfAccommodations.getRoomAvailability().keySet()) { System.out.println(key + ": " +availabilityOfAccommodations.getRoomAvailability().get(key)); } // booking of a room availabilityOfAccommodations.bookingOfRoom("235"); availabilityOfAccommodations.bookingOfRoom("500"); } }
7912_7
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.sphy141.probase.utils; /** * * @author Alan */ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class CryptoUtils { private static final String key = "sphy141groupbuy!"; public static String hashString(String password) { try { // Create an instance of the SHA-256 algorithm MessageDigest digest = MessageDigest.getInstance("SHA-256"); // Convert the password string to bytes byte[] passwordBytes = password.getBytes(); // Calculate the hash value of the password bytes byte[] hashBytes = digest.digest(passwordBytes); // Convert the hash bytes to a hexadecimal string StringBuilder sb = new StringBuilder(); for (byte hashByte : hashBytes) { sb.append(String.format("%02x", hashByte)); } return sb.toString(); } catch (NoSuchAlgorithmException e) { // Handle the exception e.printStackTrace(); } return null; }//hashString /*επειδή ο hash-256 είναι μονόδρομος αλγόριθμος κρυπρογάφισης χρησιμοποιώ τον αλγόριθμο AES προκειμένου να δημιουργήσω μία κρυπτογράφιση για τα δεδομένα της βάσης που είνια ευαίσθητα πχ χρήστη και επιχειρήσεων*/ public static String encrypt(String plainText) { try { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedBytes = cipher.doFinal(plainText.getBytes()); return Base64.getEncoder().encodeToString(encryptedBytes); } catch (Exception e) { e.printStackTrace(); } return null; }//hashAESString public static String decrypt(String encryptedText) { try { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText)); return new String(decryptedBytes); } catch (Exception e) { e.printStackTrace(); } return null; }//hashAESString public static String encryptDouble(double number) { try { String plainText = Double.toString(number); SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedBytes = cipher.doFinal(plainText.getBytes()); return Base64.getEncoder().encodeToString(encryptedBytes); } catch (Exception e) { e.printStackTrace(); } return null; } public static double decryptDouble(String encryptedText) { try { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText)); String decryptedText = new String(decryptedBytes); return Double.parseDouble(decryptedText); } catch (Exception e) { e.printStackTrace(); } return 0.0; } }//class
Alan-III/GroupBuy
groupBuyNetbeans/src/main/java/com/sphy141/probase/utils/CryptoUtils.java
989
/*επειδή ο hash-256 είναι μονόδρομος αλγόριθμος κρυπρογάφισης χρησιμοποιώ τον αλγόριθμο AES προκειμένου να δημιουργήσω μία κρυπτογράφιση για τα δεδομένα της βάσης που είνια ευαίσθητα πχ χρήστη και επιχειρήσεων*/
block_comment
el
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.sphy141.probase.utils; /** * * @author Alan */ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class CryptoUtils { private static final String key = "sphy141groupbuy!"; public static String hashString(String password) { try { // Create an instance of the SHA-256 algorithm MessageDigest digest = MessageDigest.getInstance("SHA-256"); // Convert the password string to bytes byte[] passwordBytes = password.getBytes(); // Calculate the hash value of the password bytes byte[] hashBytes = digest.digest(passwordBytes); // Convert the hash bytes to a hexadecimal string StringBuilder sb = new StringBuilder(); for (byte hashByte : hashBytes) { sb.append(String.format("%02x", hashByte)); } return sb.toString(); } catch (NoSuchAlgorithmException e) { // Handle the exception e.printStackTrace(); } return null; }//hashString /*επειδή ο hash-256<SUF>*/ public static String encrypt(String plainText) { try { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedBytes = cipher.doFinal(plainText.getBytes()); return Base64.getEncoder().encodeToString(encryptedBytes); } catch (Exception e) { e.printStackTrace(); } return null; }//hashAESString public static String decrypt(String encryptedText) { try { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText)); return new String(decryptedBytes); } catch (Exception e) { e.printStackTrace(); } return null; }//hashAESString public static String encryptDouble(double number) { try { String plainText = Double.toString(number); SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedBytes = cipher.doFinal(plainText.getBytes()); return Base64.getEncoder().encodeToString(encryptedBytes); } catch (Exception e) { e.printStackTrace(); } return null; } public static double decryptDouble(String encryptedText) { try { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText)); String decryptedText = new String(decryptedBytes); return Double.parseDouble(decryptedText); } catch (Exception e) { e.printStackTrace(); } return 0.0; } }//class
5142_0
import java.time.LocalDate; import java.util.ArrayList; import java.util.TimerTask; /*Κλάση <SystemNοtifications> Η κλάση αυτή αφορά τις ενέργειες του συστήματος οι οποίες εξαρτώνται άμεσα απο τον χρόνο. Συγκεκριμένα εξυπηρετεί τις περιπτώσεις χρήσης: Penalty - Use Case Code: 26 (X02),Warning - Use Case Code: 25 (X03)*/ public class SystemNotification extends TimerTask { //synarthsh-thread gia ton taktiko elegxo twn kyrwsewn.kaleitai sthn main public static void checkforActions() { Warning.checkforWarning(); Penalty.checkforPenalty(); Penalty.undoPenalties(); } @Override public void run() { // TODO Auto-generated method stub SystemNotification.checkforActions(); } //------------------------------------------------------// private static class Warning{ public static void checkforWarning() { int timeleft=3; ArrayList<BookLending> borrowed=Main.librarydata.getBorrowedBooks(); //gia kathe daneizomeno for(BookLending booklending:borrowed) {if(booklending.getTimeLeft(LocalDate.now().plusDays(3))==timeleft){ String text="To vivlio"+booklending.getBook().getTitle()+"prepei na epistrafei se 3 meres"; Borrower recipient=booklending.getBorrower(); Message warning=new Message(text,Main.librarian); Message.messageToBorrower(recipient, warning); } } } } private static class Penalty{ public static void checkforPenalty() { ArrayList<BookLending> borrowed=Main.librarydata.getBorrowedBooks(); ArrayList<BookLending> delayed=Main.librarydata.getDelayedBooks(); for(BookLending booklending:borrowed) { if(booklending.getTimeLeft(LocalDate.now())==-1) { delayed.add(booklending); borrowed.remove(booklending); Borrower recipient=booklending.getBorrower(); recipient.setNumberOfPenalties((recipient.getNumberOfPenalties()+1)%3); boolean severe=false; if(recipient.getNumberOfPenalties()==0) { recipient.setAbleToBorrow(false); recipient.setDateOfLastPenlty(LocalDate.now()); /**add to withpenalty list**/ ArrayList<Borrower> p=Main.librarydata.getWithPenalty(); if(p.indexOf(recipient)==-1)//if doesn't exist {p.add(recipient);} severe=true; } //message to be sent String text1="To vivlio"+booklending.getBook().getTitle()+" exei kathysterhsei ,na epistrafei amesa"; String text2="To vivlio"+booklending.getBook().getTitle()+" exei kathysterhsei ,na epistrafei amesa.Logw epanalambanomenwn kathisterhsewn" + "den mporeite na daneisteite gia 30 meres"; Message warning=null; if(!severe) {warning=new Message(text1,Main.librarian);}else {warning=new Message(text2,Main.librarian);} Message.messageToBorrower(recipient, warning); } } } public static void undoPenalties() { ArrayList<Borrower> penalties=Main.librarydata.getWithPenalty(); for(Borrower b:penalties) { if(b.getDateOfLastPenlty().plusDays(14)==LocalDate.now()) { b.setAbleToBorrow(true); penalties.remove(b); String text="Mporeite na daneisteite 3ana"; Message inform=new Message(text,Main.librarian); Message.messageToBorrower(b, inform); } } } } }
AlexMitsis/LibSoft
src/SystemNotification.java
1,124
/*Κλάση <SystemNοtifications> Η κλάση αυτή αφορά τις ενέργειες του συστήματος οι οποίες εξαρτώνται άμεσα απο τον χρόνο. Συγκεκριμένα εξυπηρετεί τις περιπτώσεις χρήσης: Penalty - Use Case Code: 26 (X02),Warning - Use Case Code: 25 (X03)*/
block_comment
el
import java.time.LocalDate; import java.util.ArrayList; import java.util.TimerTask; /*Κλάση <SystemNοtifications> Η<SUF>*/ public class SystemNotification extends TimerTask { //synarthsh-thread gia ton taktiko elegxo twn kyrwsewn.kaleitai sthn main public static void checkforActions() { Warning.checkforWarning(); Penalty.checkforPenalty(); Penalty.undoPenalties(); } @Override public void run() { // TODO Auto-generated method stub SystemNotification.checkforActions(); } //------------------------------------------------------// private static class Warning{ public static void checkforWarning() { int timeleft=3; ArrayList<BookLending> borrowed=Main.librarydata.getBorrowedBooks(); //gia kathe daneizomeno for(BookLending booklending:borrowed) {if(booklending.getTimeLeft(LocalDate.now().plusDays(3))==timeleft){ String text="To vivlio"+booklending.getBook().getTitle()+"prepei na epistrafei se 3 meres"; Borrower recipient=booklending.getBorrower(); Message warning=new Message(text,Main.librarian); Message.messageToBorrower(recipient, warning); } } } } private static class Penalty{ public static void checkforPenalty() { ArrayList<BookLending> borrowed=Main.librarydata.getBorrowedBooks(); ArrayList<BookLending> delayed=Main.librarydata.getDelayedBooks(); for(BookLending booklending:borrowed) { if(booklending.getTimeLeft(LocalDate.now())==-1) { delayed.add(booklending); borrowed.remove(booklending); Borrower recipient=booklending.getBorrower(); recipient.setNumberOfPenalties((recipient.getNumberOfPenalties()+1)%3); boolean severe=false; if(recipient.getNumberOfPenalties()==0) { recipient.setAbleToBorrow(false); recipient.setDateOfLastPenlty(LocalDate.now()); /**add to withpenalty list**/ ArrayList<Borrower> p=Main.librarydata.getWithPenalty(); if(p.indexOf(recipient)==-1)//if doesn't exist {p.add(recipient);} severe=true; } //message to be sent String text1="To vivlio"+booklending.getBook().getTitle()+" exei kathysterhsei ,na epistrafei amesa"; String text2="To vivlio"+booklending.getBook().getTitle()+" exei kathysterhsei ,na epistrafei amesa.Logw epanalambanomenwn kathisterhsewn" + "den mporeite na daneisteite gia 30 meres"; Message warning=null; if(!severe) {warning=new Message(text1,Main.librarian);}else {warning=new Message(text2,Main.librarian);} Message.messageToBorrower(recipient, warning); } } } public static void undoPenalties() { ArrayList<Borrower> penalties=Main.librarydata.getWithPenalty(); for(Borrower b:penalties) { if(b.getDateOfLastPenlty().plusDays(14)==LocalDate.now()) { b.setAbleToBorrow(true); penalties.remove(b); String text="Mporeite na daneisteite 3ana"; Message inform=new Message(text,Main.librarian); Message.messageToBorrower(b, inform); } } } } }
13673_4
package gr.aueb.dmst.T21; import java.util.Scanner; public class TestApp { static App app = new App(); // make app global and static public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Run the program (1)\nExit (0)"); int choice = sc.nextInt(); String input1 = ""; String input2 = ""; String input3 = ""; //String input4 = ""; //String input5 = ""; String input6 = ""; String expectedOutput = ""; //new object for RegistrationForm while (choice == 1) { System.out.println("productionYear"); input1 = sc.nextLine(); sc.nextLine(); // Διαβάζει την αλλαγή γραμμής που παρέμεινε στο buffer System.out.println("model"); input2 = sc.nextLine(); System.out.println("brand"); input3 = sc.nextLine(); /* System.out.println("key1"); input4 = sc.nextLine(); System.out.println("key2"); input5 = sc.nextLine(); */ System.out.println("key3"); input6 = sc.nextLine(); System.out.println("Expected output"); expectedOutput = sc.nextLine(); //check the true value chatGPT ch = new chatGPT(); String message = "Give me details about " + input6 + ", " + input3 + " " + input2 + " " + input1 + "."; //question for AI String answer = ch.chatGPT(message); if (answer.equals(expectedOutput)) { System.out.println("Test passed"); } else { System.out.println("Test failed"); //print both outputs System.out.println("Expected output: " + expectedOutput); System.out.println("Actual output: " + answer); } System.out.println("For continue press 1, for exit press 0"); choice = sc.nextInt(); } } }
Alexandra-Stath/Finding-Spare-Parts-Using-AI
Finding-Spare-Parts-Using-AI/src/main/java/gr/aueb/dmst/T21/TestApp.java
498
// Διαβάζει την αλλαγή γραμμής που παρέμεινε στο buffer
line_comment
el
package gr.aueb.dmst.T21; import java.util.Scanner; public class TestApp { static App app = new App(); // make app global and static public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Run the program (1)\nExit (0)"); int choice = sc.nextInt(); String input1 = ""; String input2 = ""; String input3 = ""; //String input4 = ""; //String input5 = ""; String input6 = ""; String expectedOutput = ""; //new object for RegistrationForm while (choice == 1) { System.out.println("productionYear"); input1 = sc.nextLine(); sc.nextLine(); // Διαβάζει την<SUF> System.out.println("model"); input2 = sc.nextLine(); System.out.println("brand"); input3 = sc.nextLine(); /* System.out.println("key1"); input4 = sc.nextLine(); System.out.println("key2"); input5 = sc.nextLine(); */ System.out.println("key3"); input6 = sc.nextLine(); System.out.println("Expected output"); expectedOutput = sc.nextLine(); //check the true value chatGPT ch = new chatGPT(); String message = "Give me details about " + input6 + ", " + input3 + " " + input2 + " " + input1 + "."; //question for AI String answer = ch.chatGPT(message); if (answer.equals(expectedOutput)) { System.out.println("Test passed"); } else { System.out.println("Test failed"); //print both outputs System.out.println("Expected output: " + expectedOutput); System.out.println("Actual output: " + answer); } System.out.println("For continue press 1, for exit press 0"); choice = sc.nextInt(); } } }
9063_3
package javaproject; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; import java.io.*; import java.util.logging.Level; import java.util.logging.Logger; public class StudentFrame extends JFrame { private ArrayList<Student> mstudents=new ArrayList<Student>(); private JButton addButton,showButton,saveButton,loadButton,removeButton; private JTextArea showArea; public String removal; int temp=0; //Προσθέτοντας Φοιτητή void addStudent() { mstudents.add(new Student()); } //Εμφανίζοντας Μαθητή void showStudent() { String text=""; for(Student x :mstudents) { text+=x+"\n"; } showArea.setText(text); } //Αποθυκεύοντας Μαθητή void saveStudent() { JFileChooser chooser=new JFileChooser(); int returnVal = chooser.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { try { String filename=chooser.getSelectedFile().getAbsolutePath(); FileWriter fw=null; fw = new FileWriter(filename); PrintWriter pw=new PrintWriter(fw); for(Student x:mstudents) { pw.println(""+x); } fw.close(); } catch (IOException ex) { Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex); } } } //Φορτώνοντας Μαθητή void loadStudent() { JFileChooser chooser=new JFileChooser(); int returnVal = chooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { try { String filename=chooser.getSelectedFile().getAbsolutePath(); FileReader rw=new FileReader(filename); Scanner in=new Scanner(rw); mstudents=new ArrayList<Student>(); while(in.hasNextLine()) { String line=in.nextLine(); String[] parts=line.split(","); mstudents.add(new Student(parts[0],parts[1],parts[2],Integer.parseInt(parts[3]))); } } catch (IOException ex) { } } } //Διαγράφωντας Μαθητή void removeStudent(){ removal = JOptionPane.showInputDialog("Παρακαλώ δώστε ΑΜ μαθήματή"); //οσο ο μαθητής υπάρχει boolean found =true; while(found) { found=false; for(int i=0;i<mstudents.size();i++) { if(temp==0){ if(mstudents.get(i).getam().equals(removal)) { mstudents.remove(i); found=true; temp=1; break; } } } } //Συνθήκη βρέθηκε τελεστής temp=1 αληθές , 0=ψευδές if(temp==0){ JOptionPane.showMessageDialog(null,"Ο Αριθμός Μητρώου δεν βρέθηκε!"); } else if(temp==1){ JOptionPane.showMessageDialog(null,"Βρέθηκε ο αριθμός μητρώου, παρακαλώ πατήστε 'Εμφάνιση' "); temp=0; } } //Φτιάχνοντας τα κουμπιά void makeButtons() { JPanel buttonPanel=new JPanel(); buttonPanel.setLayout(new GridLayout(1,2)); addButton=new JButton("Νεος Μαθητής"); addButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { addStudent(); } }); buttonPanel.add(addButton); showButton=new JButton("Εμφάνιση"); buttonPanel.add(showButton); showButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { showStudent(); } }); saveButton=new JButton("Αποθύκευση"); buttonPanel.add(saveButton); saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { saveStudent(); } }); loadButton=new JButton("Φόρτωση"); buttonPanel.add(loadButton); loadButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { loadStudent(); } }); removeButton = new JButton("Διαγραφή Μαθητή"); buttonPanel.add(removeButton); removeButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { removeStudent(); } }); add(buttonPanel); } //Φτιάχνοντας το StudentFrame public StudentFrame(String title) { super(title); setSize(750,300); setLayout(new GridLayout(3,1)); setResizable(true); makeButtons(); showArea=new JTextArea(""); showArea.setRows(5); showArea.setColumns(25); showArea.setEditable(false); JScrollPane sp=new JScrollPane(showArea); add(sp); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } }
AlexandrosPanag/My_Java_Projects
Lesson Enrollment Project/StudentFrame.java
1,453
//Φτιάχνοντας το StudentFrame
line_comment
el
package javaproject; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; import java.io.*; import java.util.logging.Level; import java.util.logging.Logger; public class StudentFrame extends JFrame { private ArrayList<Student> mstudents=new ArrayList<Student>(); private JButton addButton,showButton,saveButton,loadButton,removeButton; private JTextArea showArea; public String removal; int temp=0; //Προσθέτοντας Φοιτητή void addStudent() { mstudents.add(new Student()); } //Εμφανίζοντας Μαθητή void showStudent() { String text=""; for(Student x :mstudents) { text+=x+"\n"; } showArea.setText(text); } //Αποθυκεύοντας Μαθητή void saveStudent() { JFileChooser chooser=new JFileChooser(); int returnVal = chooser.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { try { String filename=chooser.getSelectedFile().getAbsolutePath(); FileWriter fw=null; fw = new FileWriter(filename); PrintWriter pw=new PrintWriter(fw); for(Student x:mstudents) { pw.println(""+x); } fw.close(); } catch (IOException ex) { Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex); } } } //Φορτώνοντας Μαθητή void loadStudent() { JFileChooser chooser=new JFileChooser(); int returnVal = chooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { try { String filename=chooser.getSelectedFile().getAbsolutePath(); FileReader rw=new FileReader(filename); Scanner in=new Scanner(rw); mstudents=new ArrayList<Student>(); while(in.hasNextLine()) { String line=in.nextLine(); String[] parts=line.split(","); mstudents.add(new Student(parts[0],parts[1],parts[2],Integer.parseInt(parts[3]))); } } catch (IOException ex) { } } } //Διαγράφωντας Μαθητή void removeStudent(){ removal = JOptionPane.showInputDialog("Παρακαλώ δώστε ΑΜ μαθήματή"); //οσο ο μαθητής υπάρχει boolean found =true; while(found) { found=false; for(int i=0;i<mstudents.size();i++) { if(temp==0){ if(mstudents.get(i).getam().equals(removal)) { mstudents.remove(i); found=true; temp=1; break; } } } } //Συνθήκη βρέθηκε τελεστής temp=1 αληθές , 0=ψευδές if(temp==0){ JOptionPane.showMessageDialog(null,"Ο Αριθμός Μητρώου δεν βρέθηκε!"); } else if(temp==1){ JOptionPane.showMessageDialog(null,"Βρέθηκε ο αριθμός μητρώου, παρακαλώ πατήστε 'Εμφάνιση' "); temp=0; } } //Φτιάχνοντας τα κουμπιά void makeButtons() { JPanel buttonPanel=new JPanel(); buttonPanel.setLayout(new GridLayout(1,2)); addButton=new JButton("Νεος Μαθητής"); addButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { addStudent(); } }); buttonPanel.add(addButton); showButton=new JButton("Εμφάνιση"); buttonPanel.add(showButton); showButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { showStudent(); } }); saveButton=new JButton("Αποθύκευση"); buttonPanel.add(saveButton); saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { saveStudent(); } }); loadButton=new JButton("Φόρτωση"); buttonPanel.add(loadButton); loadButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { loadStudent(); } }); removeButton = new JButton("Διαγραφή Μαθητή"); buttonPanel.add(removeButton); removeButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { removeStudent(); } }); add(buttonPanel); } //Φτιάχνοντας το<SUF> public StudentFrame(String title) { super(title); setSize(750,300); setLayout(new GridLayout(3,1)); setResizable(true); makeButtons(); showArea=new JTextArea(""); showArea.setRows(5); showArea.setColumns(25); showArea.setEditable(false); JScrollPane sp=new JScrollPane(showArea); add(sp); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } }
42450_0
/** * @author Πλέσσιας Αλέξανδρος (ΑΜ.:2025201100068). */ package PreProcessing; import java.util.ArrayList; import java.util.Arrays; /** * StopWordsRemoval remove all words contained in ArrayList stopWords. * ArrayList came from wed search. */ public class StopWordsRemoval { public static ArrayList<String> stopWords = new ArrayList<>(Arrays.asList( "without", "see", "unless", "due", "also", "must", "might", "like", "<", ">", "will", "-", "may", "can", "much", "every", "the", "in", "other", "this", "the", "many", "any", "an", "or", "for", "in", "an", "an ", "is", "a", "about", "above", "after", "again", "against", "all", "am", "an", "and", "any", "are", "aren’t", "as", "at", "be", "because", "been", "before", "being", "below", "between", "both", "but", "by", "can’t", "cannot", "could", "couldn’t", "did", "didn’t", "do", "does", "doesn’t", "doing", "don’t", "down", "during", "each", "few", "for", "from", "further", "had", "hadn’t", "has", "hasn’t", "have", "haven’t", "having", "he", "he’d", "he’ll", "he’s", "her", "here", "here’s", "hers", "herself", "him", "himself", "his", "how", "how’s", "i ", " i", "i’d", "i’ll", "i’m", "i’ve", "if", "in", "into", "is", "isn’t", "it", "it’s", "its", "itself", "let’s", "me", "more", "most", "mustn’t", "my", "myself", "no", "nor", "not", "of", "off", "on", "once", "only", "ought", "our", "ours", "ourselves", "out", "over", "own", "same", "shan’t", "she", "she’d", "she’ll", "she’s", "should", "shouldn’t", "so", "some", "such", "than", "that", "that’s", "their", "theirs", "them", "themselves", "then", "there", "there’s", "these", "they", "they’d", "they’ll", "they’re", "they’ve", "this", "those", "through", "to", "too", "under", "until", "up", "very", "was", "wasn’t", "we", "we’d", "we’ll", "we’re", "we’ve", "were", "weren’t", "what", "what’s", "when", "when’s", "where", "where’s", "which", "while", "who", "who’s", "whom", "why", "why’s", "with", "won’t", "would", "wouldn’t", "you", "you’d", "you’ll", "you’re", "you’ve", "your", "yours", "yourself", "yourselves", "without", "see", "unless", "due", "also", "must", "might", "like", "will", "may", "can", "much", "every", "the", "in", "other", "this", "the", "many", "any", "an", "or", "for", "in", "an", "an ", "is", "a", "about", "above", "after", "again", "against", "all", "am", "an", "and", "any", "are", "aren’t", "as", "at", "be", "because", "been", "before", "being", "below", "between", "both", "but", "by", "can’t", "cannot", "could", "couldn’t", "did", "didn’t", "do", "does", "doesn’t", "doing", "don’t", "down", "during", "each", "few", "for", "from", "further", "had", "hadn’t", "has", "hasn’t", "have", "haven’t", "having", "he", "he’d", "he’ll", "he’s", "her", "here", "here’s", "hers", "herself", "him", "himself", "his", "how", "how’s", "i ", " i", "i’d", "i’ll", "i’m", "i’ve", "if", "in", "into", "is", "isn’t", "it", "it’s", "its", "itself", "let’s", "me", "more", "most", "mustn’t", "my", "myself", "no", "nor", "not", "of", "off", "on", "once", "only", "ought", "our", "ours", "ourselves", "out", "over", "own", "same", "shan’t", "she", "she’d", "she’ll", "she’s", "should", "shouldn’t", "so", "some", "such", "than", "that", "that’s", "their", "theirs", "them", "themselves", "then", "there", "there’s", "these", "they", "they’d", "they’ll", "they’re", "they’ve", "this", "those", "through", "to", "too", "under", "until", "up", "very", "was", "wasn’t", "we", "we’d", "we’ll", "we’re", "we’ve", "were", "weren’t", "what", "what’s", "when", "when’s", "where", "where’s", "which", "while", "who", "who’s", "whom", "why", "why’s", "with", "won’t", "would", "wouldn’t", "you", "you’d", "you’ll", "you’re", "you’ve", "your", "yours", "yourself", "yourselves" )); public ArrayList<String> clearWords; // Remove all words match to arralist with stopwords. public StopWordsRemoval(ArrayList<String> bagOfWords) { bagOfWords.removeAll(stopWords); clearWords = bagOfWords; } // Getter. public ArrayList<String> getfileWithoutStopWords() { return clearWords; } }
AlexandrosPlessias/IR-CosineSimilarity-vs-Freq
src/PreProcessing/StopWordsRemoval.java
1,715
/** * @author Πλέσσιας Αλέξανδρος (ΑΜ.:2025201100068). */
block_comment
el
/** * @author Πλέσσιας Αλέξανδρος<SUF>*/ package PreProcessing; import java.util.ArrayList; import java.util.Arrays; /** * StopWordsRemoval remove all words contained in ArrayList stopWords. * ArrayList came from wed search. */ public class StopWordsRemoval { public static ArrayList<String> stopWords = new ArrayList<>(Arrays.asList( "without", "see", "unless", "due", "also", "must", "might", "like", "<", ">", "will", "-", "may", "can", "much", "every", "the", "in", "other", "this", "the", "many", "any", "an", "or", "for", "in", "an", "an ", "is", "a", "about", "above", "after", "again", "against", "all", "am", "an", "and", "any", "are", "aren’t", "as", "at", "be", "because", "been", "before", "being", "below", "between", "both", "but", "by", "can’t", "cannot", "could", "couldn’t", "did", "didn’t", "do", "does", "doesn’t", "doing", "don’t", "down", "during", "each", "few", "for", "from", "further", "had", "hadn’t", "has", "hasn’t", "have", "haven’t", "having", "he", "he’d", "he’ll", "he’s", "her", "here", "here’s", "hers", "herself", "him", "himself", "his", "how", "how’s", "i ", " i", "i’d", "i’ll", "i’m", "i’ve", "if", "in", "into", "is", "isn’t", "it", "it’s", "its", "itself", "let’s", "me", "more", "most", "mustn’t", "my", "myself", "no", "nor", "not", "of", "off", "on", "once", "only", "ought", "our", "ours", "ourselves", "out", "over", "own", "same", "shan’t", "she", "she’d", "she’ll", "she’s", "should", "shouldn’t", "so", "some", "such", "than", "that", "that’s", "their", "theirs", "them", "themselves", "then", "there", "there’s", "these", "they", "they’d", "they’ll", "they’re", "they’ve", "this", "those", "through", "to", "too", "under", "until", "up", "very", "was", "wasn’t", "we", "we’d", "we’ll", "we’re", "we’ve", "were", "weren’t", "what", "what’s", "when", "when’s", "where", "where’s", "which", "while", "who", "who’s", "whom", "why", "why’s", "with", "won’t", "would", "wouldn’t", "you", "you’d", "you’ll", "you’re", "you’ve", "your", "yours", "yourself", "yourselves", "without", "see", "unless", "due", "also", "must", "might", "like", "will", "may", "can", "much", "every", "the", "in", "other", "this", "the", "many", "any", "an", "or", "for", "in", "an", "an ", "is", "a", "about", "above", "after", "again", "against", "all", "am", "an", "and", "any", "are", "aren’t", "as", "at", "be", "because", "been", "before", "being", "below", "between", "both", "but", "by", "can’t", "cannot", "could", "couldn’t", "did", "didn’t", "do", "does", "doesn’t", "doing", "don’t", "down", "during", "each", "few", "for", "from", "further", "had", "hadn’t", "has", "hasn’t", "have", "haven’t", "having", "he", "he’d", "he’ll", "he’s", "her", "here", "here’s", "hers", "herself", "him", "himself", "his", "how", "how’s", "i ", " i", "i’d", "i’ll", "i’m", "i’ve", "if", "in", "into", "is", "isn’t", "it", "it’s", "its", "itself", "let’s", "me", "more", "most", "mustn’t", "my", "myself", "no", "nor", "not", "of", "off", "on", "once", "only", "ought", "our", "ours", "ourselves", "out", "over", "own", "same", "shan’t", "she", "she’d", "she’ll", "she’s", "should", "shouldn’t", "so", "some", "such", "than", "that", "that’s", "their", "theirs", "them", "themselves", "then", "there", "there’s", "these", "they", "they’d", "they’ll", "they’re", "they’ve", "this", "those", "through", "to", "too", "under", "until", "up", "very", "was", "wasn’t", "we", "we’d", "we’ll", "we’re", "we’ve", "were", "weren’t", "what", "what’s", "when", "when’s", "where", "where’s", "which", "while", "who", "who’s", "whom", "why", "why’s", "with", "won’t", "would", "wouldn’t", "you", "you’d", "you’ll", "you’re", "you’ve", "your", "yours", "yourself", "yourselves" )); public ArrayList<String> clearWords; // Remove all words match to arralist with stopwords. public StopWordsRemoval(ArrayList<String> bagOfWords) { bagOfWords.removeAll(stopWords); clearWords = bagOfWords; } // Getter. public ArrayList<String> getfileWithoutStopWords() { return clearWords; } }
1027_3
package api; import java.io.Serializable; import java.time.LocalDate; /** * Η κλάση αυτή αναπαριστά μια αξιολόγηση ενός καταλύματος * @author Anestis Zotos */ public class Evaluation implements Serializable { private String txt_eval; //αξιολόγηση σε μορφή κειμένου private double num_eval; //αξιολόγηση σε μορφή αριθμού private LocalDate curDate; //ημερομηνία τελευταίας(πιο πρόσφατης)αξιολόγησης //constructor public Evaluation(String txt,double num) { txt_eval=txt; num_eval=num; curDate=LocalDate.now(); } //empty constructor public Evaluation(){ curDate=LocalDate.now(); txt_eval=null; num_eval=0; } //getters public String getTxt_eval(){ return txt_eval; } public double getNum_eval(){ return num_eval; } //setters public void setTxt_eval(String s){ txt_eval=s; curDate=LocalDate.now(); } public void setNum_eval(double num){ num_eval=num; curDate=LocalDate.now(); } }
AnestisZotos/Accommodations-rating-platform
api/Evaluation.java
387
//ημερομηνία τελευταίας(πιο πρόσφατης)αξιολόγησης
line_comment
el
package api; import java.io.Serializable; import java.time.LocalDate; /** * Η κλάση αυτή αναπαριστά μια αξιολόγηση ενός καταλύματος * @author Anestis Zotos */ public class Evaluation implements Serializable { private String txt_eval; //αξιολόγηση σε μορφή κειμένου private double num_eval; //αξιολόγηση σε μορφή αριθμού private LocalDate curDate; //ημερομηνία τελευταίας(πιο<SUF> //constructor public Evaluation(String txt,double num) { txt_eval=txt; num_eval=num; curDate=LocalDate.now(); } //empty constructor public Evaluation(){ curDate=LocalDate.now(); txt_eval=null; num_eval=0; } //getters public String getTxt_eval(){ return txt_eval; } public double getNum_eval(){ return num_eval; } //setters public void setTxt_eval(String s){ txt_eval=s; curDate=LocalDate.now(); } public void setNum_eval(double num){ num_eval=num; curDate=LocalDate.now(); } }
1073_22
/* Όνομα: Άγγελος Τζώρτζης Α.Μ.: ice18390094 */ package netprog_project; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class BankAccountDao { public static Connection getConnection() { Connection conn = null; try { // Δημιουγρούμε σύνδεση στην βάση μας ανάλογα με ποιά βάση χρησιμοποιόυμε // και τα στοιχεία της. Class.forName("org.mariadb.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mariadb://localhost:4306/bank", "Tzortzis", "1234"); } catch (ClassNotFoundException | SQLException ex) { } return conn; } public static int addBankAccount(BankAccount bankAccount) { int status = 0; Connection conn = BankAccountDao.getConnection(); try { // Με την χρήση PreparedStatement που είναι μία ασφαλής μέθοδος, // περνάμε στην βάση μας τα στοιχεία που εισάγαμε απο το HTML αρχείο // και δώσαμε τιμές στο αντικέιμενο μας PreparedStatement ps = conn.prepareStatement("INSERT INTO bank_accounts(firstName, lastName, phoneNumber, email, accountBalance, active) VALUES (?, ?, ?, ?, ?, ?)"); ps.setString(1, bankAccount.getFirstName()); ps.setString(2, bankAccount.getLastName()); ps.setString(3, bankAccount.getPhoneNumber()); ps.setString(4, bankAccount.getEmail()); ps.setInt(5, bankAccount.getAccountBalance()); // Θεωρούμε ότι ο λογαριασμός όταν δημιουργείται είναι ενεργός. ps.setBoolean(6, true); // Εκτελούμε την εντολή της SQL. status = ps.executeUpdate(); conn.close(); } catch (SQLException ex) { } // Επιστρέφουμε το status (ορίζει αν πέτυχε η εντολή μας η όχι). return status; } public static int deposit(BankAccount bankAccount, int amount) { int status = 0; // Δημιουργία σύνδεσης ώστε να έχουμε πρόσβαση στην βάση μας. Connection conn = BankAccountDao.getConnection(); // Προσθέτουμε στον λογαριασμό το ποσό που ορίσαμε με το id του λογαριασμού που ορίσαμε. // εφόσον αυτός τηρεί της προυποθέσεις. (Είναι ενεργός και υπάρχει) try { PreparedStatement ps = conn.prepareStatement("UPDATE bank_accounts SET accountBalance=accountBalance+? WHERE accountId=? AND active = true"); ps.setInt(1, amount); ps.setInt(2, bankAccount.getAccountId()); status = ps.executeUpdate(); conn.close(); } catch (SQLException ex) { } return status; } public static int withdraw(BankAccount bankAccount, int amount) { int status = 0; Connection conn = BankAccountDao.getConnection(); // Αφαιρούμε από τον λογαριασμό το ποσό που ορίσαμε με το id του λογαριασμού που ορίσαμε, // εφόσον αυτός τηρεί της προυποθέσεις. (Είναι ενεργός, υπάρχει, και έχει τα απαραίτητα χρήματα). try { PreparedStatement ps = conn.prepareStatement("UPDATE bank_accounts SET accountBalance=accountBalance-? WHERE accountId=? AND active = true"); ps.setInt(1, amount); ps.setInt(2, bankAccount.getAccountId()); status = ps.executeUpdate(); conn.close(); } catch (SQLException ex) { } return status; } public static int transfer(BankAccount bankAccountSend, BankAccount bankAccountReceive, int amount) { int status = 0; Connection conn = BankAccountDao.getConnection(); try { // Αρχικά αφαιρούμε το ποσό απο τον λογαριασμό που θέλουμε να στείλει τα χρήματα. PreparedStatement ps = conn.prepareStatement("UPDATE bank_accounts SET accountBalance=accountBalance-? WHERE accountId=? AND active = true"); ps.setInt(1, amount); ps.setInt(2, bankAccountSend.getAccountId()); status = ps.executeUpdate(); // Εφόσον πετύχει αυτή η συναλλαγή το ποσό που αφαιρέθηκε απο τον λογαριασμό το προσθέτουμε στον άλλο. if (status != 0) { ps = conn.prepareStatement("UPDATE bank_accounts SET accountBalance=accountBalance+? WHERE accountId=? AND active = true"); ps.setInt(1, amount); ps.setInt(2, bankAccountReceive.getAccountId()); status = ps.executeUpdate(); } conn.close(); } catch (SQLException ex) { } // Εάν πετύχει αυτή η συναλλαγή θα μας επιστρέψει status = 1 η συνάρτηση. return status; } // Ενεργοποίηση λογαριασμόυ. public static int activate(BankAccount bankAccount) { int status = 0; Connection conn = BankAccountDao.getConnection(); try { // Ενεργοποιούμε μόνο αν είναι απενεργοποιημένος. PreparedStatement ps = conn.prepareStatement("UPDATE bank_accounts SET active=true WHERE accountId=? AND active=false"); ps.setInt(1, bankAccount.getAccountId()); status = ps.executeUpdate(); conn.close(); } catch (SQLException ex) { } return status; } // Απενεργοποίηση λογαριασμού. public static int deactivate(BankAccount bankAccount) { int status = 0; Connection conn = BankAccountDao.getConnection(); try { // Απενεργοποιούμε μόνο άν είναι ενεργοποιημένος. PreparedStatement ps = conn.prepareStatement("UPDATE bank_accounts SET active=false WHERE accountId=? AND active=true"); ps.setInt(1, bankAccount.getAccountId()); status = ps.executeUpdate(); conn.close(); } catch (SQLException ex) { } return status; } // Η παρακάτω συνάρτηση δέχεται ώς όρισμα έναν αριθμό λογαριασμού public static BankAccount getBankAccount(int accountId) { // Δημιουργία αντικειμένου ώστε να αποθηκεύσουμε τα στοιχεία μας. BankAccount bankAccount = new BankAccount(); Connection conn = BankAccountDao.getConnection(); try { // Εντολή SQL για την εμφάνιση όλων των στοιχείων της εγγραφής του αριθμού λογαριασμού. PreparedStatement ps = conn.prepareStatement("SELECT * FROM bank_accounts WHERE accountId=?"); ps.setInt(1, accountId); ResultSet rs = ps.executeQuery(); // Περνάμε όλα τα στοιχεία της εγγραφής στο αντικείμενο που δημιουργήσαμε πιο πάνω. if (rs.next()) { bankAccount.setAccountId(rs.getInt(1)); bankAccount.setFirstName(rs.getString(2)); bankAccount.setLastName(rs.getString(3)); bankAccount.setPhoneNumber(rs.getString(4)); bankAccount.setEmail(rs.getString(5)); bankAccount.setAccountBalance(rs.getInt(6)); bankAccount.setActive(rs.getBoolean(7)); } conn.close(); } catch (SQLException ex) { } return bankAccount; } // Eμφάνιση όλων των εγγραφών του πίνακα. public static List<BankAccount> getAllAccounts() { // Φτιάχνουμε αντικείμενο λίστα ώστε να αποθηκεύσουμε τον κάθε λογαριασμό. List<BankAccount> accountList = new ArrayList<>(); Connection conn = BankAccountDao.getConnection(); try { PreparedStatement ps = conn.prepareStatement("SELECT * FROM bank_accounts"); ResultSet rs = ps.executeQuery(); while (rs.next()) { // Φτιάχνουμε αντικείμο για να περάσουμε τα στοιχεία της εγγραφής σε ένα αντικείμενο. BankAccount bankAccount = new BankAccount(); bankAccount.setAccountId(rs.getInt(1)); bankAccount.setFirstName(rs.getString(2)); bankAccount.setLastName(rs.getString(3)); bankAccount.setPhoneNumber(rs.getString(4)); bankAccount.setEmail(rs.getString(5)); bankAccount.setAccountBalance(rs.getInt(6)); bankAccount.setActive(rs.getBoolean(7)); // Εφόσον περαστούν όλα τα στοιχεία αποθηκεύουμε το αντικείμενο στην λίστα. accountList.add(bankAccount); } conn.close(); } catch (SQLException ex) { } return accountList; } public static int deleteAccount(int accountId) { int status = 0; Connection conn = BankAccountDao.getConnection(); try { // Διαγραφή μίας εγγραφής της επιλογής μας. PreparedStatement ps = conn.prepareStatement("DELETE FROM bank_accounts WHERE accountId=?"); ps.setInt(1, accountId); status = ps.executeUpdate(); conn.close(); } catch (SQLException ex) { } return status; } }
Angelos-Tzortzis/University
Netprog_Project/src/java/netprog_project/BankAccountDao.java
3,067
// Εντολή SQL για την εμφάνιση όλων των στοιχείων της εγγραφής του αριθμού λογαριασμού.
line_comment
el
/* Όνομα: Άγγελος Τζώρτζης Α.Μ.: ice18390094 */ package netprog_project; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class BankAccountDao { public static Connection getConnection() { Connection conn = null; try { // Δημιουγρούμε σύνδεση στην βάση μας ανάλογα με ποιά βάση χρησιμοποιόυμε // και τα στοιχεία της. Class.forName("org.mariadb.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mariadb://localhost:4306/bank", "Tzortzis", "1234"); } catch (ClassNotFoundException | SQLException ex) { } return conn; } public static int addBankAccount(BankAccount bankAccount) { int status = 0; Connection conn = BankAccountDao.getConnection(); try { // Με την χρήση PreparedStatement που είναι μία ασφαλής μέθοδος, // περνάμε στην βάση μας τα στοιχεία που εισάγαμε απο το HTML αρχείο // και δώσαμε τιμές στο αντικέιμενο μας PreparedStatement ps = conn.prepareStatement("INSERT INTO bank_accounts(firstName, lastName, phoneNumber, email, accountBalance, active) VALUES (?, ?, ?, ?, ?, ?)"); ps.setString(1, bankAccount.getFirstName()); ps.setString(2, bankAccount.getLastName()); ps.setString(3, bankAccount.getPhoneNumber()); ps.setString(4, bankAccount.getEmail()); ps.setInt(5, bankAccount.getAccountBalance()); // Θεωρούμε ότι ο λογαριασμός όταν δημιουργείται είναι ενεργός. ps.setBoolean(6, true); // Εκτελούμε την εντολή της SQL. status = ps.executeUpdate(); conn.close(); } catch (SQLException ex) { } // Επιστρέφουμε το status (ορίζει αν πέτυχε η εντολή μας η όχι). return status; } public static int deposit(BankAccount bankAccount, int amount) { int status = 0; // Δημιουργία σύνδεσης ώστε να έχουμε πρόσβαση στην βάση μας. Connection conn = BankAccountDao.getConnection(); // Προσθέτουμε στον λογαριασμό το ποσό που ορίσαμε με το id του λογαριασμού που ορίσαμε. // εφόσον αυτός τηρεί της προυποθέσεις. (Είναι ενεργός και υπάρχει) try { PreparedStatement ps = conn.prepareStatement("UPDATE bank_accounts SET accountBalance=accountBalance+? WHERE accountId=? AND active = true"); ps.setInt(1, amount); ps.setInt(2, bankAccount.getAccountId()); status = ps.executeUpdate(); conn.close(); } catch (SQLException ex) { } return status; } public static int withdraw(BankAccount bankAccount, int amount) { int status = 0; Connection conn = BankAccountDao.getConnection(); // Αφαιρούμε από τον λογαριασμό το ποσό που ορίσαμε με το id του λογαριασμού που ορίσαμε, // εφόσον αυτός τηρεί της προυποθέσεις. (Είναι ενεργός, υπάρχει, και έχει τα απαραίτητα χρήματα). try { PreparedStatement ps = conn.prepareStatement("UPDATE bank_accounts SET accountBalance=accountBalance-? WHERE accountId=? AND active = true"); ps.setInt(1, amount); ps.setInt(2, bankAccount.getAccountId()); status = ps.executeUpdate(); conn.close(); } catch (SQLException ex) { } return status; } public static int transfer(BankAccount bankAccountSend, BankAccount bankAccountReceive, int amount) { int status = 0; Connection conn = BankAccountDao.getConnection(); try { // Αρχικά αφαιρούμε το ποσό απο τον λογαριασμό που θέλουμε να στείλει τα χρήματα. PreparedStatement ps = conn.prepareStatement("UPDATE bank_accounts SET accountBalance=accountBalance-? WHERE accountId=? AND active = true"); ps.setInt(1, amount); ps.setInt(2, bankAccountSend.getAccountId()); status = ps.executeUpdate(); // Εφόσον πετύχει αυτή η συναλλαγή το ποσό που αφαιρέθηκε απο τον λογαριασμό το προσθέτουμε στον άλλο. if (status != 0) { ps = conn.prepareStatement("UPDATE bank_accounts SET accountBalance=accountBalance+? WHERE accountId=? AND active = true"); ps.setInt(1, amount); ps.setInt(2, bankAccountReceive.getAccountId()); status = ps.executeUpdate(); } conn.close(); } catch (SQLException ex) { } // Εάν πετύχει αυτή η συναλλαγή θα μας επιστρέψει status = 1 η συνάρτηση. return status; } // Ενεργοποίηση λογαριασμόυ. public static int activate(BankAccount bankAccount) { int status = 0; Connection conn = BankAccountDao.getConnection(); try { // Ενεργοποιούμε μόνο αν είναι απενεργοποιημένος. PreparedStatement ps = conn.prepareStatement("UPDATE bank_accounts SET active=true WHERE accountId=? AND active=false"); ps.setInt(1, bankAccount.getAccountId()); status = ps.executeUpdate(); conn.close(); } catch (SQLException ex) { } return status; } // Απενεργοποίηση λογαριασμού. public static int deactivate(BankAccount bankAccount) { int status = 0; Connection conn = BankAccountDao.getConnection(); try { // Απενεργοποιούμε μόνο άν είναι ενεργοποιημένος. PreparedStatement ps = conn.prepareStatement("UPDATE bank_accounts SET active=false WHERE accountId=? AND active=true"); ps.setInt(1, bankAccount.getAccountId()); status = ps.executeUpdate(); conn.close(); } catch (SQLException ex) { } return status; } // Η παρακάτω συνάρτηση δέχεται ώς όρισμα έναν αριθμό λογαριασμού public static BankAccount getBankAccount(int accountId) { // Δημιουργία αντικειμένου ώστε να αποθηκεύσουμε τα στοιχεία μας. BankAccount bankAccount = new BankAccount(); Connection conn = BankAccountDao.getConnection(); try { // Εντολή SQL<SUF> PreparedStatement ps = conn.prepareStatement("SELECT * FROM bank_accounts WHERE accountId=?"); ps.setInt(1, accountId); ResultSet rs = ps.executeQuery(); // Περνάμε όλα τα στοιχεία της εγγραφής στο αντικείμενο που δημιουργήσαμε πιο πάνω. if (rs.next()) { bankAccount.setAccountId(rs.getInt(1)); bankAccount.setFirstName(rs.getString(2)); bankAccount.setLastName(rs.getString(3)); bankAccount.setPhoneNumber(rs.getString(4)); bankAccount.setEmail(rs.getString(5)); bankAccount.setAccountBalance(rs.getInt(6)); bankAccount.setActive(rs.getBoolean(7)); } conn.close(); } catch (SQLException ex) { } return bankAccount; } // Eμφάνιση όλων των εγγραφών του πίνακα. public static List<BankAccount> getAllAccounts() { // Φτιάχνουμε αντικείμενο λίστα ώστε να αποθηκεύσουμε τον κάθε λογαριασμό. List<BankAccount> accountList = new ArrayList<>(); Connection conn = BankAccountDao.getConnection(); try { PreparedStatement ps = conn.prepareStatement("SELECT * FROM bank_accounts"); ResultSet rs = ps.executeQuery(); while (rs.next()) { // Φτιάχνουμε αντικείμο για να περάσουμε τα στοιχεία της εγγραφής σε ένα αντικείμενο. BankAccount bankAccount = new BankAccount(); bankAccount.setAccountId(rs.getInt(1)); bankAccount.setFirstName(rs.getString(2)); bankAccount.setLastName(rs.getString(3)); bankAccount.setPhoneNumber(rs.getString(4)); bankAccount.setEmail(rs.getString(5)); bankAccount.setAccountBalance(rs.getInt(6)); bankAccount.setActive(rs.getBoolean(7)); // Εφόσον περαστούν όλα τα στοιχεία αποθηκεύουμε το αντικείμενο στην λίστα. accountList.add(bankAccount); } conn.close(); } catch (SQLException ex) { } return accountList; } public static int deleteAccount(int accountId) { int status = 0; Connection conn = BankAccountDao.getConnection(); try { // Διαγραφή μίας εγγραφής της επιλογής μας. PreparedStatement ps = conn.prepareStatement("DELETE FROM bank_accounts WHERE accountId=?"); ps.setInt(1, accountId); status = ps.executeUpdate(); conn.close(); } catch (SQLException ex) { } return status; } }
125_16
import java.util.Scanner; public class MainUnitConverter { public static void main(String[] args) { Title(); MainList(); //RandomValue(); //DataStorage(); Currency(); TimeFromSeconds(); EightTimes(); AboutApp(); /* ----- sos opos ch5 - CalculatorApp.java ---- switch (choice) { case '1': return OneDimension(); case '2': return TwoEnergy(); case '3': return DataStorage(); case '4': return FourMovement(); case '5': return FiveHealth(); case '6': return SixEngineering(); case '7': return SevenCurrency(); case '8': return ; case '9': return case '10': return ; case '11': return AboutApp(); default: System.out.println("Error. Try again ..."); isError = true; return 0; public static void main(String[] args) { Scanner in = new Scanner(System.in); int choice = 0; // se kathe epitimiti timh xanabgazei to menu mexri 0 gia exodo!!!!!! do { System.out.println(" CRUD (0 gia exodo):"); System.out.println("1. (insert) "); System.out.println("2. (update) "); System.out.println("3. (delete) "); System.out.println("4. (select) "); choice = in.nextInt(); } while (choice != 0); System.out.println("Thanks!"); } */ } public static void Title(){ System.out.println("\n********************************************************************"); System.out.println("* Καλώς Όρισες στην Ενοποιημένη Εφαρμογή Μετατροπής Μονάδων *"); System.out.println("* Καλώς Όρισες στην ΕΝΟΠΟΙΗΜΕΝΗ ΕΦΑΡΜΟΓΗ ΜΕΤΑΤΡΟΠΗΣ ΜΟΝΑΔΩΝ *"); System.out.println("*********************************************************************"); } public static void MainList(){ System.out.println("+---------------------------------------------------------------------+"); System.out.println("| Ανά Οικογένεια / ανά Τύπο Μονάδας |"); System.out.println("+---------------------------------------------------------------------+"); System.out.println("|1. Διάσταση [ Επιφάνεια, Μήκος, Όγκος ] |"); System.out.println("|2. Ενέργεια [ Ενέργεια, Θερμοκρασία, Ισχύς ] |"); System.out.println("|3. ΕπιστήμηΥπολογιστών [ Αποθήκευση δεδομένων ] |"); System.out.println("|4. Κίνηση [ Επιτάχυνση, Ταχύτητα, Ταχύτητα ανέμου ] |"); System.out.println("|5. Υγεία [Βάρος, Δείκτης Μάζας Σώματος ] |"); System.out.println("|6. Μηχανική [Βάρος, Δύναμη, Ροπή ] |"); System.out.println("|7. Νόμισμα [ Δολλάριο / Λίρα / Ευρώ / Γιέν ] |"); System.out.println("|8. Ώρα [ Ζώνες χρόνου, Ώρα ] |"); System.out.println("+---------------------------------------------------------------------+"); System.out.println("|9. ΕΞΟΔΟΣ ΕΦΑΡΜΟΓΗΣ |"); System.out.println("|10. Δημιουργός |"); System.out.println("|11. Περί Εφαρμογής... |"); System.out.println("+---------------------------------------------------------------------+"); } public static void AboutApp(){ System.out.println(" Η εφαρμογή δημιουργήθηκε για εκπαιδευτικούς λόγους για λόγους αυτοεξέλιξης"); System.out.println("και αυτοβελτίωσης των υπαρχόντων γνώσεών μου, όπου και κατά το τρέχων διάστημα"); System.out.println("είμαι σπουδαστής του ΚΕ.ΔΙ.ΒΙ.Μ. του Οικονομικού Πανεπιστήμιου Αθηνών "); System.out.println("στο πρόγραμμα Coding Factory. "); System.out.println("\nΤο πρόγραμμα θα ανανεώνετε και θα βελτιώνετε σύμφωνα με τις προσεχείς γνώσεις "); System.out.println("που θα λαμβάνω κατά την διάρκεια του άνωθεν τρέχοντος προγράμματος."); System.out.println("\nΣκοπός του προγράμματος είναι η υποθετική συνεργασία με συνάδελφους προγραμματιστές"); System.out.println("οπότε και θα πρέπει να «τοποθετώ» ουσιαστικά σχόλια στον κώδικά μου που θα μπορώ να"); System.out.println("ξαναθυμάμαι και εγώ σε βάθος χρόνου και να είναι κατανοητά και στους υποτιθέμενους "); System.out.println("συνάδελφους σε περίπτωση collaboration οποιουδήποτε project σε team work."); System.out.println("\nΑποσκοπεί επίσης και σε μια πιθανή επίδειξη γνώσεων και δεξιοτήτων μου στην τρέχουσα"); System.out.println("γλώσσα δημιουργίας του project για οποιονδήποτε πιθανό εργοδότη μου."); System.out.println("\n_________________\nH εφαρμογή δεν αποτελεί πλήρη οδηγό Μετατροπής Μονάδων, παρ' όλα αυτά όμως,"); System.out.println("είναι ελεγμένο και θα είναι πάντα υπό έλεγχο κατά την πρόοδο του ώστε να διασφαλίζω"); System.out.println("-σύμφωνα με τους ελέγχους μου- την ορθότητα και ακρίβειά του."); System.out.println("\nΤο πρόγραμμα καλύπτει της τεχνικές απαιτήσεις επαναληψιμότητας που καλά είναι να έχει"); System.out.println("ένας κώδικας και τους ελέγχους αποτελεσματικότητας σύμφωνα με προβλεπόμενα αποτελέσματα,"); System.out.println("ακολουθώντας πάντα και την βέλτιστη απλότητα και κατανόηση στην σύνταξή του!"); System.out.println("\n\nΟ Δημιουργός\n___________________\nΑντωνίου Ιωάννης"); } public static void RandomValue() { int intValue = (int) (Math.random() * 16) + 1; float floatValue = (float) (Math.random() * 6) + 1; System.out.printf("(%d, %.3f)", intValue, floatValue); } public static void OneDimension(){ Title(); //ypomenou oikogenias θα υπαχει επιλογη για να γυρισει στον αρχικο πινακα } public static void Area(){} public static void Length(){} public static void Volume (){} public static void TwoEnergy(){ Title(); //ypomenou oikogenias θα υπαχει επιλογη για να γυρισει στον αρχικο πινακα } public static void Temperature(){ /* Τ(κ) = =τ(c)+ 2731,15 & T(k)= (5 * ( valueFahrenheit - 32 ) / 9) + 273,15 */ Scanner Temper = new Scanner(System.in); int valueFahrenheit = 0; System.out.print("Δώσε την τιμή θερμοκρασίας Fahrenheit σε ακέραια μορφή: "); valueFahrenheit = Temper.nextInt(); int valueCelsiou = 0; double valueKelvin = 0.0; final int CELSIOU_CONVERSION = 5 * (valueFahrenheit - 32) / 9; final double KELVIN_CONVERSION = (5.0 * (valueFahrenheit - 32.0) / 9.0) + 273.15; valueCelsiou = CELSIOU_CONVERSION; valueKelvin = KELVIN_CONVERSION; System.out.printf("\nΈδωσες την τιμή %d βαθμούς Fahrenheit που ισοδυναμεί με %d βαθμούς Κελσίου \n", valueFahrenheit, valueCelsiou); System.out.println("\n\nΟι δοκιμές για τον έλεγχο ορθότητας του προγράμματος έγινε με την υποστήιξη της ιστοσελίδας\n https://www.metric-conversions.org/el/temperature/fahrenheit-to-celsius.htm"); System.out.printf("\nEND OF PROGRAM Temperature \n\n"); } public static void DataStorage(){ /* χρησιμο για ... System.out.printf("Type: %s, Size: %d bits, Min: %,d, Max: %,d\n", Integer.TYPE, Integer.SIZE, Integer.MIN_VALUE, Integer.MAX_VALUE); System.out.printf("Type: %s, Size: %d bits, Min: %d, Max: %d\n", Byte.TYPE, Byte.SIZE, Byte.MIN_VALUE, Byte.MAX_VALUE); System.out.printf("Type: %s, Size: %d bits, Min: %d, Max: %d\n", Short.TYPE, Short.SIZE, Short.MIN_VALUE, Short.MAX_VALUE); System.out.printf("Type: %s, Size: %d bits, Min: %,d, Max: %,d\n", Long.TYPE, Long.SIZE, Long.MIN_VALUE, Long.MAX_VALUE); */ Scanner SizeData = new Scanner(System.in); int fetchSizeData = 0; System.out.print("Δώσε το μεγεθος σε ακέραια μορφή: "); fetchSizeData = SizeData.nextInt(); // public static void PowerApp() { //Scanner in = new Scanner(System.in); int base = 0; int power = 0; int result = 1; int i = 1; System.out.println("Please insert base, power"); base = in.nextInt(); power = in.nextInt(); while (i <= power) { result *= base; // result = result * base; i++; } System.out.printf("%d ^ %d = %,d\n", base, power, result); // edv pio kato dino karfotes times System.out.printf("2 ^ 8 = %d", (int) Math.pow(2, 8)); } public static void FourMovement(){ Title(); //ypomenou oikogenias θα υπαχει επιλογη για να γυρισει στον αρχικο πινακα } public static void Movement(){} public static void Acceleration(){} public static void Speed(){} public static void WindSpeed(){} public static void FiveHealth(){ Title(); //ypomenou oikogenias θα υπαχει επιλογη για να γυρισει στον αρχικο πινακα } public static void Weight(){ // github - ch3 - GradesApp.java // ch3 TernaryOpApp.java } public static void BodyMassIndex(){} public static void SixEngineering(){ Title(); //ypomenou oikogenias θα υπαχει επιλογη για να γυρισει στον αρχικο πινακα } public static void Weight(){} public static void Force(){} public static void Torque(){} public static void SevenCurrency(){ Title(); Scanner giveEuros = new Scanner(System.in); double eurosEUR = 0.00, dollarsUSD = 0.00, liraGBP = 0.00; double fragoCHF = 0.00, yienJPY = 0.00, youanCNY = 0.00, roubliRUB = 0.00; // Ισοτιμίες νομισμάτων την ημερα Δευτέρα 29 Απριλίου Πηγή απο https://www.synallagma.gr/ final double USD_PARITY = 1.0723; // Δολλάριο ΗΠΑ (USD) final double GLR_PARITY = 0.8535; // Λίρα Αγγλίας (GBP) final double CHF_PARITY = 0.9761; // Φράγκο Ελβετίας (CHF) final double JPY_PARITY = 167.41; // Γιέν Ιαπωνίας (JPY) final double CNY_PARITY = 7.7622; // Γουάν Κίνας (CNY) final double RUB_PARITY = 100.81; // Ρούβλι Ρωσίας (RUB) System.out.print("\nΔώστε παρακαλώ το ποσό σε Ευρώ: "); // εδω θα ενημερωσουμε το συστημα οτι θα δεχτει απο χρηστη δεδομένα eurosEUR = giveEuros.nextDouble(); dollarsUSD = eurosEUR * USD_PARITY; /* για να δουμε ποσα Δολλάριο ΗΠΑ (USD) ειναι */ liraGBP = eurosEUR * GLR_PARITY; /* για να δουμε ποσα Λίρα Αγγλίας (GBP) ειναι */ fragoCHF = eurosEUR * CHF_PARITY; /* για να δουμε ποσα Φράγκο Ελβετίας (CHF) ειναι */ yienJPY = eurosEUR * JPY_PARITY; /* για να δουμε ποσα Γιέν Ιαπωνίας (JPY) ειναι */ youanCNY = eurosEUR * CNY_PARITY; /* για να δουμε ποσα Γουάν Κίνας (CNY) ειναι */ roubliRUB = eurosEUR * RUB_PARITY; /* για να δουμε ποσα Ρούβλι Ρωσίας (RUB) ειναι */ System.out.printf("Έδωσες το ποσό των [ %.2f ].\nΚατά την τρέχουσα ημέρα η ισοτιμία του με τα κάτωθι νομίσματα είναι:\n", eurosEUR); System.out.printf("[ %.2f euros ] = [ %.4f ] Δολλάριο ΗΠΑ (USD)\n", eurosEUR, dollarsUSD); System.out.printf("\n[ %.2f euros ] = [ %.4f ] Λίρα Αγγλίας (GBP)\n", eurosEUR, liraGBP); System.out.printf("\n[ %.2f euros ] = [ %.4f ] Φράγκο Ελβετίας (CHF)\n", eurosEUR, fragoCHF); System.out.printf("\n[ %.2f euros ] = [ %.4f ] Γιέν Ιαπωνίας (JPY)\n", eurosEUR, yienJPY); System.out.printf("\n[ %.2f euros ] = [ %.4f ] Γουάν Κίνας (CNY)\n", eurosEUR, youanCNY); System.out.printf("\n[ %.2f euros ] = [ %.4f ] Ρούβλι Ρωσίας (RUB)\n", eurosEUR, roubliRUB); System.out.println("\nEND OF PROGRAM CURRENCY \n"); } public static void Dollar(){} public static void PoundEuroYen(){} public static void EightTimes(){ Title(); // υπομενου οικογενειας } public static void TimeZones(){} public static void Time(){ public static void TimeFromMinutes() { Scanner getMinutes = new Scanner(System.in); // μετα την επιλογη του θα δινω τυχαιο αριθμο που θα κανει ξανα τις πραξεις // σε ms, sec, min, hour, day, week, month, year, decade int RandomMinutes = (int) (Math.random() * 999999) + 10000; // min 10.000 - max 999.999 final int MS_PER_SECS = 1000; final int SECS_PER_MINUTE = 60; final int SECS_PER_HOUR = 60 * 60; final int SECS_PER_DAY = 24 * 60 * 60; int ms = 0; int days = 0; int hours = 0; int minutes = 0; int totalSeconds = 0; int remainingSeconds = 0; System.out.print("Δώσε παρακαλώ την διάρκεια του χρόνου σε Λεπτά ---> "); fetchMinutes = getMinutes.nextInt(); days = fetchMinutes / SECS_PER_DAY; remainingSeconds = fetchMinutes % SECS_PER_DAY; hours = remainingSeconds / SECS_PER_HOUR; remainingSeconds = remainingSeconds % SECS_PER_HOUR; minutes = remainingSeconds / SECS_PER_MINUTE; remainingSeconds = remainingSeconds % SECS_PER_MINUTE; System.out.printf("Έδωσες διάρκεια χρόνου σε Δευτερόλεπτα: -- %,d --\nΑυτή είναι [ %d ] Ημέρες, \n[ %02d ] Ώρες, [ %02d ] Λεπτά και [ %02d ] Δευτερόλεπτα.\n\n", totalSeconds, days, hours, minutes, remainingSeconds); System.out.printf("\n--------------\nΤυχαία επιλογή χρόνου σε Λεπτά [ %d ] ", RandomMinutes); days_r = RandomMinutes / SECS_PER_DAY; remainingSeconds_r = RandomMinutes % SECS_PER_DAY; hours_s = remainingSeconds / SECS_PER_HOUR; remainingSeconds_r = remainingSeconds_r % SECS_PER_HOUR; minutes_r = remainingSeconds_r / SECS_PER_MINUTE; remainingSeconds_r = remainingSeconds_r % SECS_PER_MINUTE; System.out.printf("Έδωσες διάρκεια χρόνου σε Lεπτα: -- %,d --\nΑυτή είναι [ %d ] Ημέρες, \n[ %02d ] Ώρες, [ %02d ] Λεπτά και [ %02d ] Δευτερόλεπτα.\n\n", RandomMinutes, days_r, hours_r, minutes_r, remainingSeconds_r); System.out.println("\nEND OF PROGRAM TimeFromSeconds \n\n"); } }
AntoniouIoannis/new-demo
MainUnitConverter.java
6,199
// Φράγκο Ελβετίας (CHF)
line_comment
el
import java.util.Scanner; public class MainUnitConverter { public static void main(String[] args) { Title(); MainList(); //RandomValue(); //DataStorage(); Currency(); TimeFromSeconds(); EightTimes(); AboutApp(); /* ----- sos opos ch5 - CalculatorApp.java ---- switch (choice) { case '1': return OneDimension(); case '2': return TwoEnergy(); case '3': return DataStorage(); case '4': return FourMovement(); case '5': return FiveHealth(); case '6': return SixEngineering(); case '7': return SevenCurrency(); case '8': return ; case '9': return case '10': return ; case '11': return AboutApp(); default: System.out.println("Error. Try again ..."); isError = true; return 0; public static void main(String[] args) { Scanner in = new Scanner(System.in); int choice = 0; // se kathe epitimiti timh xanabgazei to menu mexri 0 gia exodo!!!!!! do { System.out.println(" CRUD (0 gia exodo):"); System.out.println("1. (insert) "); System.out.println("2. (update) "); System.out.println("3. (delete) "); System.out.println("4. (select) "); choice = in.nextInt(); } while (choice != 0); System.out.println("Thanks!"); } */ } public static void Title(){ System.out.println("\n********************************************************************"); System.out.println("* Καλώς Όρισες στην Ενοποιημένη Εφαρμογή Μετατροπής Μονάδων *"); System.out.println("* Καλώς Όρισες στην ΕΝΟΠΟΙΗΜΕΝΗ ΕΦΑΡΜΟΓΗ ΜΕΤΑΤΡΟΠΗΣ ΜΟΝΑΔΩΝ *"); System.out.println("*********************************************************************"); } public static void MainList(){ System.out.println("+---------------------------------------------------------------------+"); System.out.println("| Ανά Οικογένεια / ανά Τύπο Μονάδας |"); System.out.println("+---------------------------------------------------------------------+"); System.out.println("|1. Διάσταση [ Επιφάνεια, Μήκος, Όγκος ] |"); System.out.println("|2. Ενέργεια [ Ενέργεια, Θερμοκρασία, Ισχύς ] |"); System.out.println("|3. ΕπιστήμηΥπολογιστών [ Αποθήκευση δεδομένων ] |"); System.out.println("|4. Κίνηση [ Επιτάχυνση, Ταχύτητα, Ταχύτητα ανέμου ] |"); System.out.println("|5. Υγεία [Βάρος, Δείκτης Μάζας Σώματος ] |"); System.out.println("|6. Μηχανική [Βάρος, Δύναμη, Ροπή ] |"); System.out.println("|7. Νόμισμα [ Δολλάριο / Λίρα / Ευρώ / Γιέν ] |"); System.out.println("|8. Ώρα [ Ζώνες χρόνου, Ώρα ] |"); System.out.println("+---------------------------------------------------------------------+"); System.out.println("|9. ΕΞΟΔΟΣ ΕΦΑΡΜΟΓΗΣ |"); System.out.println("|10. Δημιουργός |"); System.out.println("|11. Περί Εφαρμογής... |"); System.out.println("+---------------------------------------------------------------------+"); } public static void AboutApp(){ System.out.println(" Η εφαρμογή δημιουργήθηκε για εκπαιδευτικούς λόγους για λόγους αυτοεξέλιξης"); System.out.println("και αυτοβελτίωσης των υπαρχόντων γνώσεών μου, όπου και κατά το τρέχων διάστημα"); System.out.println("είμαι σπουδαστής του ΚΕ.ΔΙ.ΒΙ.Μ. του Οικονομικού Πανεπιστήμιου Αθηνών "); System.out.println("στο πρόγραμμα Coding Factory. "); System.out.println("\nΤο πρόγραμμα θα ανανεώνετε και θα βελτιώνετε σύμφωνα με τις προσεχείς γνώσεις "); System.out.println("που θα λαμβάνω κατά την διάρκεια του άνωθεν τρέχοντος προγράμματος."); System.out.println("\nΣκοπός του προγράμματος είναι η υποθετική συνεργασία με συνάδελφους προγραμματιστές"); System.out.println("οπότε και θα πρέπει να «τοποθετώ» ουσιαστικά σχόλια στον κώδικά μου που θα μπορώ να"); System.out.println("ξαναθυμάμαι και εγώ σε βάθος χρόνου και να είναι κατανοητά και στους υποτιθέμενους "); System.out.println("συνάδελφους σε περίπτωση collaboration οποιουδήποτε project σε team work."); System.out.println("\nΑποσκοπεί επίσης και σε μια πιθανή επίδειξη γνώσεων και δεξιοτήτων μου στην τρέχουσα"); System.out.println("γλώσσα δημιουργίας του project για οποιονδήποτε πιθανό εργοδότη μου."); System.out.println("\n_________________\nH εφαρμογή δεν αποτελεί πλήρη οδηγό Μετατροπής Μονάδων, παρ' όλα αυτά όμως,"); System.out.println("είναι ελεγμένο και θα είναι πάντα υπό έλεγχο κατά την πρόοδο του ώστε να διασφαλίζω"); System.out.println("-σύμφωνα με τους ελέγχους μου- την ορθότητα και ακρίβειά του."); System.out.println("\nΤο πρόγραμμα καλύπτει της τεχνικές απαιτήσεις επαναληψιμότητας που καλά είναι να έχει"); System.out.println("ένας κώδικας και τους ελέγχους αποτελεσματικότητας σύμφωνα με προβλεπόμενα αποτελέσματα,"); System.out.println("ακολουθώντας πάντα και την βέλτιστη απλότητα και κατανόηση στην σύνταξή του!"); System.out.println("\n\nΟ Δημιουργός\n___________________\nΑντωνίου Ιωάννης"); } public static void RandomValue() { int intValue = (int) (Math.random() * 16) + 1; float floatValue = (float) (Math.random() * 6) + 1; System.out.printf("(%d, %.3f)", intValue, floatValue); } public static void OneDimension(){ Title(); //ypomenou oikogenias θα υπαχει επιλογη για να γυρισει στον αρχικο πινακα } public static void Area(){} public static void Length(){} public static void Volume (){} public static void TwoEnergy(){ Title(); //ypomenou oikogenias θα υπαχει επιλογη για να γυρισει στον αρχικο πινακα } public static void Temperature(){ /* Τ(κ) = =τ(c)+ 2731,15 & T(k)= (5 * ( valueFahrenheit - 32 ) / 9) + 273,15 */ Scanner Temper = new Scanner(System.in); int valueFahrenheit = 0; System.out.print("Δώσε την τιμή θερμοκρασίας Fahrenheit σε ακέραια μορφή: "); valueFahrenheit = Temper.nextInt(); int valueCelsiou = 0; double valueKelvin = 0.0; final int CELSIOU_CONVERSION = 5 * (valueFahrenheit - 32) / 9; final double KELVIN_CONVERSION = (5.0 * (valueFahrenheit - 32.0) / 9.0) + 273.15; valueCelsiou = CELSIOU_CONVERSION; valueKelvin = KELVIN_CONVERSION; System.out.printf("\nΈδωσες την τιμή %d βαθμούς Fahrenheit που ισοδυναμεί με %d βαθμούς Κελσίου \n", valueFahrenheit, valueCelsiou); System.out.println("\n\nΟι δοκιμές για τον έλεγχο ορθότητας του προγράμματος έγινε με την υποστήιξη της ιστοσελίδας\n https://www.metric-conversions.org/el/temperature/fahrenheit-to-celsius.htm"); System.out.printf("\nEND OF PROGRAM Temperature \n\n"); } public static void DataStorage(){ /* χρησιμο για ... System.out.printf("Type: %s, Size: %d bits, Min: %,d, Max: %,d\n", Integer.TYPE, Integer.SIZE, Integer.MIN_VALUE, Integer.MAX_VALUE); System.out.printf("Type: %s, Size: %d bits, Min: %d, Max: %d\n", Byte.TYPE, Byte.SIZE, Byte.MIN_VALUE, Byte.MAX_VALUE); System.out.printf("Type: %s, Size: %d bits, Min: %d, Max: %d\n", Short.TYPE, Short.SIZE, Short.MIN_VALUE, Short.MAX_VALUE); System.out.printf("Type: %s, Size: %d bits, Min: %,d, Max: %,d\n", Long.TYPE, Long.SIZE, Long.MIN_VALUE, Long.MAX_VALUE); */ Scanner SizeData = new Scanner(System.in); int fetchSizeData = 0; System.out.print("Δώσε το μεγεθος σε ακέραια μορφή: "); fetchSizeData = SizeData.nextInt(); // public static void PowerApp() { //Scanner in = new Scanner(System.in); int base = 0; int power = 0; int result = 1; int i = 1; System.out.println("Please insert base, power"); base = in.nextInt(); power = in.nextInt(); while (i <= power) { result *= base; // result = result * base; i++; } System.out.printf("%d ^ %d = %,d\n", base, power, result); // edv pio kato dino karfotes times System.out.printf("2 ^ 8 = %d", (int) Math.pow(2, 8)); } public static void FourMovement(){ Title(); //ypomenou oikogenias θα υπαχει επιλογη για να γυρισει στον αρχικο πινακα } public static void Movement(){} public static void Acceleration(){} public static void Speed(){} public static void WindSpeed(){} public static void FiveHealth(){ Title(); //ypomenou oikogenias θα υπαχει επιλογη για να γυρισει στον αρχικο πινακα } public static void Weight(){ // github - ch3 - GradesApp.java // ch3 TernaryOpApp.java } public static void BodyMassIndex(){} public static void SixEngineering(){ Title(); //ypomenou oikogenias θα υπαχει επιλογη για να γυρισει στον αρχικο πινακα } public static void Weight(){} public static void Force(){} public static void Torque(){} public static void SevenCurrency(){ Title(); Scanner giveEuros = new Scanner(System.in); double eurosEUR = 0.00, dollarsUSD = 0.00, liraGBP = 0.00; double fragoCHF = 0.00, yienJPY = 0.00, youanCNY = 0.00, roubliRUB = 0.00; // Ισοτιμίες νομισμάτων την ημερα Δευτέρα 29 Απριλίου Πηγή απο https://www.synallagma.gr/ final double USD_PARITY = 1.0723; // Δολλάριο ΗΠΑ (USD) final double GLR_PARITY = 0.8535; // Λίρα Αγγλίας (GBP) final double CHF_PARITY = 0.9761; // Φράγκο Ελβετίας<SUF> final double JPY_PARITY = 167.41; // Γιέν Ιαπωνίας (JPY) final double CNY_PARITY = 7.7622; // Γουάν Κίνας (CNY) final double RUB_PARITY = 100.81; // Ρούβλι Ρωσίας (RUB) System.out.print("\nΔώστε παρακαλώ το ποσό σε Ευρώ: "); // εδω θα ενημερωσουμε το συστημα οτι θα δεχτει απο χρηστη δεδομένα eurosEUR = giveEuros.nextDouble(); dollarsUSD = eurosEUR * USD_PARITY; /* για να δουμε ποσα Δολλάριο ΗΠΑ (USD) ειναι */ liraGBP = eurosEUR * GLR_PARITY; /* για να δουμε ποσα Λίρα Αγγλίας (GBP) ειναι */ fragoCHF = eurosEUR * CHF_PARITY; /* για να δουμε ποσα Φράγκο Ελβετίας (CHF) ειναι */ yienJPY = eurosEUR * JPY_PARITY; /* για να δουμε ποσα Γιέν Ιαπωνίας (JPY) ειναι */ youanCNY = eurosEUR * CNY_PARITY; /* για να δουμε ποσα Γουάν Κίνας (CNY) ειναι */ roubliRUB = eurosEUR * RUB_PARITY; /* για να δουμε ποσα Ρούβλι Ρωσίας (RUB) ειναι */ System.out.printf("Έδωσες το ποσό των [ %.2f ].\nΚατά την τρέχουσα ημέρα η ισοτιμία του με τα κάτωθι νομίσματα είναι:\n", eurosEUR); System.out.printf("[ %.2f euros ] = [ %.4f ] Δολλάριο ΗΠΑ (USD)\n", eurosEUR, dollarsUSD); System.out.printf("\n[ %.2f euros ] = [ %.4f ] Λίρα Αγγλίας (GBP)\n", eurosEUR, liraGBP); System.out.printf("\n[ %.2f euros ] = [ %.4f ] Φράγκο Ελβετίας (CHF)\n", eurosEUR, fragoCHF); System.out.printf("\n[ %.2f euros ] = [ %.4f ] Γιέν Ιαπωνίας (JPY)\n", eurosEUR, yienJPY); System.out.printf("\n[ %.2f euros ] = [ %.4f ] Γουάν Κίνας (CNY)\n", eurosEUR, youanCNY); System.out.printf("\n[ %.2f euros ] = [ %.4f ] Ρούβλι Ρωσίας (RUB)\n", eurosEUR, roubliRUB); System.out.println("\nEND OF PROGRAM CURRENCY \n"); } public static void Dollar(){} public static void PoundEuroYen(){} public static void EightTimes(){ Title(); // υπομενου οικογενειας } public static void TimeZones(){} public static void Time(){ public static void TimeFromMinutes() { Scanner getMinutes = new Scanner(System.in); // μετα την επιλογη του θα δινω τυχαιο αριθμο που θα κανει ξανα τις πραξεις // σε ms, sec, min, hour, day, week, month, year, decade int RandomMinutes = (int) (Math.random() * 999999) + 10000; // min 10.000 - max 999.999 final int MS_PER_SECS = 1000; final int SECS_PER_MINUTE = 60; final int SECS_PER_HOUR = 60 * 60; final int SECS_PER_DAY = 24 * 60 * 60; int ms = 0; int days = 0; int hours = 0; int minutes = 0; int totalSeconds = 0; int remainingSeconds = 0; System.out.print("Δώσε παρακαλώ την διάρκεια του χρόνου σε Λεπτά ---> "); fetchMinutes = getMinutes.nextInt(); days = fetchMinutes / SECS_PER_DAY; remainingSeconds = fetchMinutes % SECS_PER_DAY; hours = remainingSeconds / SECS_PER_HOUR; remainingSeconds = remainingSeconds % SECS_PER_HOUR; minutes = remainingSeconds / SECS_PER_MINUTE; remainingSeconds = remainingSeconds % SECS_PER_MINUTE; System.out.printf("Έδωσες διάρκεια χρόνου σε Δευτερόλεπτα: -- %,d --\nΑυτή είναι [ %d ] Ημέρες, \n[ %02d ] Ώρες, [ %02d ] Λεπτά και [ %02d ] Δευτερόλεπτα.\n\n", totalSeconds, days, hours, minutes, remainingSeconds); System.out.printf("\n--------------\nΤυχαία επιλογή χρόνου σε Λεπτά [ %d ] ", RandomMinutes); days_r = RandomMinutes / SECS_PER_DAY; remainingSeconds_r = RandomMinutes % SECS_PER_DAY; hours_s = remainingSeconds / SECS_PER_HOUR; remainingSeconds_r = remainingSeconds_r % SECS_PER_HOUR; minutes_r = remainingSeconds_r / SECS_PER_MINUTE; remainingSeconds_r = remainingSeconds_r % SECS_PER_MINUTE; System.out.printf("Έδωσες διάρκεια χρόνου σε Lεπτα: -- %,d --\nΑυτή είναι [ %d ] Ημέρες, \n[ %02d ] Ώρες, [ %02d ] Λεπτά και [ %02d ] Δευτερόλεπτα.\n\n", RandomMinutes, days_r, hours_r, minutes_r, remainingSeconds_r); System.out.println("\nEND OF PROGRAM TimeFromSeconds \n\n"); } }
7411_0
/*Αντιστοιχεί στον οργανισμό που υποστηρίζει το σύστημα donation.*/ import java.util.ArrayList; class Organization { private String name; private Admin admin; private ArrayList<Entity> entityList = new ArrayList<Entity>(); private ArrayList<Donator> donatorList = new ArrayList<Donator>(); private ArrayList<Beneficiary> beneficiaryList = new ArrayList<Beneficiary>(); private RequestDonationList currentDonations = new RequestDonationList(); Organization(){} Organization(String name) { this.name = name; ArrayList<Entity> entityList = new ArrayList<Entity>(); ArrayList<Donator> donatorList = new ArrayList<Donator>(); ArrayList<Beneficiary> beneficiaryList = new ArrayList<Beneficiary>(); RequestDonationList currentDonations = new RequestDonationList(); } public ArrayList<Donator> getDonatorsArrayList() { return donatorList; } public ArrayList<Beneficiary> getBeneficiaryArrayList() { return beneficiaryList; } public void setBeneficiaryList(ArrayList<Beneficiary> beneficiaryList) { this.beneficiaryList = beneficiaryList; } void setAdmin(Admin new_admin) { admin = new_admin; } Admin getAdmin() { return admin; } public RequestDonationList getCurrentDonations() { return currentDonations; } public String getName() { return name; } public void addEntity(Entity new_entity) { entityList.add(new_entity); } public void removeEntity(Entity removed_entity) { entityList.remove(removed_entity); } public void insertDonator(Donator new_donator) { donatorList.add(new_donator); } public void removeDonator(Donator removed_donator) { donatorList.clear(); } public void insertBeneficiary(Beneficiary new_beneficiary) { beneficiaryList.add(new_beneficiary); } public void removeBeneficiary(int choice) { int cnt=0; for (int i = 0; i < beneficiaryList.size(); i++) { if((choice-1) == i) { beneficiaryList.remove(choice-1); cnt++; System.out.println("Beneficiary has been deleted!"); } } if(cnt==0){ System.out.println("Beneficiary " + name + " not found!"); } } public void removeBeneficiaryReceivedList(int choice) { for (int i = 0; i < beneficiaryList.size(); i++) { if((choice-1) == i) { beneficiaryList.get(choice-1).clearRecievedList(); System.out.println("Beneficiary's received list cleared"); } } } public void removeCurrentDonation(int id,double quantity) { for(RequestDonation index : currentDonations.rdEntities ) { if(id == index.getEntity().getId()) { index.setQuantity(index.getQuantity()-quantity); } } } public void clearBeneficiaryRequests () { for(Beneficiary index : beneficiaryList) { index.clearRecievedList(); } } //------------------------------------------------------------------LISTING void listEntities() { System.out.println("<This is the list of "+ getName() +" Entities>"); System.out.println(); for (Entity index : entityList) { System.out.println(index.toString()); System.out.println(); } } void listBeneficiaries() { int cnt = 0; System.out.println("<This is the list of "+ getName() +" Beneficiaries>"); System.out.println(); for (Beneficiary index : beneficiaryList) { System.out.println(++cnt); index.viewBeneficiaryDetails(); } } void listDonators() { System.out.println("<This is the list of "+ getName() +" Donators>"); System.out.println(); for (Donator index : donatorList) { index.viewDonatorDetails(); } } void listCurrentDonations() { System.out.println("<This is the list of "+ getName() +" Current Donations>"); System.out.println(); currentDonations.monitor(); } void listMaterials() { int cnt=0; System.out.println("<This is the list of " + getName() + " Materials>"); System.out.println(); for (Entity index : entityList) { if (index.getIsMaterial()) System.out.println(++cnt + ". " + index.toString()); System.out.println(); } } void listServices() { int cnt=0; System.out.println("<This is the list of " + getName() + " Services>"); System.out.println(); for (Entity index : entityList) { if (!(index.getIsMaterial())) System.out.println(++cnt + ". " + index.toString()); System.out.println(); } } }
Antonis01/OOP_Team_Project_2020-2021
src/Organisation.java
1,187
/*Αντιστοιχεί στον οργανισμό που υποστηρίζει το σύστημα donation.*/
block_comment
el
/*Αντιστοιχεί στον οργανισμό<SUF>*/ import java.util.ArrayList; class Organization { private String name; private Admin admin; private ArrayList<Entity> entityList = new ArrayList<Entity>(); private ArrayList<Donator> donatorList = new ArrayList<Donator>(); private ArrayList<Beneficiary> beneficiaryList = new ArrayList<Beneficiary>(); private RequestDonationList currentDonations = new RequestDonationList(); Organization(){} Organization(String name) { this.name = name; ArrayList<Entity> entityList = new ArrayList<Entity>(); ArrayList<Donator> donatorList = new ArrayList<Donator>(); ArrayList<Beneficiary> beneficiaryList = new ArrayList<Beneficiary>(); RequestDonationList currentDonations = new RequestDonationList(); } public ArrayList<Donator> getDonatorsArrayList() { return donatorList; } public ArrayList<Beneficiary> getBeneficiaryArrayList() { return beneficiaryList; } public void setBeneficiaryList(ArrayList<Beneficiary> beneficiaryList) { this.beneficiaryList = beneficiaryList; } void setAdmin(Admin new_admin) { admin = new_admin; } Admin getAdmin() { return admin; } public RequestDonationList getCurrentDonations() { return currentDonations; } public String getName() { return name; } public void addEntity(Entity new_entity) { entityList.add(new_entity); } public void removeEntity(Entity removed_entity) { entityList.remove(removed_entity); } public void insertDonator(Donator new_donator) { donatorList.add(new_donator); } public void removeDonator(Donator removed_donator) { donatorList.clear(); } public void insertBeneficiary(Beneficiary new_beneficiary) { beneficiaryList.add(new_beneficiary); } public void removeBeneficiary(int choice) { int cnt=0; for (int i = 0; i < beneficiaryList.size(); i++) { if((choice-1) == i) { beneficiaryList.remove(choice-1); cnt++; System.out.println("Beneficiary has been deleted!"); } } if(cnt==0){ System.out.println("Beneficiary " + name + " not found!"); } } public void removeBeneficiaryReceivedList(int choice) { for (int i = 0; i < beneficiaryList.size(); i++) { if((choice-1) == i) { beneficiaryList.get(choice-1).clearRecievedList(); System.out.println("Beneficiary's received list cleared"); } } } public void removeCurrentDonation(int id,double quantity) { for(RequestDonation index : currentDonations.rdEntities ) { if(id == index.getEntity().getId()) { index.setQuantity(index.getQuantity()-quantity); } } } public void clearBeneficiaryRequests () { for(Beneficiary index : beneficiaryList) { index.clearRecievedList(); } } //------------------------------------------------------------------LISTING void listEntities() { System.out.println("<This is the list of "+ getName() +" Entities>"); System.out.println(); for (Entity index : entityList) { System.out.println(index.toString()); System.out.println(); } } void listBeneficiaries() { int cnt = 0; System.out.println("<This is the list of "+ getName() +" Beneficiaries>"); System.out.println(); for (Beneficiary index : beneficiaryList) { System.out.println(++cnt); index.viewBeneficiaryDetails(); } } void listDonators() { System.out.println("<This is the list of "+ getName() +" Donators>"); System.out.println(); for (Donator index : donatorList) { index.viewDonatorDetails(); } } void listCurrentDonations() { System.out.println("<This is the list of "+ getName() +" Current Donations>"); System.out.println(); currentDonations.monitor(); } void listMaterials() { int cnt=0; System.out.println("<This is the list of " + getName() + " Materials>"); System.out.println(); for (Entity index : entityList) { if (index.getIsMaterial()) System.out.println(++cnt + ". " + index.toString()); System.out.println(); } } void listServices() { int cnt=0; System.out.println("<This is the list of " + getName() + " Services>"); System.out.println(); for (Entity index : entityList) { if (!(index.getIsMaterial())) System.out.println(++cnt + ". " + index.toString()); System.out.println(); } } }
7770_1
package gr.uop.gav.mailerdaemon.util; import org.xbill.DNS.Lookup; import org.xbill.DNS.MXRecord; import org.xbill.DNS.Record; import org.xbill.DNS.Type; import javax.naming.directory.InitialDirContext; import java.util.Arrays; import java.util.Comparator; public class WebUtil { public static MXRecord[] resolveMxRecords(String domain) { MXRecord[] records = new MXRecord[]{}; try { /* Σύμφωνα με το RFC5321, δίνουμε προτεραιότητα στα mx records με την μικρότερο αριθμό "προτίμησης" περισσότερες πληροφορίες https://en.wikipedia.org/wiki/MX_record */ Lookup lookup = new Lookup(domain, Type.MX); Record[] mxRecords = lookup.run(); // Θα κάνουμε sort to records array με αύξουσα σειρά Arrays.sort(mxRecords, Comparator.comparingInt(record -> ((MXRecord) record).getPriority())); records = new MXRecord[mxRecords.length]; for(int i = 0; i < mxRecords.length; i++) { records[i] = (MXRecord) mxRecords[i]; } return records; } catch (Exception ex) { ex.printStackTrace(); return records; } } }
Arisstath/GAVLab---Email
MailerDaemon/src/main/java/gr/uop/gav/mailerdaemon/util/WebUtil.java
393
// Θα κάνουμε sort to records array με αύξουσα σειρά
line_comment
el
package gr.uop.gav.mailerdaemon.util; import org.xbill.DNS.Lookup; import org.xbill.DNS.MXRecord; import org.xbill.DNS.Record; import org.xbill.DNS.Type; import javax.naming.directory.InitialDirContext; import java.util.Arrays; import java.util.Comparator; public class WebUtil { public static MXRecord[] resolveMxRecords(String domain) { MXRecord[] records = new MXRecord[]{}; try { /* Σύμφωνα με το RFC5321, δίνουμε προτεραιότητα στα mx records με την μικρότερο αριθμό "προτίμησης" περισσότερες πληροφορίες https://en.wikipedia.org/wiki/MX_record */ Lookup lookup = new Lookup(domain, Type.MX); Record[] mxRecords = lookup.run(); // Θα κάνουμε<SUF> Arrays.sort(mxRecords, Comparator.comparingInt(record -> ((MXRecord) record).getPriority())); records = new MXRecord[mxRecords.length]; for(int i = 0; i < mxRecords.length; i++) { records[i] = (MXRecord) mxRecords[i]; } return records; } catch (Exception ex) { ex.printStackTrace(); return records; } } }
3664_6
package com.RapidPharma; import java.util.*; import java.mail.*; import javax.mail.internet.*; import javax.activation.*; import javax.swing.*; import java.sql.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.RapidPharma.lista_aitima; public class Dromologhths extends xristis{ //Επιστρέφονται όλα τα αιτήματα που αφορουν το δρομολογητη public static ObservableList<Aitima> getaitimata(String ID_DROMOLOGITI) { private static Statement statement; aitimata = FXCollections.observableArrayList(); try { statement = DataConnection.getConnection("jdbc:mysql://localhost:3306/RapidPharma", "root", "root").createStatement(); ResultSet myRs = statement.executeQuery("select * from Aitima inner join xristis a on ID_dromologiti=a.id where a.id=" + ID_DROMOLOGITI + ";"); if (myRs != null) while (myRs.next()) { Aitima aitima_1 = new Aitima(); aitima_1.setid(myRs.getInt(1)); aitima_1.setImerominia(myRs.getInt(2)); aitima_1.setApo_Topothesia(myRs.getString(3)); aitima_1.setPros_Topothesia(myRs.getString(4)); aitima_1.setEidos_Metaforas(myRs.getString(5)); aitima_1.setRequired_Europaletes(myRs.getInt(6)); aitima_1.setstatus(myRs.getInt(7)); aitimata.add(aitima_1); } } catch (Exception e) { e.printStackTrace(); } return aitimata; } public static void Diaxirisi_insert(String id_aitimatos,String id_dromologiti){ Aitima aitima = new Aitima(); try { Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/RapidPharma", "root", "root"); Statement myStmt = myConn.createStatement(); Scanner scanner = new Scanner(System.in); System.out.println("Εισαγωγή ευροπαλετών:"); int europaletes = scanner.nextInt(); System.out.println("Εισαγωγή ημερομηνίας:"); String imerominia = scanner.nextLine(); ResultSet myRs = myStmt.executeQuery("select sunolo_paletwn from Aitima where id_aitimatos="+id_aitimatos); anakateuthinsi_CheckBox = new javax.swing.JCheckBox();//checkbox που επιλέγει ο χρήστης ανακατατεύθυνση boolean checked = anakateuthinsi_CheckBox.getState(); if (anakateuthinsi_CheckBox.getState()) { System.out.println("Δώσε την περιγραφή του αιτήματος που ανακατευθύνεται:"); String Perigrafi_anakateuthinomenou = scanner.next(); if(Perigrafi_anakateuthinomenou!=null){ //εαν δηλαδή θέλω να ανακατευθύνω ένα τμήμα του αιτήματος System.out.println("Εισαγωγή αιτιολογίας ανακατεύθυνσης:");//αυτό θα αντικατασταθεί απο το GUI String Aitiologia = scanner.nextLine(); System.out.println("Εισαγωγή κωδικού νεου δρομολογητή:"); int allagi_kwdikou = scanner.nextInt(); ResultSet myRs_1 = myStmt.executeQuery("Update Aitima set perigrafh="+Perigrafi_anakateuthinomenou+" where id_aitimatos=" + id_aitimatos); aitima.Update_status(id_aitimatos,1); aitima.updateRouter(allagi_kwdikou,id_aitimatos,Aitiologia,id_dromologiti); System.out.println("Δώσε το ID του νέου αιτήματος:"); String ID_new_Aitimatos = scanner.next(); System.out.println("Δώσε την περιγραφή του αιτήματος που δρομολογείται:"); String Perigrafi_dromologimenou = scanner.next(); ResultSet myRs_2 = myStmt.executeQuery("select * from Aitima where id_aitimatos=" + id_aitimatos); String Apo = myRs_2.getString("apo"); String Pros = myRs_2.getString("pros"); String Eidos_metaforas = myRs_2.getString("eidos_metaforas"); Date Imerominia_dhmiourgias = myRs_2.getDate("imerominia_dhmiourgias"); Date Imerominia_dromologiou = myRs_1.getDate("imerominia_dromologiou"); int Sunolo_paletwn = myRs_2.getInt("sunolo_paletwn"); int Status = myRs_2.getInt("status"); Boolean Inroute = myRs_2.getBoolean("inroute"); int Route_id = myRs_2.getInt("route_id"); String Id_dimiourgou = myRs_2.getString("ID_dimiourgou"); String Id_dromologiti = myRs_2.getString("ID_dromologiti"); //Το κομμάτι του αιτήματος που θα δρομολογεί τώρα (αυτό που μένει και δεν ανακατευθύνθηκε) //Εδω δημιουργουμε το νεο αιτημα το οποιο έχει τα ίδια πεδία με το προηγούμενο αίτημα εκτός απο τα perigrafh(εδώ ο δρομολογητής συμπληρώνει αυτά που δεν έχουν ανακατευθυνθεί) ,id_aitimatos(το οποίο είναι // το νέο id που θέτει ο δρομολογητής για το κομμάτι του αιτήματος που δρομολογεί τώρα) ResultSet myRs_3 = myStmt.executeQuery("Insert into Aitima set imerominia_dromologiou="+Imerominia_dromologiou+",id_aitimatos="+ID_new_Aitimatos+",perigrafh="+Perigrafi_dromologimenou+ ",apo="+Apo+",pros="+Pros+",eidos_metaforas="+Eidos_metaforas+",imerominia_dhmiourgias="+Imerominia_dhmiourgias+",sunolo_paletwn="+Sunolo_paletwn+ ",status="+Status+",aitiologia="+Aitiologia+",inroute="+Inroute+",route_id="+Route_id+",ID_dimiourgou="+Id_dimiourgou+",ID_dromologiti="+Id_dromologiti); ResultSet myRs_4 = myStmt.executeQuery("Update Aitima set imerominia_dromologiou=" + imerominia + " where id_aitimatos=" + ID_new_Aitimatos); aitima.Update_status(ID_new_Aitimatos,1); }else { System.out.println("Εισαγωγή αιτιολογίας ανακατεύθυνσης:"); String Aitiologia = scanner.nextLine(); System.out.println("Εισαγωγή κωδικού νεου δρομολογητή:"); int allagi_kwdikou = scanner.nextInt(); aitima.updateRouter(allagi_kwdikou,id_aitimatos,Aitiologia,id_dromologiti); } } else { if (europaletes==myRs.getInt("sunolo_paletwn")) { ResultSet myRs_1 = myStmt.executeQuery("Update Aitima set imerominia_dromologiou=" + imerominia + " where id_aitimatos=" + id_aitimatos); aitima.Update_status(id_aitimatos,1); } if (europaletes<myRs.getInt("sunolo_paletwn")){ //Το κομμάτι του αιτήματος που δρομολογείται τωρα System.out.println("Δώσε την περιγραφή του αιτήματος που δρομολογείται:"); String Perigrafi_old = scanner.next(); ResultSet myRs_2 = myStmt.executeQuery("Update Aitima set imerominia_dromologiou="+imerominia+", perigrafh="+Perigrafi_old+" where id_aitimatos=" + id_aitimatos); aitima.Update_status(id_aitimatos,1); System.out.println("Δώσε το ID του νέου αιτήματος:"); String ID_new_Aitimatos = scanner.next(); System.out.println("Δώσε την περιγραφή του νέου αιτήματος:"); String Perigrafi_new = scanner.next(); ResultSet myRs_1 = myStmt.executeQuery("select * from Aitima where id_aitimatos=" + id_aitimatos); String Apo = myRs_1.getString("apo"); String Pros = myRs_1.getString("pros"); String Eidos_metaforas = myRs_1.getString("eidos_metaforas"); Date Imerominia_dhmiourgias = myRs_1.getDate("imerominia_dhmiourgias"); Date Imerominia_dromologiou = myRs_1.getDate("imerominia_dromologiou"); int Sunolo_paletwn = myRs_1.getInt("sunolo_paletwn"); int Status = myRs_1.getInt("status"); String Aitiologia = myRs_1.getString("aitiologia"); Boolean Inroute = myRs_1.getBoolean("inroute"); int Route_id = myRs_1.getInt("route_id"); String Id_dimiourgou = myRs_1.getString("ID_dimiourgou"); String Id_dromologiti = myRs_1.getString("ID_dromologiti"); //Το κομμάτι του αιτήματος που θα δρομολογηθεί αργότερα //Εδω δημιουργουμε το νεο αιτημα το οποιο έχει τα ίδια πεδία με το προηγούμενο αίτημα εκτός απο τα perigrafh(εδώ ο δρομολογητής συμπληρώνει αυτά που δεν έχουν δρομολογηθεί) ,id_aitimatos(το οποίο είναι // το νέο id που θέτει ο δρομολογητής για το κομμάτι του αιτήματος που δε δρομολογείται τώρα) ResultSet myRs_3 = myStmt.executeQuery("Insert into Aitima set imerominia_dromologiou="+Imerominia_dromologiou+",id_aitimatos="+ID_new_Aitimatos+",perigrafh="+Perigrafi_new+ ",apo="+Apo+",pros="+Pros+",eidos_metaforas="+Eidos_metaforas+",imerominia_dhmiourgias="+Imerominia_dhmiourgias+",sunolo_paletwn="+Sunolo_paletwn+ ",status="+Status+",aitiologia="+Aitiologia+",inroute="+Inroute+",route_id="+Route_id+",ID_dimiourgou="+Id_dimiourgou+",ID_dromologiti="+Id_dromologiti); aitima.Update_status(ID_new_Aitimatos,4); } } } catch(Exception exc) { exc.printStackTrace(); } } }
Asbaharoon/java-project
java_src/dromologhths.java
3,551
//Το κομμάτι του αιτήματος που θα δρομολογεί τώρα (αυτό που μένει και δεν ανακατευθύνθηκε)
line_comment
el
package com.RapidPharma; import java.util.*; import java.mail.*; import javax.mail.internet.*; import javax.activation.*; import javax.swing.*; import java.sql.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.RapidPharma.lista_aitima; public class Dromologhths extends xristis{ //Επιστρέφονται όλα τα αιτήματα που αφορουν το δρομολογητη public static ObservableList<Aitima> getaitimata(String ID_DROMOLOGITI) { private static Statement statement; aitimata = FXCollections.observableArrayList(); try { statement = DataConnection.getConnection("jdbc:mysql://localhost:3306/RapidPharma", "root", "root").createStatement(); ResultSet myRs = statement.executeQuery("select * from Aitima inner join xristis a on ID_dromologiti=a.id where a.id=" + ID_DROMOLOGITI + ";"); if (myRs != null) while (myRs.next()) { Aitima aitima_1 = new Aitima(); aitima_1.setid(myRs.getInt(1)); aitima_1.setImerominia(myRs.getInt(2)); aitima_1.setApo_Topothesia(myRs.getString(3)); aitima_1.setPros_Topothesia(myRs.getString(4)); aitima_1.setEidos_Metaforas(myRs.getString(5)); aitima_1.setRequired_Europaletes(myRs.getInt(6)); aitima_1.setstatus(myRs.getInt(7)); aitimata.add(aitima_1); } } catch (Exception e) { e.printStackTrace(); } return aitimata; } public static void Diaxirisi_insert(String id_aitimatos,String id_dromologiti){ Aitima aitima = new Aitima(); try { Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/RapidPharma", "root", "root"); Statement myStmt = myConn.createStatement(); Scanner scanner = new Scanner(System.in); System.out.println("Εισαγωγή ευροπαλετών:"); int europaletes = scanner.nextInt(); System.out.println("Εισαγωγή ημερομηνίας:"); String imerominia = scanner.nextLine(); ResultSet myRs = myStmt.executeQuery("select sunolo_paletwn from Aitima where id_aitimatos="+id_aitimatos); anakateuthinsi_CheckBox = new javax.swing.JCheckBox();//checkbox που επιλέγει ο χρήστης ανακατατεύθυνση boolean checked = anakateuthinsi_CheckBox.getState(); if (anakateuthinsi_CheckBox.getState()) { System.out.println("Δώσε την περιγραφή του αιτήματος που ανακατευθύνεται:"); String Perigrafi_anakateuthinomenou = scanner.next(); if(Perigrafi_anakateuthinomenou!=null){ //εαν δηλαδή θέλω να ανακατευθύνω ένα τμήμα του αιτήματος System.out.println("Εισαγωγή αιτιολογίας ανακατεύθυνσης:");//αυτό θα αντικατασταθεί απο το GUI String Aitiologia = scanner.nextLine(); System.out.println("Εισαγωγή κωδικού νεου δρομολογητή:"); int allagi_kwdikou = scanner.nextInt(); ResultSet myRs_1 = myStmt.executeQuery("Update Aitima set perigrafh="+Perigrafi_anakateuthinomenou+" where id_aitimatos=" + id_aitimatos); aitima.Update_status(id_aitimatos,1); aitima.updateRouter(allagi_kwdikou,id_aitimatos,Aitiologia,id_dromologiti); System.out.println("Δώσε το ID του νέου αιτήματος:"); String ID_new_Aitimatos = scanner.next(); System.out.println("Δώσε την περιγραφή του αιτήματος που δρομολογείται:"); String Perigrafi_dromologimenou = scanner.next(); ResultSet myRs_2 = myStmt.executeQuery("select * from Aitima where id_aitimatos=" + id_aitimatos); String Apo = myRs_2.getString("apo"); String Pros = myRs_2.getString("pros"); String Eidos_metaforas = myRs_2.getString("eidos_metaforas"); Date Imerominia_dhmiourgias = myRs_2.getDate("imerominia_dhmiourgias"); Date Imerominia_dromologiou = myRs_1.getDate("imerominia_dromologiou"); int Sunolo_paletwn = myRs_2.getInt("sunolo_paletwn"); int Status = myRs_2.getInt("status"); Boolean Inroute = myRs_2.getBoolean("inroute"); int Route_id = myRs_2.getInt("route_id"); String Id_dimiourgou = myRs_2.getString("ID_dimiourgou"); String Id_dromologiti = myRs_2.getString("ID_dromologiti"); //Το κομμάτι<SUF> //Εδω δημιουργουμε το νεο αιτημα το οποιο έχει τα ίδια πεδία με το προηγούμενο αίτημα εκτός απο τα perigrafh(εδώ ο δρομολογητής συμπληρώνει αυτά που δεν έχουν ανακατευθυνθεί) ,id_aitimatos(το οποίο είναι // το νέο id που θέτει ο δρομολογητής για το κομμάτι του αιτήματος που δρομολογεί τώρα) ResultSet myRs_3 = myStmt.executeQuery("Insert into Aitima set imerominia_dromologiou="+Imerominia_dromologiou+",id_aitimatos="+ID_new_Aitimatos+",perigrafh="+Perigrafi_dromologimenou+ ",apo="+Apo+",pros="+Pros+",eidos_metaforas="+Eidos_metaforas+",imerominia_dhmiourgias="+Imerominia_dhmiourgias+",sunolo_paletwn="+Sunolo_paletwn+ ",status="+Status+",aitiologia="+Aitiologia+",inroute="+Inroute+",route_id="+Route_id+",ID_dimiourgou="+Id_dimiourgou+",ID_dromologiti="+Id_dromologiti); ResultSet myRs_4 = myStmt.executeQuery("Update Aitima set imerominia_dromologiou=" + imerominia + " where id_aitimatos=" + ID_new_Aitimatos); aitima.Update_status(ID_new_Aitimatos,1); }else { System.out.println("Εισαγωγή αιτιολογίας ανακατεύθυνσης:"); String Aitiologia = scanner.nextLine(); System.out.println("Εισαγωγή κωδικού νεου δρομολογητή:"); int allagi_kwdikou = scanner.nextInt(); aitima.updateRouter(allagi_kwdikou,id_aitimatos,Aitiologia,id_dromologiti); } } else { if (europaletes==myRs.getInt("sunolo_paletwn")) { ResultSet myRs_1 = myStmt.executeQuery("Update Aitima set imerominia_dromologiou=" + imerominia + " where id_aitimatos=" + id_aitimatos); aitima.Update_status(id_aitimatos,1); } if (europaletes<myRs.getInt("sunolo_paletwn")){ //Το κομμάτι του αιτήματος που δρομολογείται τωρα System.out.println("Δώσε την περιγραφή του αιτήματος που δρομολογείται:"); String Perigrafi_old = scanner.next(); ResultSet myRs_2 = myStmt.executeQuery("Update Aitima set imerominia_dromologiou="+imerominia+", perigrafh="+Perigrafi_old+" where id_aitimatos=" + id_aitimatos); aitima.Update_status(id_aitimatos,1); System.out.println("Δώσε το ID του νέου αιτήματος:"); String ID_new_Aitimatos = scanner.next(); System.out.println("Δώσε την περιγραφή του νέου αιτήματος:"); String Perigrafi_new = scanner.next(); ResultSet myRs_1 = myStmt.executeQuery("select * from Aitima where id_aitimatos=" + id_aitimatos); String Apo = myRs_1.getString("apo"); String Pros = myRs_1.getString("pros"); String Eidos_metaforas = myRs_1.getString("eidos_metaforas"); Date Imerominia_dhmiourgias = myRs_1.getDate("imerominia_dhmiourgias"); Date Imerominia_dromologiou = myRs_1.getDate("imerominia_dromologiou"); int Sunolo_paletwn = myRs_1.getInt("sunolo_paletwn"); int Status = myRs_1.getInt("status"); String Aitiologia = myRs_1.getString("aitiologia"); Boolean Inroute = myRs_1.getBoolean("inroute"); int Route_id = myRs_1.getInt("route_id"); String Id_dimiourgou = myRs_1.getString("ID_dimiourgou"); String Id_dromologiti = myRs_1.getString("ID_dromologiti"); //Το κομμάτι του αιτήματος που θα δρομολογηθεί αργότερα //Εδω δημιουργουμε το νεο αιτημα το οποιο έχει τα ίδια πεδία με το προηγούμενο αίτημα εκτός απο τα perigrafh(εδώ ο δρομολογητής συμπληρώνει αυτά που δεν έχουν δρομολογηθεί) ,id_aitimatos(το οποίο είναι // το νέο id που θέτει ο δρομολογητής για το κομμάτι του αιτήματος που δε δρομολογείται τώρα) ResultSet myRs_3 = myStmt.executeQuery("Insert into Aitima set imerominia_dromologiou="+Imerominia_dromologiou+",id_aitimatos="+ID_new_Aitimatos+",perigrafh="+Perigrafi_new+ ",apo="+Apo+",pros="+Pros+",eidos_metaforas="+Eidos_metaforas+",imerominia_dhmiourgias="+Imerominia_dhmiourgias+",sunolo_paletwn="+Sunolo_paletwn+ ",status="+Status+",aitiologia="+Aitiologia+",inroute="+Inroute+",route_id="+Route_id+",ID_dimiourgou="+Id_dimiourgou+",ID_dromologiti="+Id_dromologiti); aitima.Update_status(ID_new_Aitimatos,4); } } } catch(Exception exc) { exc.printStackTrace(); } } }
16571_0
import java.util.Date; import java.text.*; //import MyDateLib.java; public class Foititis { private static int auxwnArithmos = 0; private String AM; private String onomatEpwnymo; private Date hmeromGennisis; public Foititis(int etos, String onomatEpwnymo, Date hmeromGennisis) { auxwnArithmos+=1; // Δημιουργία αριθμού 3 ψηφίων DecimalFormat myFormatter = new DecimalFormat("000"); String tempArithm = myFormatter.format(auxwnArithmos); this.AM= (etos + tempArithm); this.onomatEpwnymo = onomatEpwnymo; this.hmeromGennisis = hmeromGennisis; } public String toString() { StringBuffer sb = new StringBuffer(this.AM + " "); sb.append(this.onomatEpwnymo + " "); sb.append(dateToStr(this.hmeromGennisis)); return sb.toString(); } private String dateToStr(Date hmeromGennisis) { DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); String str = df.format(this.hmeromGennisis); return str; } String getAM() { return this.AM; } String getOnEp() { return this.onomatEpwnymo; } Date getHmerom() { return this.hmeromGennisis; } public void setHmerom(Date hmerom) { this.hmeromGennisis=hmerom; } public void setOnEp(String OnEp) { this.onomatEpwnymo=OnEp; } }
Astodialo/A23
Foititis.java
458
// Δημιουργία αριθμού 3 ψηφίων
line_comment
el
import java.util.Date; import java.text.*; //import MyDateLib.java; public class Foititis { private static int auxwnArithmos = 0; private String AM; private String onomatEpwnymo; private Date hmeromGennisis; public Foititis(int etos, String onomatEpwnymo, Date hmeromGennisis) { auxwnArithmos+=1; // Δημιουργία αριθμού<SUF> DecimalFormat myFormatter = new DecimalFormat("000"); String tempArithm = myFormatter.format(auxwnArithmos); this.AM= (etos + tempArithm); this.onomatEpwnymo = onomatEpwnymo; this.hmeromGennisis = hmeromGennisis; } public String toString() { StringBuffer sb = new StringBuffer(this.AM + " "); sb.append(this.onomatEpwnymo + " "); sb.append(dateToStr(this.hmeromGennisis)); return sb.toString(); } private String dateToStr(Date hmeromGennisis) { DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); String str = df.format(this.hmeromGennisis); return str; } String getAM() { return this.AM; } String getOnEp() { return this.onomatEpwnymo; } Date getHmerom() { return this.hmeromGennisis; } public void setHmerom(Date hmerom) { this.hmeromGennisis=hmerom; } public void setOnEp(String OnEp) { this.onomatEpwnymo=OnEp; } }
30042_4
package org.hua.dit.oopii_21950_219113.Controller; import org.hua.dit.oopii_21950_219113.Dao.CityRepository; import org.hua.dit.oopii_21950_219113.Exceptions.NoSuchCityException; import org.hua.dit.oopii_21950_219113.Exceptions.NoSuchOpenWeatherCityException; import org.hua.dit.oopii_21950_219113.Service.CityService; import org.hua.dit.oopii_21950_219113.Service.TravellersService; import org.hua.dit.oopii_21950_219113.entitys.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Here in the future we will have the main functionality of the web app, for now we hard coded most of it for the 1st * deliverable's sake. */ //@CrossOrigin(origins= "http://localhost:3000") @CrossOrigin("*") @RestController @RequestMapping(path = "/") //Because we are hard coding data every time we will be showing stats for the same traveller. public class TravellersController { /* NOT RECOMENED BY SPRING, for the purposes of this project we can ignore that because this helps us, as a small team write and test code faster, also it is an automation which makes the Dependency injection real easy to understand. */ @Autowired private final TravellersService travellersService; private final CityRepository cityRepository; /** * * @param travellersService initialize the class object with a given TravellerService * @param cityRepository */ public TravellersController(TravellersService travellersService, CityRepository cityRepository) { this.travellersService = travellersService; this.cityRepository=cityRepository; } @GetMapping(path = "/travellers") public ArrayList<Traveller> getAllTravellers() throws InterruptedException { return travellersService.getAllTravellers(); } @GetMapping( path = "{name}/bestCity") public City findBestCityForTheUser(@PathVariable("name")String name) throws InterruptedException { return travellersService.findBestCityForTheUser(name); } @GetMapping( path = "{name}/bestCity/collaborate") public City findBestCityCollaborating(@PathVariable("name")String name) throws InterruptedException { return travellersService.findBestCityCollaborating(name); } @GetMapping(path = "{cityName}/{country}/search") public City checkCity(@PathVariable("cityName")String cityName,@PathVariable("country")String country){ try { return travellersService.searchCity(cityName,country); }catch (NoSuchCityException | InterruptedException e) { System.out.println("There is no city with this name!"); e.printStackTrace(); } return null; } @PostMapping( path = "/addYoungTraveller") public String addNewTraveller(@RequestBody YoungTraveller traveller) throws IOException, InterruptedException { return travellersService.addNewTraveller(traveller); } @PostMapping( path = "/addMiddleTraveller") public String addNewTraveller(@RequestBody MiddleTraveller traveller) throws IOException, InterruptedException { return travellersService.addNewTraveller(traveller); } @PostMapping( path = "/addElderTraveller") public String addNewTraveller(@RequestBody ElderTraveller traveller) throws IOException, InterruptedException { return travellersService.addNewTraveller(traveller); } //TODO: για το free ticket θα βαλουμε ενα switch case για του 12 μηνες του χρονου και καθε μηνα θα εχουμε διαφορερικη πολη για free ticket (αυτο θα γινετε στο frontend) @GetMapping( path = "{cityName}/{country}/freeTicket") public Traveller findFreeTicket(@PathVariable("cityName") String FreeCityName , @PathVariable("country") String FreeCountry) throws NoSuchCityException, InterruptedException { return travellersService.findFreeTicket(FreeCityName,FreeCountry); } @GetMapping(path = "{name}/{number}/bestCity" ) public ArrayList<City> findXBestCities(@PathVariable String name, @PathVariable Integer number) throws InterruptedException { return travellersService.findXBestCities(name,number); } }
Athanasioschourlias/Travellers-recomendation-App
src/main/java/org/hua/dit/oopii_21950_219113/Controller/TravellersController.java
1,189
//TODO: για το free ticket θα βαλουμε ενα switch case για του 12 μηνες του χρονου και καθε μηνα θα εχουμε διαφορερικη πολη για free ticket (αυτο θα γινετε στο frontend)
line_comment
el
package org.hua.dit.oopii_21950_219113.Controller; import org.hua.dit.oopii_21950_219113.Dao.CityRepository; import org.hua.dit.oopii_21950_219113.Exceptions.NoSuchCityException; import org.hua.dit.oopii_21950_219113.Exceptions.NoSuchOpenWeatherCityException; import org.hua.dit.oopii_21950_219113.Service.CityService; import org.hua.dit.oopii_21950_219113.Service.TravellersService; import org.hua.dit.oopii_21950_219113.entitys.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Here in the future we will have the main functionality of the web app, for now we hard coded most of it for the 1st * deliverable's sake. */ //@CrossOrigin(origins= "http://localhost:3000") @CrossOrigin("*") @RestController @RequestMapping(path = "/") //Because we are hard coding data every time we will be showing stats for the same traveller. public class TravellersController { /* NOT RECOMENED BY SPRING, for the purposes of this project we can ignore that because this helps us, as a small team write and test code faster, also it is an automation which makes the Dependency injection real easy to understand. */ @Autowired private final TravellersService travellersService; private final CityRepository cityRepository; /** * * @param travellersService initialize the class object with a given TravellerService * @param cityRepository */ public TravellersController(TravellersService travellersService, CityRepository cityRepository) { this.travellersService = travellersService; this.cityRepository=cityRepository; } @GetMapping(path = "/travellers") public ArrayList<Traveller> getAllTravellers() throws InterruptedException { return travellersService.getAllTravellers(); } @GetMapping( path = "{name}/bestCity") public City findBestCityForTheUser(@PathVariable("name")String name) throws InterruptedException { return travellersService.findBestCityForTheUser(name); } @GetMapping( path = "{name}/bestCity/collaborate") public City findBestCityCollaborating(@PathVariable("name")String name) throws InterruptedException { return travellersService.findBestCityCollaborating(name); } @GetMapping(path = "{cityName}/{country}/search") public City checkCity(@PathVariable("cityName")String cityName,@PathVariable("country")String country){ try { return travellersService.searchCity(cityName,country); }catch (NoSuchCityException | InterruptedException e) { System.out.println("There is no city with this name!"); e.printStackTrace(); } return null; } @PostMapping( path = "/addYoungTraveller") public String addNewTraveller(@RequestBody YoungTraveller traveller) throws IOException, InterruptedException { return travellersService.addNewTraveller(traveller); } @PostMapping( path = "/addMiddleTraveller") public String addNewTraveller(@RequestBody MiddleTraveller traveller) throws IOException, InterruptedException { return travellersService.addNewTraveller(traveller); } @PostMapping( path = "/addElderTraveller") public String addNewTraveller(@RequestBody ElderTraveller traveller) throws IOException, InterruptedException { return travellersService.addNewTraveller(traveller); } //TODO: για<SUF> @GetMapping( path = "{cityName}/{country}/freeTicket") public Traveller findFreeTicket(@PathVariable("cityName") String FreeCityName , @PathVariable("country") String FreeCountry) throws NoSuchCityException, InterruptedException { return travellersService.findFreeTicket(FreeCityName,FreeCountry); } @GetMapping(path = "{name}/{number}/bestCity" ) public ArrayList<City> findXBestCities(@PathVariable String name, @PathVariable Integer number) throws InterruptedException { return travellersService.findXBestCities(name,number); } }
46342_6
package gr.aueb.dmst.pijavaparty.proderp.dao; import gr.aueb.dmst.pijavaparty.proderp.entity.COrderItem; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * COrderItemDao.java - a class for interacting and modifying the fields of a * customer's items. * * @author Athina P. * @see COrderItem */ public class COrderItemDao extends Dao implements CompositeEntityI<COrderItem> { private static final String GETALL = "SELECT * FROM C_order_items"; private static final String GETBYIDS = "SELECT * FROM C_order_items WHERE c_order_id = ? AND product_id = ?"; private static final String GETITEMSPERCORDER = "SELECT * FROM C_order_items WHERE c_order_id = ?"; private static final String INSERT = "INSERT INTO C_order_items VALUES (?, ?, ?)"; private static final String DELETE = "DELETE FROM C_order_items WHERE c_order_id = ? AND product_id = ?"; private COrderDao co = new COrderDao(); private ProductDao pr = new ProductDao(); /** * Retrieve customer order items from database * * @return A COrderItem data type List. */ @Override public List<COrderItem> getAll() { List<COrderItem> corders = new ArrayList(); Statement st = null; ResultSet rs = null; try { st = getConnection().createStatement(); rs = st.executeQuery(GETALL); while (rs.next()) { corders.add(new COrderItem(co.getById(rs.getInt(1)), pr.getById(rs.getInt(2)), rs.getInt(3)));//δεν υπαρχει η getById στην COrdrDao } } catch (SQLException ex) { Logger.getLogger(CustomerDao.class.getName()).log(Level.SEVERE, null, ex); } finally { closeStatementAndResultSet(rs, st); } return corders; } /** * Get a customer's order item with a specific id. * * @param coid COrder's id. * @param prid Product's id. * @return A COrderItem data type object. */ public COrderItem getByIds(int coid, int prid) { PreparedStatement pst = null; ResultSet rs = null; try { pst = getConnection().prepareStatement(GETBYIDS); pst.setInt(1, coid); pst.setInt(2, prid); rs = pst.executeQuery(); if (rs.next()) { return new COrderItem(co.getById(rs.getInt(1)), pr.getById(rs.getInt(2)), rs.getInt(3)); } } catch (SQLException ex) { Logger.getLogger(CustomerDao.class.getName()).log(Level.SEVERE, null, ex); } finally { closeStatementAndResultSet(rs, pst); } return null; } /** * Get items of a specific COrder. * * @param coid COrder's id. * @return A COrderItem data type List. */ public List<COrderItem> getItemsPerCOrder(int coid) { List<COrderItem> coi = new ArrayList(); PreparedStatement pst = null; ResultSet rs = null; try { pst = getConnection().prepareStatement(GETITEMSPERCORDER); pst.setInt(1, coid); rs = pst.executeQuery(); while (rs.next()) { coi.add(new COrderItem(co.getById(rs.getInt(1)), pr.getById(rs.getInt(2)), rs.getInt(3))); } } catch (SQLException ex) { Logger.getLogger(CustomerDao.class.getName()).log(Level.SEVERE, null, ex); } finally { closeStatementAndResultSet(rs, pst); } return coi; } /** * Insert a new customer's item. * * @param coi An object of type COrderItem. */ @Override public void insert(COrderItem coi) { PreparedStatement pst = null; try { pst = getConnection().prepareStatement(INSERT); pst.setInt(1, coi.getCorder().getId()); pst.setInt(2, coi.getProduct().getId()); pst.setInt(3, coi.getQuantity()); pst.execute(); } catch (SQLException ex) { Logger.getLogger(ProductRawMaterialDao.class.getName()).log(Level.SEVERE, null, ex);//εδω τι θα μπει; } finally { closeStatementAndResultSet(pst); } } /** * Delete a customer's item with a specific id. * * @param cordId COrder's id. * @param pId Product's id. */ @Override public void delete(int cordId, int pId) { PreparedStatement pst = null; try { pst = getConnection().prepareStatement(DELETE); pst.setInt(1, cordId); pst.setInt(2, pId); pst.execute(); closeStatementAndResultSet(pst); } catch (SQLException ex) { Logger.getLogger(ProductRawMaterialDao.class.getName()).log(Level.SEVERE, null, ex);//εδω τι θα μπει; } finally { closeStatementAndResultSet(pst); } } }
AthinaDavari/JavaAssignment
proderp/src/main/java/gr/aueb/dmst/pijavaparty/proderp/dao/COrderItemDao.java
1,340
//εδω τι θα μπει;
line_comment
el
package gr.aueb.dmst.pijavaparty.proderp.dao; import gr.aueb.dmst.pijavaparty.proderp.entity.COrderItem; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * COrderItemDao.java - a class for interacting and modifying the fields of a * customer's items. * * @author Athina P. * @see COrderItem */ public class COrderItemDao extends Dao implements CompositeEntityI<COrderItem> { private static final String GETALL = "SELECT * FROM C_order_items"; private static final String GETBYIDS = "SELECT * FROM C_order_items WHERE c_order_id = ? AND product_id = ?"; private static final String GETITEMSPERCORDER = "SELECT * FROM C_order_items WHERE c_order_id = ?"; private static final String INSERT = "INSERT INTO C_order_items VALUES (?, ?, ?)"; private static final String DELETE = "DELETE FROM C_order_items WHERE c_order_id = ? AND product_id = ?"; private COrderDao co = new COrderDao(); private ProductDao pr = new ProductDao(); /** * Retrieve customer order items from database * * @return A COrderItem data type List. */ @Override public List<COrderItem> getAll() { List<COrderItem> corders = new ArrayList(); Statement st = null; ResultSet rs = null; try { st = getConnection().createStatement(); rs = st.executeQuery(GETALL); while (rs.next()) { corders.add(new COrderItem(co.getById(rs.getInt(1)), pr.getById(rs.getInt(2)), rs.getInt(3)));//δεν υπαρχει η getById στην COrdrDao } } catch (SQLException ex) { Logger.getLogger(CustomerDao.class.getName()).log(Level.SEVERE, null, ex); } finally { closeStatementAndResultSet(rs, st); } return corders; } /** * Get a customer's order item with a specific id. * * @param coid COrder's id. * @param prid Product's id. * @return A COrderItem data type object. */ public COrderItem getByIds(int coid, int prid) { PreparedStatement pst = null; ResultSet rs = null; try { pst = getConnection().prepareStatement(GETBYIDS); pst.setInt(1, coid); pst.setInt(2, prid); rs = pst.executeQuery(); if (rs.next()) { return new COrderItem(co.getById(rs.getInt(1)), pr.getById(rs.getInt(2)), rs.getInt(3)); } } catch (SQLException ex) { Logger.getLogger(CustomerDao.class.getName()).log(Level.SEVERE, null, ex); } finally { closeStatementAndResultSet(rs, pst); } return null; } /** * Get items of a specific COrder. * * @param coid COrder's id. * @return A COrderItem data type List. */ public List<COrderItem> getItemsPerCOrder(int coid) { List<COrderItem> coi = new ArrayList(); PreparedStatement pst = null; ResultSet rs = null; try { pst = getConnection().prepareStatement(GETITEMSPERCORDER); pst.setInt(1, coid); rs = pst.executeQuery(); while (rs.next()) { coi.add(new COrderItem(co.getById(rs.getInt(1)), pr.getById(rs.getInt(2)), rs.getInt(3))); } } catch (SQLException ex) { Logger.getLogger(CustomerDao.class.getName()).log(Level.SEVERE, null, ex); } finally { closeStatementAndResultSet(rs, pst); } return coi; } /** * Insert a new customer's item. * * @param coi An object of type COrderItem. */ @Override public void insert(COrderItem coi) { PreparedStatement pst = null; try { pst = getConnection().prepareStatement(INSERT); pst.setInt(1, coi.getCorder().getId()); pst.setInt(2, coi.getProduct().getId()); pst.setInt(3, coi.getQuantity()); pst.execute(); } catch (SQLException ex) { Logger.getLogger(ProductRawMaterialDao.class.getName()).log(Level.SEVERE, null, ex);//εδω τι<SUF> } finally { closeStatementAndResultSet(pst); } } /** * Delete a customer's item with a specific id. * * @param cordId COrder's id. * @param pId Product's id. */ @Override public void delete(int cordId, int pId) { PreparedStatement pst = null; try { pst = getConnection().prepareStatement(DELETE); pst.setInt(1, cordId); pst.setInt(2, pId); pst.execute(); closeStatementAndResultSet(pst); } catch (SQLException ex) { Logger.getLogger(ProductRawMaterialDao.class.getName()).log(Level.SEVERE, null, ex);//εδω τι θα μπει; } finally { closeStatementAndResultSet(pst); } } }
617_4
package tillerino.tillerinobot.lang; import java.util.List; import java.util.Random; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import tillerino.tillerinobot.CommandHandler.Action; import tillerino.tillerinobot.CommandHandler.Message; import tillerino.tillerinobot.CommandHandler.Response; /** * @author Till https://github.com/nikosbks https://osu.ppy.sh/u/3619345 */ public class Greek implements Language { @Override public String unknownBeatmap() { return "Συγνώμη, δεν γνωρίζω αυτό το τραγούδι. Ίσως είναι αρκετά νεο, πολυ δύσκολο, μη εγκεκριμένο ή να μην είναι για το osu standard mode." ; } @Override public String internalException(String marker) { return "Εχ... μάλλον φαίνεται ότι ο ανθρώπινος Tillerino έκανε μαντάρα την σύνδεσή μου." +" Εάν δεν το παρατηρήσει σύντομα, μπορείς [https://github.com/Tillerino/Tillerinobot/wiki/Contact να τον ενημερώσεις]; (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Τί συμβαίνει; Παίρνω μονο παραλογίες από τον server του osu. Μπορείς να μου πείς τι σημαίνει αυτο; 0011101001010000" + " Ο ανθρώπινος Tillerino λέει ότι δεν υπάρχει κάτι για να ανησυχείς, και ότι πρέπει να ξαναπροσπαθήσουμε." + " Εάν ανησυχείς πάρα πολύ για κάποιο λογο, μπορείς να [https://github.com/Tillerino/Tillerinobot/wiki/Contact του το πείς]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Δεν υπάρχουν δεδομένα για τα ζητούμενα mods." ; } @Override public Response welcomeUser(OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { return new Message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { return new Message("Καλώς ήρθες πίσω," + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { return new Message(apiUser.getUserName() + "...") .then(new Message("...είσαι εσύ αυτός; Πάει πολύς καιρός!")) .then(new Message("Είναι ωραίο να σε έχουμε πίσω. Μπορώ να σε ενδιαφέρω με μια πρόταση;")); } else { String[] messages = { "Φαίνεσαι σαν να θες μια πρόταση.", "Πόσο ωραίο να σε βλέπω :)", "Ο αγαπημένος μου άνθρωπος. (Μην το πείς στούς άλλους!)", "Τι ευχάριστη έκπληξη! ^.^", "Περίμενα ότι θα εμφανιστείς. Όλοι οι άλλοι άνθρωποι ειναι μπούφοι, αλλα μην τους πείς ότι το ειπα! :3", "Τι έχεις την διάθεση να κάνεις σήμερα;", }; Random random = new Random(); String message = messages[random.nextInt(messages.length)]; return new Message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Άγνωστη εντολή \"" + command + "\". Πληκτρολόγησε !help αν χρειάζεσαι βοήθεια!"; } @Override public String noInformationForMods() { return "Συγνώμη, δεν μπορώ να παρέχω πληροφορίες για αυτά τα mods αυτή τη στιγμή"; } @Override public String malformattedMods(String mods) { return "Αυτα τα mods δεν φαίνονται σωστά. Τα mods μπορεί να είναι ενας συνδυασμός από DT HR HD HT EZ NC FL SO NF.Συνδυάζοντάς τα χωρίς κενά ή ειδικούς χαρακτήρες. Παράδειγμα: !with HDHR, !with DTEZ"; } @Override public String noLastSongInfo() { return "Δεν θυμάμαι να πήρες καμία πληροφορία τραγουδιού..."; } @Override public String tryWithMods() { return "Δοκίμασε αυτό το τραγούδι με μερικά mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Δοκίμασε αυτό το τραγούδι με " + Mods.toShortNamesContinuous(mods); } @Override public String excuseForError() { return "Συγνώμη, υπήρχε αυτή η όμορφη σειρά από άσσους και μηδενικά και παρασύρθηκα. Τί ήθελες ξανα;"; } @Override public String complaint() { return "Το παράπονό σου κατατέθηκε. Ο Tillerino θα το κοιτάξει όταν μπορέσει."; } @Override public Response hug(OsuApiUser apiUser) { return new Message("Έλα εδώ εσυ!") .then(new Action("Αγκαλιάζει " + apiUser.getUserName())); } @Override public String help() { return "Γειά! Είμαι το ρομπότ που σκότωσε τον Tillerino και πήρε τον λογαριασμό του. Πλάκα κάνω, αλλά όντως χρησιμοποιώ τον λογαριασμό αρκετά." + " [https://twitter.com/Tillerinobot status και updates]" + " - [https://github.com/Tillerino/Tillerinobot/wiki εντολές]" + " - [http://ppaddict.tillerino.org/ ppaddict]" + " - [https://github.com/Tillerino/Tillerinobot/wiki/Contact επικοινωνία]"; } @Override public String faq() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ Συχνά ερωτώμενες ερωτήσεις]"; } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Συγνώμη, σε αυτό το σημείο " + feature + "είναι μόνο διαθέσιμο για παίκτες που εχουν ξεπερασμένη τάξη " + minRank + "."; } @Override public String mixedNomodAndMods() { return "Τί εννοείς nomods με mods;"; } @Override public String outOfRecommendations() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do" + " Έχω προτίνει ό,τι μπορώ να σκεφτώ]. " + " Προσπάθησε άλλες επιλογές προτάσεων ή χρησιμοποίησε το !rest. Εάν δεν είσαι σίγουρος, έλεγξε το !help."; } @Override public String notRanked() { return "Απ' ότι φαίνεται αυτό το τραγούδι δεν είναι εγκεκριμένο."; } @Override public String invalidAccuracy(String acc) { return "Άκυρη ακρίβεια: \"" + acc + "\""; } @Override public Response optionalCommentOnLanguage(OsuApiUser apiUser) { return new Message("Ο N for Niko με βοήθησε να μάθω Ελληνικά"); } @Override public String invalidChoice(String invalid, String choices) { return "Συγνώμη, αλλά \"" + invalid + "\" δεν υπολογίζει. Προσπάθησε αυτά: " + choices + "!"; } @Override public String setFormat() { return "Η σύνταξη για να ρυθμιστεί η παράμετρος είναι !set ρύθμιση ποσού. Δοκίμασε !help εάν χρειάζεσαι περισσότερες υποδείξεις."; } @Override public String apiTimeoutException() { return new Default().apiTimeoutException(); } @Override public String noRecentPlays() { return new Default().noRecentPlays(); } @Override public String isSetId() { return new Default().isSetId(); } }
Banbeucmas/Tillerinobot
tillerinobot/src/main/java/tillerino/tillerinobot/lang/Greek.java
3,297
//github.com/Tillerino/Tillerinobot/wiki/FAQ Συχνά ερωτώμενες ερωτήσεις]";
line_comment
el
package tillerino.tillerinobot.lang; import java.util.List; import java.util.Random; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import tillerino.tillerinobot.CommandHandler.Action; import tillerino.tillerinobot.CommandHandler.Message; import tillerino.tillerinobot.CommandHandler.Response; /** * @author Till https://github.com/nikosbks https://osu.ppy.sh/u/3619345 */ public class Greek implements Language { @Override public String unknownBeatmap() { return "Συγνώμη, δεν γνωρίζω αυτό το τραγούδι. Ίσως είναι αρκετά νεο, πολυ δύσκολο, μη εγκεκριμένο ή να μην είναι για το osu standard mode." ; } @Override public String internalException(String marker) { return "Εχ... μάλλον φαίνεται ότι ο ανθρώπινος Tillerino έκανε μαντάρα την σύνδεσή μου." +" Εάν δεν το παρατηρήσει σύντομα, μπορείς [https://github.com/Tillerino/Tillerinobot/wiki/Contact να τον ενημερώσεις]; (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Τί συμβαίνει; Παίρνω μονο παραλογίες από τον server του osu. Μπορείς να μου πείς τι σημαίνει αυτο; 0011101001010000" + " Ο ανθρώπινος Tillerino λέει ότι δεν υπάρχει κάτι για να ανησυχείς, και ότι πρέπει να ξαναπροσπαθήσουμε." + " Εάν ανησυχείς πάρα πολύ για κάποιο λογο, μπορείς να [https://github.com/Tillerino/Tillerinobot/wiki/Contact του το πείς]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Δεν υπάρχουν δεδομένα για τα ζητούμενα mods." ; } @Override public Response welcomeUser(OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { return new Message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { return new Message("Καλώς ήρθες πίσω," + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { return new Message(apiUser.getUserName() + "...") .then(new Message("...είσαι εσύ αυτός; Πάει πολύς καιρός!")) .then(new Message("Είναι ωραίο να σε έχουμε πίσω. Μπορώ να σε ενδιαφέρω με μια πρόταση;")); } else { String[] messages = { "Φαίνεσαι σαν να θες μια πρόταση.", "Πόσο ωραίο να σε βλέπω :)", "Ο αγαπημένος μου άνθρωπος. (Μην το πείς στούς άλλους!)", "Τι ευχάριστη έκπληξη! ^.^", "Περίμενα ότι θα εμφανιστείς. Όλοι οι άλλοι άνθρωποι ειναι μπούφοι, αλλα μην τους πείς ότι το ειπα! :3", "Τι έχεις την διάθεση να κάνεις σήμερα;", }; Random random = new Random(); String message = messages[random.nextInt(messages.length)]; return new Message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Άγνωστη εντολή \"" + command + "\". Πληκτρολόγησε !help αν χρειάζεσαι βοήθεια!"; } @Override public String noInformationForMods() { return "Συγνώμη, δεν μπορώ να παρέχω πληροφορίες για αυτά τα mods αυτή τη στιγμή"; } @Override public String malformattedMods(String mods) { return "Αυτα τα mods δεν φαίνονται σωστά. Τα mods μπορεί να είναι ενας συνδυασμός από DT HR HD HT EZ NC FL SO NF.Συνδυάζοντάς τα χωρίς κενά ή ειδικούς χαρακτήρες. Παράδειγμα: !with HDHR, !with DTEZ"; } @Override public String noLastSongInfo() { return "Δεν θυμάμαι να πήρες καμία πληροφορία τραγουδιού..."; } @Override public String tryWithMods() { return "Δοκίμασε αυτό το τραγούδι με μερικά mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Δοκίμασε αυτό το τραγούδι με " + Mods.toShortNamesContinuous(mods); } @Override public String excuseForError() { return "Συγνώμη, υπήρχε αυτή η όμορφη σειρά από άσσους και μηδενικά και παρασύρθηκα. Τί ήθελες ξανα;"; } @Override public String complaint() { return "Το παράπονό σου κατατέθηκε. Ο Tillerino θα το κοιτάξει όταν μπορέσει."; } @Override public Response hug(OsuApiUser apiUser) { return new Message("Έλα εδώ εσυ!") .then(new Action("Αγκαλιάζει " + apiUser.getUserName())); } @Override public String help() { return "Γειά! Είμαι το ρομπότ που σκότωσε τον Tillerino και πήρε τον λογαριασμό του. Πλάκα κάνω, αλλά όντως χρησιμοποιώ τον λογαριασμό αρκετά." + " [https://twitter.com/Tillerinobot status και updates]" + " - [https://github.com/Tillerino/Tillerinobot/wiki εντολές]" + " - [http://ppaddict.tillerino.org/ ppaddict]" + " - [https://github.com/Tillerino/Tillerinobot/wiki/Contact επικοινωνία]"; } @Override public String faq() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ Συχνά<SUF> } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Συγνώμη, σε αυτό το σημείο " + feature + "είναι μόνο διαθέσιμο για παίκτες που εχουν ξεπερασμένη τάξη " + minRank + "."; } @Override public String mixedNomodAndMods() { return "Τί εννοείς nomods με mods;"; } @Override public String outOfRecommendations() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do" + " Έχω προτίνει ό,τι μπορώ να σκεφτώ]. " + " Προσπάθησε άλλες επιλογές προτάσεων ή χρησιμοποίησε το !rest. Εάν δεν είσαι σίγουρος, έλεγξε το !help."; } @Override public String notRanked() { return "Απ' ότι φαίνεται αυτό το τραγούδι δεν είναι εγκεκριμένο."; } @Override public String invalidAccuracy(String acc) { return "Άκυρη ακρίβεια: \"" + acc + "\""; } @Override public Response optionalCommentOnLanguage(OsuApiUser apiUser) { return new Message("Ο N for Niko με βοήθησε να μάθω Ελληνικά"); } @Override public String invalidChoice(String invalid, String choices) { return "Συγνώμη, αλλά \"" + invalid + "\" δεν υπολογίζει. Προσπάθησε αυτά: " + choices + "!"; } @Override public String setFormat() { return "Η σύνταξη για να ρυθμιστεί η παράμετρος είναι !set ρύθμιση ποσού. Δοκίμασε !help εάν χρειάζεσαι περισσότερες υποδείξεις."; } @Override public String apiTimeoutException() { return new Default().apiTimeoutException(); } @Override public String noRecentPlays() { return new Default().noRecentPlays(); } @Override public String isSetId() { return new Default().isSetId(); } }
28487_4
/* * Copyright (C) 2005-2012 BetaCONCEPT Limited * * This file is part of Astroboa. * * Astroboa is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Astroboa is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Astroboa. If not, see <http://www.gnu.org/licenses/>. */ package org.betaconceptframework.astroboa.portal.form; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.betaconceptframework.astroboa.api.model.BooleanProperty; import org.betaconceptframework.astroboa.api.model.CalendarProperty; import org.betaconceptframework.astroboa.api.model.ContentObject; import org.betaconceptframework.astroboa.api.model.RepositoryUser; import org.betaconceptframework.astroboa.api.model.StringProperty; import org.betaconceptframework.astroboa.api.model.Topic; import org.betaconceptframework.astroboa.api.model.TopicReferenceProperty; import org.betaconceptframework.astroboa.api.model.definition.CmsPropertyDefinition; import org.betaconceptframework.astroboa.api.model.io.FetchLevel; import org.betaconceptframework.astroboa.api.model.io.ResourceRepresentationType; import org.betaconceptframework.astroboa.client.AstroboaClient; import org.betaconceptframework.astroboa.portal.utility.CalendarUtils; import org.betaconceptframework.astroboa.portal.utility.CmsUtils; import org.betaconceptframework.astroboa.portal.utility.PortalStringConstants; import org.betaconceptframework.ui.jsf.utility.JSFUtilities; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Out; import org.jboss.seam.faces.Renderer; import org.jboss.seam.international.LocaleSelector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Gregory Chomatas ([email protected]) * @author Savvas Triantafyllou ([email protected]) * */ public abstract class AbstractForm<T extends AstroboaClient> { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); private Map<String, Object> formParams = new HashMap<String, Object>(); /* * This map can store values which do not correspond to content object properties, * like password confirmation input field. It is not used by form infrastructure. * * It may be used from implementor as a container for any key, value pair */ private Map<String, Object> tempParams = new HashMap<String, Object>(); @Out(required=false) protected ContentObject formContentObject = null; @In(value="#{captcha.challengeText}", required=false) private String challengeText; @In(value="#{captcha.response}", required=false) private String challengeResponse; @In(create=true) protected Renderer renderer; @In protected LocaleSelector localeSelector; protected List<String> formSubmissionMessageList = new ArrayList<String>(); private Boolean successfulFormSubmission; @In(create=true) protected CmsUtils cmsUtils; @In(create=true) protected CalendarUtils calendarUtils; private final static String STATUS_OF_USER_SUBMITTED_FORM = "submittedByExternalUser"; private final static String WORKFLOW_FOR_USER_SUBMITTED_FORM = "webPublishing"; public String submitForm() { formContentObject = null; try { formSubmissionMessageList = new ArrayList<String>(); checkChallengeResponsePhase(); formContentObject = getFormsRepositoryClient().getCmsRepositoryEntityFactory().newObjectForType(getFormType()); applyDefaultValuesPhase(formParams, formContentObject); validateAndApplyFormValuesPhase(formParams, formContentObject); // run custom form post processing code before saving postValidateAndApplyValuesPhase(formParams, formContentObject); savePhase(formContentObject); postSavePhase(formParams, formContentObject); //return "/successfulFormSubmission.xhtml"; successfulFormSubmission = true; return null; } catch (ChallengeValidationException e) { logger.info("An null or invalid form challenge response was provided"); return null; } catch (FormValidationException e) { logger.warn("An error occured during validation", e); if (CollectionUtils.isEmpty(formSubmissionMessageList)) { formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.unknown.error", null)); } return null; } catch (Exception e) { logger.error("Failed to save user submitted form", e); formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.unknown.error", null)); if (formContentObject != null) { formContentObject.setId(null); } return null; } } private void savePhase(ContentObject formContentObject) throws Exception { getFormsRepositoryClient().getContentService().save(formContentObject, false, true, null); formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.successful.submission", null)); formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.successful.submission.key.message", new String[]{formContentObject.getId()})); formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.successful.submission.info.message", null)); } private void checkChallengeResponsePhase() throws ChallengeValidationException{ if (enableCheckForChallengeRespone()) { if (StringUtils.isBlank(challengeResponse)) { //String message = "Δεν συμπληρώσατε τα γράμματα που εμφανίζονται στην εικόνα. Παρακαλώ συμπληρώστε τα γράμματα που βλέπετε στην εικόνα."; formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.empty.challenge.response", null)); throw new ChallengeValidationException("Null Challenge Responce"); } if (challengeText != null && challengeResponse != null && !challengeResponse.equals(challengeText)) { //String message = "Δεν συμπληρώσατε σωστά τα γράμματα που εμφανίζονται στην εικόνα. Παρακαλώ συμπληρώστε τα γράμματα που βλέπετε στην εικόνα."; formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.empty.challenge.response", null)); throw new ChallengeValidationException("challengeText=" + challengeText + " ,challenge responce=" + challengeResponse + " - No Match"); } } } private void validateAndApplyFormValuesPhase(Map<String,Object> formParams, ContentObject formContentObject) throws Exception { for (String formParameter : formParams.keySet()) { applyFormParameterToContentObjectProperty(formContentObject, formParams, formParameter); } } private void applyDefaultValuesPhase(Map<String,Object> formParams, ContentObject formContentObject) throws Exception { StringProperty statusProperty = (StringProperty) formContentObject.getCmsProperty("profile.contentObjectStatus"); statusProperty.setSimpleTypeValue(STATUS_OF_USER_SUBMITTED_FORM); StringProperty workflowProperty = (StringProperty) formContentObject.getCmsProperty("workflow.managedThroughWorkflow"); workflowProperty.setSimpleTypeValue(WORKFLOW_FOR_USER_SUBMITTED_FORM); // StringProperty commentsProperty = (StringProperty) formContentObject.addChildCmsPropertyTemplate("internalComments"); // commentsProperty.setSimpleTypeValue("External Submitter Name: " + firstName + " " + lastName + "\n" + // "email: " + email + "\n" + // "telephone: " + telephone + "\n" + // "Organization Name: " + organizationName); //Form submitter is ALWAYS SYSTEM Repository User RepositoryUser formSubmitter = getFormsRepositoryClient().getRepositoryUserService().getSystemRepositoryUser(); if (formSubmitter == null) { logger.error("Retrieved a null User for form submitter. Cannot proceed to save submitted event"); formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.empty.challenge.response", null)); throw new Exception("Retrieved a null User for form submitter. Cannot proceed to save submitted event"); } formContentObject.setOwner(formSubmitter); Calendar now = GregorianCalendar.getInstance(JSFUtilities.getTimeZone(), JSFUtilities.getLocale()); CalendarProperty createdProperty = (CalendarProperty) formContentObject.getCmsProperty("profile.created"); createdProperty.setSimpleTypeValue(now); CalendarProperty modifiedProperty = (CalendarProperty) formContentObject.getCmsProperty("profile.modified"); modifiedProperty.setSimpleTypeValue(now); // supply a default title, language and author // these may be overwritten by formPostProcessing method StringProperty titleProperty = (StringProperty) formContentObject.getCmsProperty("profile.title"); titleProperty.setSimpleTypeValue(formContentObject.getTypeDefinition().getDisplayName().getLocalizedLabelForLocale(JSFUtilities.getLocaleAsString()) + " " + calendarUtils.convertDateToString(now.getTime(), PortalStringConstants.DATE_FORMAT_PATTERN)); StringProperty languageProperty = (StringProperty) formContentObject.getCmsProperty("profile.language"); languageProperty.addSimpleTypeValue(JSFUtilities.getLocaleAsString()); StringProperty creatorProperty = (StringProperty) formContentObject.getCmsProperty("profile.creator"); creatorProperty.addSimpleTypeValue("anonymous"); applyAccessibilityPropertiesPhase(formContentObject); } private void applyFormParameterToContentObjectProperty(ContentObject formContentObject, Map<String, Object> formParameters, String formParameter) throws Exception, FormValidationException { CmsPropertyDefinition formParameterDefinition = (CmsPropertyDefinition) getFormsRepositoryClient().getDefinitionService().getCmsDefinition(formContentObject.getContentObjectType()+"."+formParameter, ResourceRepresentationType.DEFINITION_INSTANCE,false); // check if field is defined if (formParameterDefinition == null) { String errorMessage = "For the provided form parameter: " + formParameter + ", there is no corresponding property in the ContentObject Type:" + formContentObject.getContentObjectType() + "which models the form"; throw new FormValidationException(errorMessage); } Object formParameterValue = formParameters.get(formParameter); String requiredFieldErrorMessage = "Το πεδίο " + "'" + formParameterDefinition.getDisplayName().getLocalizedLabelForLocale(JSFUtilities.getLocaleAsString()) + "'" + " είναι υποχρεωτικό. Παρακαλώ βάλτε τιμή"; switch (formParameterDefinition.getValueType()) { case String: { // check if form value is of the appropriate type if (!(formParameterValue instanceof String)) { throw new FormValidationException("Invalid form field value type for property:" + formParameter + " A String value was expected"); } // check if no value has been provided for a mandatory property if (formParameterDefinition.isMandatory() && StringUtils.isBlank((String) formParameterValue)) { formSubmissionMessageList.add(requiredFieldErrorMessage); throw new FormValidationException(requiredFieldErrorMessage); } StringProperty formParameterProperty = (StringProperty) formContentObject.getCmsProperty(formParameter); if (StringUtils.isBlank((String) formParameterValue)) { formParameterProperty.setSimpleTypeValue(null); } else { formParameterProperty.setSimpleTypeValue((String)formParameterValue); } break; } case Date: { // check if form value is of the appropriate type if (!(formParameterValue instanceof Date)) { throw new FormValidationException("Invalid form field value type for property:" + formParameter + " A Date value was expected"); } // check if no value has been provided for a mandatory property if (formParameterDefinition.isMandatory() && formParameterValue == null) { formSubmissionMessageList.add(requiredFieldErrorMessage); throw new FormValidationException(requiredFieldErrorMessage); } CalendarProperty formParameterProperty = (CalendarProperty) formContentObject.getCmsProperty(formParameter); if (formParameterValue == null) { formParameterProperty.setSimpleTypeValue(null); } else { Calendar calendar = GregorianCalendar.getInstance(JSFUtilities.getTimeZone(), JSFUtilities.getLocale()); calendar.setTime(((Date)formParameters.get(formParameter))); formParameterProperty.setSimpleTypeValue(calendar); } break; } case Boolean: { // check if form value is of the appropriate type if (!(formParameterValue instanceof Boolean)) { throw new FormValidationException("Invalid form field value type for property:" + formParameter + " A Boolean value was expected"); } // check if no value has been provided for a mandatory property if (formParameterDefinition.isMandatory() && formParameterValue == null) { formSubmissionMessageList.add(requiredFieldErrorMessage); throw new FormValidationException(requiredFieldErrorMessage); } BooleanProperty formParameterProperty = (BooleanProperty) formContentObject.getCmsProperty(formParameter); if (formParameterValue == null) { formParameterProperty.setSimpleTypeValue(null); } else { formParameterProperty.setSimpleTypeValue((Boolean)formParameters.get(formParameter)); } break; } case TopicReference: { // check if form value is of the appropriate type // we expect a string which corresponds to the id of an existing topic if (!(formParameterValue instanceof String)) { throw new FormValidationException("Invalid form field value type for property:" + formParameter + " A string value corresponding to the id of an existing topic was expected"); } // check if no value has been provided for a mandatory property if (formParameterDefinition.isMandatory() && StringUtils.isBlank((String) formParameterValue)) { formSubmissionMessageList.add(requiredFieldErrorMessage); throw new FormValidationException(requiredFieldErrorMessage); } TopicReferenceProperty formParameterProperty = (TopicReferenceProperty) formContentObject.getCmsProperty(formParameter); if (StringUtils.isBlank((String)formParameterValue)) { formParameterProperty.setSimpleTypeValue(null); } else { Topic retrievedTopic = getFormsRepositoryClient().getTopicService().getTopic((String) formParameterValue, ResourceRepresentationType.TOPIC_INSTANCE, FetchLevel.ENTITY, false); if (retrievedTopic == null) { throw new Exception("Not topic found for the provided topic id:" + formParameterValue); } formParameterProperty.setSimpleTypeValue(retrievedTopic); } break; } default: throw new Exception("Not supported value type:" + formParameterDefinition.getValueType() + " for parameter:" + formParameter); } } // run custom validation rules and do custom processing to formContentObject or formParams public abstract void postValidateAndApplyValuesPhase(Map<String,Object> formParams, ContentObject formContentObject) throws Exception; // run additional actions after successful form saving, e.g. send email, start a workflow, etc. public abstract void postSavePhase(Map<String,Object> formParams, ContentObject formContentObject) throws Exception; // called inside applyDefaultValuesPhase and permit custom accessibility setup protected abstract void applyAccessibilityPropertiesPhase(ContentObject formContentObject); //called inside checkChallengeResponsePhase and allow users to disable challenge response in case they do //not display captcha in their form protected abstract boolean enableCheckForChallengeRespone(); public Map<String, Object> getFormParams() { return formParams; } public abstract String getFormType(); protected abstract T getFormsRepositoryClient(); public ContentObject getFormContentObject() { return formContentObject; } public List<String> getFormSubmissionMessageList() { return formSubmissionMessageList; } public Boolean getSuccessfulFormSubmission() { return successfulFormSubmission; } public void setSuccessfulFormSubmission(Boolean successfulFormSubmission) { this.successfulFormSubmission = successfulFormSubmission; } public Map<String, Object> getTempParams() { return tempParams; } }
BetaCONCEPT/astroboa
astroboa-portal-commons/src/main/java/org/betaconceptframework/astroboa/portal/form/AbstractForm.java
4,286
//String message = "Δεν συμπληρώσατε τα γράμματα που εμφανίζονται στην εικόνα. Παρακαλώ συμπληρώστε τα γράμματα που βλέπετε στην εικόνα.";
line_comment
el
/* * Copyright (C) 2005-2012 BetaCONCEPT Limited * * This file is part of Astroboa. * * Astroboa is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Astroboa is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Astroboa. If not, see <http://www.gnu.org/licenses/>. */ package org.betaconceptframework.astroboa.portal.form; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.betaconceptframework.astroboa.api.model.BooleanProperty; import org.betaconceptframework.astroboa.api.model.CalendarProperty; import org.betaconceptframework.astroboa.api.model.ContentObject; import org.betaconceptframework.astroboa.api.model.RepositoryUser; import org.betaconceptframework.astroboa.api.model.StringProperty; import org.betaconceptframework.astroboa.api.model.Topic; import org.betaconceptframework.astroboa.api.model.TopicReferenceProperty; import org.betaconceptframework.astroboa.api.model.definition.CmsPropertyDefinition; import org.betaconceptframework.astroboa.api.model.io.FetchLevel; import org.betaconceptframework.astroboa.api.model.io.ResourceRepresentationType; import org.betaconceptframework.astroboa.client.AstroboaClient; import org.betaconceptframework.astroboa.portal.utility.CalendarUtils; import org.betaconceptframework.astroboa.portal.utility.CmsUtils; import org.betaconceptframework.astroboa.portal.utility.PortalStringConstants; import org.betaconceptframework.ui.jsf.utility.JSFUtilities; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Out; import org.jboss.seam.faces.Renderer; import org.jboss.seam.international.LocaleSelector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Gregory Chomatas ([email protected]) * @author Savvas Triantafyllou ([email protected]) * */ public abstract class AbstractForm<T extends AstroboaClient> { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); private Map<String, Object> formParams = new HashMap<String, Object>(); /* * This map can store values which do not correspond to content object properties, * like password confirmation input field. It is not used by form infrastructure. * * It may be used from implementor as a container for any key, value pair */ private Map<String, Object> tempParams = new HashMap<String, Object>(); @Out(required=false) protected ContentObject formContentObject = null; @In(value="#{captcha.challengeText}", required=false) private String challengeText; @In(value="#{captcha.response}", required=false) private String challengeResponse; @In(create=true) protected Renderer renderer; @In protected LocaleSelector localeSelector; protected List<String> formSubmissionMessageList = new ArrayList<String>(); private Boolean successfulFormSubmission; @In(create=true) protected CmsUtils cmsUtils; @In(create=true) protected CalendarUtils calendarUtils; private final static String STATUS_OF_USER_SUBMITTED_FORM = "submittedByExternalUser"; private final static String WORKFLOW_FOR_USER_SUBMITTED_FORM = "webPublishing"; public String submitForm() { formContentObject = null; try { formSubmissionMessageList = new ArrayList<String>(); checkChallengeResponsePhase(); formContentObject = getFormsRepositoryClient().getCmsRepositoryEntityFactory().newObjectForType(getFormType()); applyDefaultValuesPhase(formParams, formContentObject); validateAndApplyFormValuesPhase(formParams, formContentObject); // run custom form post processing code before saving postValidateAndApplyValuesPhase(formParams, formContentObject); savePhase(formContentObject); postSavePhase(formParams, formContentObject); //return "/successfulFormSubmission.xhtml"; successfulFormSubmission = true; return null; } catch (ChallengeValidationException e) { logger.info("An null or invalid form challenge response was provided"); return null; } catch (FormValidationException e) { logger.warn("An error occured during validation", e); if (CollectionUtils.isEmpty(formSubmissionMessageList)) { formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.unknown.error", null)); } return null; } catch (Exception e) { logger.error("Failed to save user submitted form", e); formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.unknown.error", null)); if (formContentObject != null) { formContentObject.setId(null); } return null; } } private void savePhase(ContentObject formContentObject) throws Exception { getFormsRepositoryClient().getContentService().save(formContentObject, false, true, null); formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.successful.submission", null)); formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.successful.submission.key.message", new String[]{formContentObject.getId()})); formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.successful.submission.info.message", null)); } private void checkChallengeResponsePhase() throws ChallengeValidationException{ if (enableCheckForChallengeRespone()) { if (StringUtils.isBlank(challengeResponse)) { //String message<SUF> formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.empty.challenge.response", null)); throw new ChallengeValidationException("Null Challenge Responce"); } if (challengeText != null && challengeResponse != null && !challengeResponse.equals(challengeText)) { //String message = "Δεν συμπληρώσατε σωστά τα γράμματα που εμφανίζονται στην εικόνα. Παρακαλώ συμπληρώστε τα γράμματα που βλέπετε στην εικόνα."; formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.empty.challenge.response", null)); throw new ChallengeValidationException("challengeText=" + challengeText + " ,challenge responce=" + challengeResponse + " - No Match"); } } } private void validateAndApplyFormValuesPhase(Map<String,Object> formParams, ContentObject formContentObject) throws Exception { for (String formParameter : formParams.keySet()) { applyFormParameterToContentObjectProperty(formContentObject, formParams, formParameter); } } private void applyDefaultValuesPhase(Map<String,Object> formParams, ContentObject formContentObject) throws Exception { StringProperty statusProperty = (StringProperty) formContentObject.getCmsProperty("profile.contentObjectStatus"); statusProperty.setSimpleTypeValue(STATUS_OF_USER_SUBMITTED_FORM); StringProperty workflowProperty = (StringProperty) formContentObject.getCmsProperty("workflow.managedThroughWorkflow"); workflowProperty.setSimpleTypeValue(WORKFLOW_FOR_USER_SUBMITTED_FORM); // StringProperty commentsProperty = (StringProperty) formContentObject.addChildCmsPropertyTemplate("internalComments"); // commentsProperty.setSimpleTypeValue("External Submitter Name: " + firstName + " " + lastName + "\n" + // "email: " + email + "\n" + // "telephone: " + telephone + "\n" + // "Organization Name: " + organizationName); //Form submitter is ALWAYS SYSTEM Repository User RepositoryUser formSubmitter = getFormsRepositoryClient().getRepositoryUserService().getSystemRepositoryUser(); if (formSubmitter == null) { logger.error("Retrieved a null User for form submitter. Cannot proceed to save submitted event"); formSubmissionMessageList.add(JSFUtilities.getLocalizedMessage("form.empty.challenge.response", null)); throw new Exception("Retrieved a null User for form submitter. Cannot proceed to save submitted event"); } formContentObject.setOwner(formSubmitter); Calendar now = GregorianCalendar.getInstance(JSFUtilities.getTimeZone(), JSFUtilities.getLocale()); CalendarProperty createdProperty = (CalendarProperty) formContentObject.getCmsProperty("profile.created"); createdProperty.setSimpleTypeValue(now); CalendarProperty modifiedProperty = (CalendarProperty) formContentObject.getCmsProperty("profile.modified"); modifiedProperty.setSimpleTypeValue(now); // supply a default title, language and author // these may be overwritten by formPostProcessing method StringProperty titleProperty = (StringProperty) formContentObject.getCmsProperty("profile.title"); titleProperty.setSimpleTypeValue(formContentObject.getTypeDefinition().getDisplayName().getLocalizedLabelForLocale(JSFUtilities.getLocaleAsString()) + " " + calendarUtils.convertDateToString(now.getTime(), PortalStringConstants.DATE_FORMAT_PATTERN)); StringProperty languageProperty = (StringProperty) formContentObject.getCmsProperty("profile.language"); languageProperty.addSimpleTypeValue(JSFUtilities.getLocaleAsString()); StringProperty creatorProperty = (StringProperty) formContentObject.getCmsProperty("profile.creator"); creatorProperty.addSimpleTypeValue("anonymous"); applyAccessibilityPropertiesPhase(formContentObject); } private void applyFormParameterToContentObjectProperty(ContentObject formContentObject, Map<String, Object> formParameters, String formParameter) throws Exception, FormValidationException { CmsPropertyDefinition formParameterDefinition = (CmsPropertyDefinition) getFormsRepositoryClient().getDefinitionService().getCmsDefinition(formContentObject.getContentObjectType()+"."+formParameter, ResourceRepresentationType.DEFINITION_INSTANCE,false); // check if field is defined if (formParameterDefinition == null) { String errorMessage = "For the provided form parameter: " + formParameter + ", there is no corresponding property in the ContentObject Type:" + formContentObject.getContentObjectType() + "which models the form"; throw new FormValidationException(errorMessage); } Object formParameterValue = formParameters.get(formParameter); String requiredFieldErrorMessage = "Το πεδίο " + "'" + formParameterDefinition.getDisplayName().getLocalizedLabelForLocale(JSFUtilities.getLocaleAsString()) + "'" + " είναι υποχρεωτικό. Παρακαλώ βάλτε τιμή"; switch (formParameterDefinition.getValueType()) { case String: { // check if form value is of the appropriate type if (!(formParameterValue instanceof String)) { throw new FormValidationException("Invalid form field value type for property:" + formParameter + " A String value was expected"); } // check if no value has been provided for a mandatory property if (formParameterDefinition.isMandatory() && StringUtils.isBlank((String) formParameterValue)) { formSubmissionMessageList.add(requiredFieldErrorMessage); throw new FormValidationException(requiredFieldErrorMessage); } StringProperty formParameterProperty = (StringProperty) formContentObject.getCmsProperty(formParameter); if (StringUtils.isBlank((String) formParameterValue)) { formParameterProperty.setSimpleTypeValue(null); } else { formParameterProperty.setSimpleTypeValue((String)formParameterValue); } break; } case Date: { // check if form value is of the appropriate type if (!(formParameterValue instanceof Date)) { throw new FormValidationException("Invalid form field value type for property:" + formParameter + " A Date value was expected"); } // check if no value has been provided for a mandatory property if (formParameterDefinition.isMandatory() && formParameterValue == null) { formSubmissionMessageList.add(requiredFieldErrorMessage); throw new FormValidationException(requiredFieldErrorMessage); } CalendarProperty formParameterProperty = (CalendarProperty) formContentObject.getCmsProperty(formParameter); if (formParameterValue == null) { formParameterProperty.setSimpleTypeValue(null); } else { Calendar calendar = GregorianCalendar.getInstance(JSFUtilities.getTimeZone(), JSFUtilities.getLocale()); calendar.setTime(((Date)formParameters.get(formParameter))); formParameterProperty.setSimpleTypeValue(calendar); } break; } case Boolean: { // check if form value is of the appropriate type if (!(formParameterValue instanceof Boolean)) { throw new FormValidationException("Invalid form field value type for property:" + formParameter + " A Boolean value was expected"); } // check if no value has been provided for a mandatory property if (formParameterDefinition.isMandatory() && formParameterValue == null) { formSubmissionMessageList.add(requiredFieldErrorMessage); throw new FormValidationException(requiredFieldErrorMessage); } BooleanProperty formParameterProperty = (BooleanProperty) formContentObject.getCmsProperty(formParameter); if (formParameterValue == null) { formParameterProperty.setSimpleTypeValue(null); } else { formParameterProperty.setSimpleTypeValue((Boolean)formParameters.get(formParameter)); } break; } case TopicReference: { // check if form value is of the appropriate type // we expect a string which corresponds to the id of an existing topic if (!(formParameterValue instanceof String)) { throw new FormValidationException("Invalid form field value type for property:" + formParameter + " A string value corresponding to the id of an existing topic was expected"); } // check if no value has been provided for a mandatory property if (formParameterDefinition.isMandatory() && StringUtils.isBlank((String) formParameterValue)) { formSubmissionMessageList.add(requiredFieldErrorMessage); throw new FormValidationException(requiredFieldErrorMessage); } TopicReferenceProperty formParameterProperty = (TopicReferenceProperty) formContentObject.getCmsProperty(formParameter); if (StringUtils.isBlank((String)formParameterValue)) { formParameterProperty.setSimpleTypeValue(null); } else { Topic retrievedTopic = getFormsRepositoryClient().getTopicService().getTopic((String) formParameterValue, ResourceRepresentationType.TOPIC_INSTANCE, FetchLevel.ENTITY, false); if (retrievedTopic == null) { throw new Exception("Not topic found for the provided topic id:" + formParameterValue); } formParameterProperty.setSimpleTypeValue(retrievedTopic); } break; } default: throw new Exception("Not supported value type:" + formParameterDefinition.getValueType() + " for parameter:" + formParameter); } } // run custom validation rules and do custom processing to formContentObject or formParams public abstract void postValidateAndApplyValuesPhase(Map<String,Object> formParams, ContentObject formContentObject) throws Exception; // run additional actions after successful form saving, e.g. send email, start a workflow, etc. public abstract void postSavePhase(Map<String,Object> formParams, ContentObject formContentObject) throws Exception; // called inside applyDefaultValuesPhase and permit custom accessibility setup protected abstract void applyAccessibilityPropertiesPhase(ContentObject formContentObject); //called inside checkChallengeResponsePhase and allow users to disable challenge response in case they do //not display captcha in their form protected abstract boolean enableCheckForChallengeRespone(); public Map<String, Object> getFormParams() { return formParams; } public abstract String getFormType(); protected abstract T getFormsRepositoryClient(); public ContentObject getFormContentObject() { return formContentObject; } public List<String> getFormSubmissionMessageList() { return formSubmissionMessageList; } public Boolean getSuccessfulFormSubmission() { return successfulFormSubmission; } public void setSuccessfulFormSubmission(Boolean successfulFormSubmission) { this.successfulFormSubmission = successfulFormSubmission; } public Map<String, Object> getTempParams() { return tempParams; } }
5767_2
import java.util.Scanner; public class friday13 { public static void main(String[] args) { Scanner input =new Scanner(System.in); System.out.println("Single or Multiple year input ?"); System.out.println("For single year input press (s)"); System.out.println("For multiple year input press (m)"); while (true) { char selector = input.next().charAt(0); //Selection Zone // if (selector=='s') { System.out.println("Enter the desired year:"); int year = input.nextInt(); int diff = year-2012; int k = 0; int extraday; if(diff >= 0) { if(diff%4 != 0) { k = 1; } extraday = (diff/4)*5 + (diff%4 + k) ; extraday = extraday - ((diff+11)/100); // αφαιρει τα δισεκτα που μπηκαν λαθος πριν extraday = extraday + ((diff+11)/400); // προσθετη αυτα που εβγαλε λαθος η προηγουμενη εντολη extraday = extraday % 7 ; // αφου τελειωσει με τις πραξεις κανει το % 7 για να βρει την εξτρα μερα } else { if(diff%4 != 3) { k = -1; } extraday = ((diff/4)*5)+(diff%4 + k) ; extraday = extraday + ((diff-77)/100); // -77 ωστε η διαφορα να γινει - 100 extraday = extraday - ((diff-377)/400); // -377 διοτι πρεπει να μετραει το 2000 σαν δισεκτο extraday = extraday % 7; extraday = 8 + extraday ; } int month = 1; int feb = 1; if (year%4!=0 || ( year%100==0 & year%400!=0 ) ) { feb = 0; } System.out.println("Stay in your bed at the following dates :"); if (extraday%7 == 0 ) { System.out.println("13/" + month + "/" + year ); } month++; extraday += 3 ; if (extraday%7 == 0 ) { System.out.println("13/" + month + "/" + year); } month++; extraday += feb; int c = 3 ; for(int i= 3; i<=9 ; i++) { if (extraday%7 ==0 ) { System.out.println("13/" + month + "/" + year); } extraday = extraday + 3*(i%2) - 2 * ((i%2)-1) ; month++; c++ ; if (c==8) { i = 4; } } break; } else if (selector == 'm') { System.out.println("Enter the desired years:"); int year = input.nextInt(), year2 = input.nextInt(); int diff ; int distance = year2 - year ; System.out.println("Stay in your bed at the following dates :"); for (int i=0 ; i<=distance-1 ; i++) { diff = year-2012; int k = 0; int extraday; if(diff >= 0) { if(diff%4 != 0) { k = 1; } extraday = (diff/4)*5 + (diff%4 + k) ; extraday = extraday - ((diff+11)/100); // αφαιρει τα δισεκτα που μπηκαν λαθος πριν extraday = extraday + ((diff+11)/400); // προσθετη αυτα που εβγαλε λαθος η προηγουμενη εντολη extraday = extraday % 7 ; // αφου τελειωσει με τις πραξεις κανει το % 7 για να βρει την εξτρα μερα } else { if(diff%4 != 3) { k = -1; } extraday = ((diff/4)*5)+(diff%4 + k) ; extraday = extraday + ((diff-77)/100); // -77 ωστε η διαφορα να γινει - 100 extraday = extraday - ((diff-377)/400); // -377 διοτι πρεπει να μετραει το 2000 σαν δισεκτο extraday = extraday % 7; extraday = 8 + extraday ; } int month = 1; int feb = 1; if (year%4!=0 || ( year%100==0 & year%400!=0 ) ) { feb = 0; } if (extraday%7 == 0 ) { System.out.println("13/" + month + "/" + year ); } month++; extraday += 3 ; if (extraday%7 == 0 ) { System.out.println("13/" + month + "/" + year); } month++; extraday += feb; int c = 3 ; for (int j =3 ;j<=9 ; j++) { if (extraday%7 ==0 ) { System.out.println("13/" + month + "/" + year); } extraday = extraday + 3*(j%2) - 2 * ((j%2)-1) ; month++; c++ ; if (c==8) { j = 4; } } year += 1 ; } break; } else { System.out.println("Try again you dumb fuck !"); continue; } } } }
Bilkouristas/Friday13th
Friday13finder/src/friday13.java
1,761
// προσθετη αυτα που εβγαλε λαθος η προηγουμενη εντολη
line_comment
el
import java.util.Scanner; public class friday13 { public static void main(String[] args) { Scanner input =new Scanner(System.in); System.out.println("Single or Multiple year input ?"); System.out.println("For single year input press (s)"); System.out.println("For multiple year input press (m)"); while (true) { char selector = input.next().charAt(0); //Selection Zone // if (selector=='s') { System.out.println("Enter the desired year:"); int year = input.nextInt(); int diff = year-2012; int k = 0; int extraday; if(diff >= 0) { if(diff%4 != 0) { k = 1; } extraday = (diff/4)*5 + (diff%4 + k) ; extraday = extraday - ((diff+11)/100); // αφαιρει τα δισεκτα που μπηκαν λαθος πριν extraday = extraday + ((diff+11)/400); // προσθετη αυτα<SUF> extraday = extraday % 7 ; // αφου τελειωσει με τις πραξεις κανει το % 7 για να βρει την εξτρα μερα } else { if(diff%4 != 3) { k = -1; } extraday = ((diff/4)*5)+(diff%4 + k) ; extraday = extraday + ((diff-77)/100); // -77 ωστε η διαφορα να γινει - 100 extraday = extraday - ((diff-377)/400); // -377 διοτι πρεπει να μετραει το 2000 σαν δισεκτο extraday = extraday % 7; extraday = 8 + extraday ; } int month = 1; int feb = 1; if (year%4!=0 || ( year%100==0 & year%400!=0 ) ) { feb = 0; } System.out.println("Stay in your bed at the following dates :"); if (extraday%7 == 0 ) { System.out.println("13/" + month + "/" + year ); } month++; extraday += 3 ; if (extraday%7 == 0 ) { System.out.println("13/" + month + "/" + year); } month++; extraday += feb; int c = 3 ; for(int i= 3; i<=9 ; i++) { if (extraday%7 ==0 ) { System.out.println("13/" + month + "/" + year); } extraday = extraday + 3*(i%2) - 2 * ((i%2)-1) ; month++; c++ ; if (c==8) { i = 4; } } break; } else if (selector == 'm') { System.out.println("Enter the desired years:"); int year = input.nextInt(), year2 = input.nextInt(); int diff ; int distance = year2 - year ; System.out.println("Stay in your bed at the following dates :"); for (int i=0 ; i<=distance-1 ; i++) { diff = year-2012; int k = 0; int extraday; if(diff >= 0) { if(diff%4 != 0) { k = 1; } extraday = (diff/4)*5 + (diff%4 + k) ; extraday = extraday - ((diff+11)/100); // αφαιρει τα δισεκτα που μπηκαν λαθος πριν extraday = extraday + ((diff+11)/400); // προσθετη αυτα που εβγαλε λαθος η προηγουμενη εντολη extraday = extraday % 7 ; // αφου τελειωσει με τις πραξεις κανει το % 7 για να βρει την εξτρα μερα } else { if(diff%4 != 3) { k = -1; } extraday = ((diff/4)*5)+(diff%4 + k) ; extraday = extraday + ((diff-77)/100); // -77 ωστε η διαφορα να γινει - 100 extraday = extraday - ((diff-377)/400); // -377 διοτι πρεπει να μετραει το 2000 σαν δισεκτο extraday = extraday % 7; extraday = 8 + extraday ; } int month = 1; int feb = 1; if (year%4!=0 || ( year%100==0 & year%400!=0 ) ) { feb = 0; } if (extraday%7 == 0 ) { System.out.println("13/" + month + "/" + year ); } month++; extraday += 3 ; if (extraday%7 == 0 ) { System.out.println("13/" + month + "/" + year); } month++; extraday += feb; int c = 3 ; for (int j =3 ;j<=9 ; j++) { if (extraday%7 ==0 ) { System.out.println("13/" + month + "/" + year); } extraday = extraday + 3*(j%2) - 2 * ((j%2)-1) ; month++; c++ ; if (c==8) { j = 4; } } year += 1 ; } break; } else { System.out.println("Try again you dumb fuck !"); continue; } } } }
1844_0
package com.example.billy.cainstructionquiz; import android.app.Dialog; import android.content.Intent; import android.content.SharedPreferences; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import java.math.RoundingMode; import java.security.SecureRandom; import java.text.DecimalFormat; public class QuizActivity extends AppCompatActivity { private static final String TAG = "button"; private static final String ADDBTN = "addButton"; private static final String SUBBTN = "subButton"; private static final String MULTBTN = "multButton"; private static final String DIVBTN = "divButton"; private static final String QUESTION = "Πόσο κάνει "; private static final String ADDACTION = " σύν "; private static final String SUBACTION = " μείον "; private static final String MULTACTION = " επί "; private static final String DIVACTION = " διά "; private static final String QUESTIONMARK = ";"; private static final String WINMESSAGE = "Μπράβο!"; private static final String LOSEMESSAGE = "Προσπάθησε ξανά, αυτή την φόρα θα τα καταφέρεις!"; private static final String ERRORMESSAGE = "Προσπάθησε ξανά, έδωσες λάθος αριθμό!"; private static final String EASY = "Εύκολο"; private static final String MEDIUM = "Μέτριο"; private static final String HARD = "Δύσκολο"; private SecureRandom random = new SecureRandom(); private int number1; private int number2; private int rightAnswers; private int rightAddAnswers; private int rightSubAnswers; private int rightMultAnswers; private int rightDivAnswers; private int wrongAnswers; private int wrongAddAnswers; private int wrongSubAnswers; private int wrongMultAnswers; private int wrongDivAnswers; private String action=""; private TextView questionTxtView; private EditText answerEditText; private Animation shakeAnimation; private SharedPreferences sharedPref; private SharedPreferences.Editor editor; private String difficulty; private String background_color; @Override protected void onResume() { super.onResume(); String background_color = sharedPref.getString(MainActivity.COLOR, MainActivity.RED); RelativeLayout rl = (RelativeLayout) findViewById(R.id.activity_quiz); switch(background_color){ case MainActivity.GREEN: rl.setBackgroundResource(R.drawable.blackboard_background_green); break; case MainActivity.RED: rl.setBackgroundResource(R.drawable.blackboard_background_red); break; case MainActivity.BLUE: rl.setBackgroundResource(R.drawable.blackboard_background_blue); break; case MainActivity.PINK: rl.setBackgroundResource(R.drawable.blackboard_background_pink); break; case MainActivity.PURPLE: rl.setBackgroundResource(R.drawable.blackboard_background_purple); break; } } @Override protected void onCreate(Bundle savedInstanceState) { sharedPref = PreferenceManager.getDefaultSharedPreferences(this); background_color = sharedPref.getString(MainActivity.COLOR, MainActivity.GREEN); switch(background_color){ case MainActivity.GREEN: setTheme(R.style.AppTheme_Green); break; case MainActivity.RED: setTheme(R.style.AppTheme_Red); break; case MainActivity.BLUE: setTheme(R.style.AppTheme_Blue); break; case MainActivity.PINK: setTheme(R.style.AppTheme_Pink); break; case MainActivity.PURPLE: setTheme(R.style.AppTheme_Purple); break; } super.onCreate(savedInstanceState); setContentView(R.layout.activity_quiz); //Αρχικοποίηση του animation του κουμπιού shakeAnimation = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.shake_effect); questionTxtView = (TextView) findViewById(R.id.questionTxtView); answerEditText = (EditText) findViewById(R.id.answerEditText); //KeyListener για να τρέχει την συνάρτηση υπολογισμού και με το πλήκτρο enter. answerEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) { checkProcess(); return true; } return false; } }); //Αρχικοποίηση του Default SharedPreference Manager και Editor sharedPref = PreferenceManager.getDefaultSharedPreferences(this); editor = sharedPref.edit(); //Εισαγωγή των μεταβλητών από τα SharedPreferrence για τα στατιστικά του παιχνιδιού int defaultValue = getResources().getInteger(R.integer.answers_default); rightAnswers = sharedPref.getInt(getString(R.string.right_answers), defaultValue); rightAddAnswers = sharedPref.getInt(getString(R.string.right_add_answers), defaultValue); rightSubAnswers = sharedPref.getInt(getString(R.string.right_sub_answers), defaultValue); rightMultAnswers = sharedPref.getInt(getString(R.string.right_mult_answers), defaultValue); rightDivAnswers = sharedPref.getInt(getString(R.string.right_div_answers), defaultValue); wrongAnswers = sharedPref.getInt(getString(R.string.wrong_answers), defaultValue); wrongAddAnswers = sharedPref.getInt(getString(R.string.wrong_add_answers), defaultValue); wrongSubAnswers = sharedPref.getInt(getString(R.string.wrong_sub_answers), defaultValue); wrongMultAnswers = sharedPref.getInt(getString(R.string.wrong_mult_answers), defaultValue); wrongDivAnswers = sharedPref.getInt(getString(R.string.wrong_div_answers), defaultValue); //Εισαγωγή της μεταβλητής από τα SharedPreferrence για την δυσκολία του παιχνιδιού //Σε περίπτωση προβλήματος με την μεταβλητή του SharedPreferrence για την δυσκολία να βάζει αυτόματα εύκολο difficulty = sharedPref.getString(MainActivity.DIFFICULTY, EASY); //Αρχικοποίηση των αριθμών για την πράξη βάση της δυσκολίας setRandoms(); //Εύρεση πράξης από τα στοιχεία που προήρθαν από το προηγούμενο Activity String buttonString=""; Intent i = getIntent(); Bundle b = i.getExtras(); if(b!=null) { buttonString = (String) b.get(TAG); } switch(buttonString){ case ADDBTN: action=ADDACTION; break; case SUBBTN: action=SUBACTION; break; case MULTBTN: action=MULTACTION; break; case DIVBTN: action=DIVACTION; break; } questionTxtView.setText(QUESTION+String.valueOf(number1)+action+String.valueOf(number2)+QUESTIONMARK); } private void setRandoms(){ switch(difficulty){ case EASY: number1 = random.nextInt(10 - 1) + 1; number2 = random.nextInt(10 - 1) + 1; break; case MEDIUM: number1 = random.nextInt(100 - 1) + 1; number2 = random.nextInt(100 - 1) + 1; break; case HARD: number1 = random.nextInt(1000 - 1) + 1; number2 = random.nextInt(1000 - 1) + 1; break; } } // Η συνάρτηση dialog παίρνει μια μεταβλητή integer οπού όταν είναι 0 σημαίνει ότι είναι νικητήριο dialog και όταν είναι 1 είναι ηττημένο dialog // ενώ όταν είναι -1 (ή οποιοσδήποτε άλλος ακέραιος) σημαίνει οτι υπήρξε κάποιο πρόβλημα με τον αριθμό. private void dialog(int win_or_lose){ final Dialog dialog = new Dialog(QuizActivity.this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.custom_dialog); TextView text = (TextView) dialog.findViewById(R.id.textView); ImageView image = (ImageView) dialog.findViewById(R.id.image); if(win_or_lose==0){ text.setText(WINMESSAGE); rightAnswers++; editor.putInt(getString(R.string.right_answers), rightAnswers); image.setImageResource(R.drawable.star); final MediaPlayer mediaPlayer = MediaPlayer.create(QuizActivity.this, R.raw.tada); mediaPlayer.start(); mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.reset(); mp.release(); } }); }else if (win_or_lose==1){ image.setImageResource(R.drawable.sad_face); text.setText(LOSEMESSAGE); wrongAnswers++; editor.putInt(getString(R.string.wrong_answers), wrongAnswers); }else{ image.setImageResource(R.drawable.error_icon); text.setText(ERRORMESSAGE); } editor.commit(); dialog.show(); Handler handler = new Handler(); handler.postDelayed( new Runnable() { @Override public void run() { dialog.dismiss(); } }, 5000); } private void resetValues(){ setRandoms(); answerEditText.setText(""); questionTxtView.setText(QUESTION+String.valueOf(number1)+action+String.valueOf(number2)+QUESTIONMARK); } private void checkProcess(){ DecimalFormat df = new DecimalFormat("#.#"); df.setRoundingMode(RoundingMode.HALF_UP); int counter = 0; for( int i=0; i<answerEditText.getText().toString().length(); i++ ) { if( answerEditText.getText().toString().charAt(i) == '.' || answerEditText.getText().toString().charAt(i) == ',') { counter++; } } if(counter==0 || counter==1) { String answer_string = df.format(Double.parseDouble(answerEditText.getText().toString())).replace(',','.'); double answer = Double.parseDouble(answer_string); switch (action) { case ADDACTION: if (answer == (number1 + number2)) { dialog(0); resetValues(); rightAddAnswers++; editor.putInt(getString(R.string.right_add_answers), rightAddAnswers); } else { dialog(1); wrongAddAnswers++; editor.putInt(getString(R.string.wrong_add_answers), wrongAddAnswers); } break; case SUBACTION: if (answer == (number1 - number2)) { dialog(0); resetValues(); rightSubAnswers++; editor.putInt(getString(R.string.right_sub_answers), rightSubAnswers); } else { dialog(1); wrongSubAnswers++; editor.putInt(getString(R.string.wrong_sub_answers), wrongSubAnswers); } break; case MULTACTION: if (answer == (number1 * number2)) { dialog(0); resetValues(); rightMultAnswers++; editor.putInt(getString(R.string.right_mult_answers), rightMultAnswers); } else { dialog(1); wrongMultAnswers++; editor.putInt(getString(R.string.wrong_mult_answers), wrongMultAnswers); } break; case DIVACTION: if (answer == Double.parseDouble(df.format((double) number1 / number2).replace(',','.'))) { dialog(0); resetValues(); rightDivAnswers++; editor.putInt(getString(R.string.right_div_answers), rightDivAnswers); } else { dialog(1); wrongDivAnswers++; editor.putInt(getString(R.string.wrong_div_answers), wrongDivAnswers); } break; } editor.commit(); }else { dialog(-1); } } public void checkButtonPressed(View v){ v.startAnimation(shakeAnimation); checkProcess(); } }
Billeclipse/C.A.InstructionQuiz-Project
CAInstructionQuiz/app/src/main/java/com/example/billy/cainstructionquiz/QuizActivity.java
3,402
//Αρχικοποίηση του animation του κουμπιού
line_comment
el
package com.example.billy.cainstructionquiz; import android.app.Dialog; import android.content.Intent; import android.content.SharedPreferences; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import java.math.RoundingMode; import java.security.SecureRandom; import java.text.DecimalFormat; public class QuizActivity extends AppCompatActivity { private static final String TAG = "button"; private static final String ADDBTN = "addButton"; private static final String SUBBTN = "subButton"; private static final String MULTBTN = "multButton"; private static final String DIVBTN = "divButton"; private static final String QUESTION = "Πόσο κάνει "; private static final String ADDACTION = " σύν "; private static final String SUBACTION = " μείον "; private static final String MULTACTION = " επί "; private static final String DIVACTION = " διά "; private static final String QUESTIONMARK = ";"; private static final String WINMESSAGE = "Μπράβο!"; private static final String LOSEMESSAGE = "Προσπάθησε ξανά, αυτή την φόρα θα τα καταφέρεις!"; private static final String ERRORMESSAGE = "Προσπάθησε ξανά, έδωσες λάθος αριθμό!"; private static final String EASY = "Εύκολο"; private static final String MEDIUM = "Μέτριο"; private static final String HARD = "Δύσκολο"; private SecureRandom random = new SecureRandom(); private int number1; private int number2; private int rightAnswers; private int rightAddAnswers; private int rightSubAnswers; private int rightMultAnswers; private int rightDivAnswers; private int wrongAnswers; private int wrongAddAnswers; private int wrongSubAnswers; private int wrongMultAnswers; private int wrongDivAnswers; private String action=""; private TextView questionTxtView; private EditText answerEditText; private Animation shakeAnimation; private SharedPreferences sharedPref; private SharedPreferences.Editor editor; private String difficulty; private String background_color; @Override protected void onResume() { super.onResume(); String background_color = sharedPref.getString(MainActivity.COLOR, MainActivity.RED); RelativeLayout rl = (RelativeLayout) findViewById(R.id.activity_quiz); switch(background_color){ case MainActivity.GREEN: rl.setBackgroundResource(R.drawable.blackboard_background_green); break; case MainActivity.RED: rl.setBackgroundResource(R.drawable.blackboard_background_red); break; case MainActivity.BLUE: rl.setBackgroundResource(R.drawable.blackboard_background_blue); break; case MainActivity.PINK: rl.setBackgroundResource(R.drawable.blackboard_background_pink); break; case MainActivity.PURPLE: rl.setBackgroundResource(R.drawable.blackboard_background_purple); break; } } @Override protected void onCreate(Bundle savedInstanceState) { sharedPref = PreferenceManager.getDefaultSharedPreferences(this); background_color = sharedPref.getString(MainActivity.COLOR, MainActivity.GREEN); switch(background_color){ case MainActivity.GREEN: setTheme(R.style.AppTheme_Green); break; case MainActivity.RED: setTheme(R.style.AppTheme_Red); break; case MainActivity.BLUE: setTheme(R.style.AppTheme_Blue); break; case MainActivity.PINK: setTheme(R.style.AppTheme_Pink); break; case MainActivity.PURPLE: setTheme(R.style.AppTheme_Purple); break; } super.onCreate(savedInstanceState); setContentView(R.layout.activity_quiz); //Αρχικοποίηση του<SUF> shakeAnimation = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.shake_effect); questionTxtView = (TextView) findViewById(R.id.questionTxtView); answerEditText = (EditText) findViewById(R.id.answerEditText); //KeyListener για να τρέχει την συνάρτηση υπολογισμού και με το πλήκτρο enter. answerEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) { checkProcess(); return true; } return false; } }); //Αρχικοποίηση του Default SharedPreference Manager και Editor sharedPref = PreferenceManager.getDefaultSharedPreferences(this); editor = sharedPref.edit(); //Εισαγωγή των μεταβλητών από τα SharedPreferrence για τα στατιστικά του παιχνιδιού int defaultValue = getResources().getInteger(R.integer.answers_default); rightAnswers = sharedPref.getInt(getString(R.string.right_answers), defaultValue); rightAddAnswers = sharedPref.getInt(getString(R.string.right_add_answers), defaultValue); rightSubAnswers = sharedPref.getInt(getString(R.string.right_sub_answers), defaultValue); rightMultAnswers = sharedPref.getInt(getString(R.string.right_mult_answers), defaultValue); rightDivAnswers = sharedPref.getInt(getString(R.string.right_div_answers), defaultValue); wrongAnswers = sharedPref.getInt(getString(R.string.wrong_answers), defaultValue); wrongAddAnswers = sharedPref.getInt(getString(R.string.wrong_add_answers), defaultValue); wrongSubAnswers = sharedPref.getInt(getString(R.string.wrong_sub_answers), defaultValue); wrongMultAnswers = sharedPref.getInt(getString(R.string.wrong_mult_answers), defaultValue); wrongDivAnswers = sharedPref.getInt(getString(R.string.wrong_div_answers), defaultValue); //Εισαγωγή της μεταβλητής από τα SharedPreferrence για την δυσκολία του παιχνιδιού //Σε περίπτωση προβλήματος με την μεταβλητή του SharedPreferrence για την δυσκολία να βάζει αυτόματα εύκολο difficulty = sharedPref.getString(MainActivity.DIFFICULTY, EASY); //Αρχικοποίηση των αριθμών για την πράξη βάση της δυσκολίας setRandoms(); //Εύρεση πράξης από τα στοιχεία που προήρθαν από το προηγούμενο Activity String buttonString=""; Intent i = getIntent(); Bundle b = i.getExtras(); if(b!=null) { buttonString = (String) b.get(TAG); } switch(buttonString){ case ADDBTN: action=ADDACTION; break; case SUBBTN: action=SUBACTION; break; case MULTBTN: action=MULTACTION; break; case DIVBTN: action=DIVACTION; break; } questionTxtView.setText(QUESTION+String.valueOf(number1)+action+String.valueOf(number2)+QUESTIONMARK); } private void setRandoms(){ switch(difficulty){ case EASY: number1 = random.nextInt(10 - 1) + 1; number2 = random.nextInt(10 - 1) + 1; break; case MEDIUM: number1 = random.nextInt(100 - 1) + 1; number2 = random.nextInt(100 - 1) + 1; break; case HARD: number1 = random.nextInt(1000 - 1) + 1; number2 = random.nextInt(1000 - 1) + 1; break; } } // Η συνάρτηση dialog παίρνει μια μεταβλητή integer οπού όταν είναι 0 σημαίνει ότι είναι νικητήριο dialog και όταν είναι 1 είναι ηττημένο dialog // ενώ όταν είναι -1 (ή οποιοσδήποτε άλλος ακέραιος) σημαίνει οτι υπήρξε κάποιο πρόβλημα με τον αριθμό. private void dialog(int win_or_lose){ final Dialog dialog = new Dialog(QuizActivity.this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.custom_dialog); TextView text = (TextView) dialog.findViewById(R.id.textView); ImageView image = (ImageView) dialog.findViewById(R.id.image); if(win_or_lose==0){ text.setText(WINMESSAGE); rightAnswers++; editor.putInt(getString(R.string.right_answers), rightAnswers); image.setImageResource(R.drawable.star); final MediaPlayer mediaPlayer = MediaPlayer.create(QuizActivity.this, R.raw.tada); mediaPlayer.start(); mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.reset(); mp.release(); } }); }else if (win_or_lose==1){ image.setImageResource(R.drawable.sad_face); text.setText(LOSEMESSAGE); wrongAnswers++; editor.putInt(getString(R.string.wrong_answers), wrongAnswers); }else{ image.setImageResource(R.drawable.error_icon); text.setText(ERRORMESSAGE); } editor.commit(); dialog.show(); Handler handler = new Handler(); handler.postDelayed( new Runnable() { @Override public void run() { dialog.dismiss(); } }, 5000); } private void resetValues(){ setRandoms(); answerEditText.setText(""); questionTxtView.setText(QUESTION+String.valueOf(number1)+action+String.valueOf(number2)+QUESTIONMARK); } private void checkProcess(){ DecimalFormat df = new DecimalFormat("#.#"); df.setRoundingMode(RoundingMode.HALF_UP); int counter = 0; for( int i=0; i<answerEditText.getText().toString().length(); i++ ) { if( answerEditText.getText().toString().charAt(i) == '.' || answerEditText.getText().toString().charAt(i) == ',') { counter++; } } if(counter==0 || counter==1) { String answer_string = df.format(Double.parseDouble(answerEditText.getText().toString())).replace(',','.'); double answer = Double.parseDouble(answer_string); switch (action) { case ADDACTION: if (answer == (number1 + number2)) { dialog(0); resetValues(); rightAddAnswers++; editor.putInt(getString(R.string.right_add_answers), rightAddAnswers); } else { dialog(1); wrongAddAnswers++; editor.putInt(getString(R.string.wrong_add_answers), wrongAddAnswers); } break; case SUBACTION: if (answer == (number1 - number2)) { dialog(0); resetValues(); rightSubAnswers++; editor.putInt(getString(R.string.right_sub_answers), rightSubAnswers); } else { dialog(1); wrongSubAnswers++; editor.putInt(getString(R.string.wrong_sub_answers), wrongSubAnswers); } break; case MULTACTION: if (answer == (number1 * number2)) { dialog(0); resetValues(); rightMultAnswers++; editor.putInt(getString(R.string.right_mult_answers), rightMultAnswers); } else { dialog(1); wrongMultAnswers++; editor.putInt(getString(R.string.wrong_mult_answers), wrongMultAnswers); } break; case DIVACTION: if (answer == Double.parseDouble(df.format((double) number1 / number2).replace(',','.'))) { dialog(0); resetValues(); rightDivAnswers++; editor.putInt(getString(R.string.right_div_answers), rightDivAnswers); } else { dialog(1); wrongDivAnswers++; editor.putInt(getString(R.string.wrong_div_answers), wrongDivAnswers); } break; } editor.commit(); }else { dialog(-1); } } public void checkButtonPressed(View v){ v.startAnimation(shakeAnimation); checkProcess(); } }
286_13
import javax.swing.*; import java.awt.*; import java.io.*; import java.util.*; public class MainFrame extends JFrame { public static int songID = 1; private JLabel titleLabel, durationLabel, dateLabel, artistLabel, genreLabel, browsingLabel; private JTextField title, date , duration, artist; private JComboBox genre; private JButton aboutBtn, insertBtn, saveBtn, exitBtn, statisticsBtn; public JTextArea area; private String fileName= "songlist.txt"; private ArrayList<Song> songList = new ArrayList(); private JMenuBar menuBar; private JMenu fileMenu; private JMenu helpMenu; private JMenuItem saveItem; private JMenuItem insertItem; private JMenuItem statisticsItem; private JMenuItem exitItem; private JMenuItem aboutItem; public MainFrame(){ // Η διαδικασία που ακολουθούμε για να προετοιμάσουμε το window είναι η ίδια που είδαμε με του main frame. this.setSize(780,420); this.setTitle("Insert new song"); this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); this.setLocationRelativeTo(null); this.setLayout(null); this.setResizable(false); // Αφαιρούμε από τον χρήστη την δυνατότητα να κάνει resize το window System.setProperty("bgrd","0XD0E2F4"); this.getContentPane().setBackground(Color.getColor("bgrd")); Image icon = Toolkit.getDefaultToolkit().getImage("icon.png"); this.setIconImage(icon); //Καλούμε όλες τις απαραίτητες συναρτήσεις για να μας δημιουργηθεί το window prepareMenu(); prepareTexts(); prepareButtons(); this.setVisible(true); } public void prepareMenu(){ //Μέθοδος για να αρχικοποιήσουμε τo Menu menuBar = new JMenuBar(); fileMenu = new JMenu("File"); helpMenu = new JMenu("Help"); this.menuBar = new JMenuBar(); this.fileMenu = new JMenu("File"); this.saveItem = new JMenuItem("Save to file"); this.exitItem = new JMenuItem("Exit"); this.insertItem = new JMenuItem("Insert songs"); this.statisticsItem = new JMenuItem("Statistics tab"); this.aboutItem = new JMenuItem("About"); this.saveItem.addActionListener(e -> save()); this.exitItem.addActionListener(e -> exitApp()); this.insertItem.addActionListener(e -> getText()); this.statisticsItem.addActionListener(e -> statistic()); this.aboutItem.addActionListener(e -> about()); fileMenu.add(insertItem); fileMenu.add(saveItem); fileMenu.add(statisticsItem); fileMenu.addSeparator(); fileMenu.add(exitItem); helpMenu.add(aboutItem); menuBar.add(fileMenu); menuBar.add(helpMenu); this.setJMenuBar(menuBar); } public void prepareButtons(){ //Μέθοδος για να αρχικοποιήσουμε τα buttons System.setProperty("color","0XE1EDF8"); insertBtn = new JButton("Insert"); this.insertBtn.setBackground(Color.getColor("color")); this.insertBtn.setBounds(100, 320, 100, 30); this.add(this.insertBtn); add(insertBtn); insertBtn.addActionListener(e -> getText()); saveBtn = new JButton("Save"); this.saveBtn.setBackground(Color.getColor("color")); this.saveBtn.setBounds(205, 320, 80, 30); this.add(this.saveBtn); add(saveBtn); saveBtn.addActionListener(e -> save()); statisticsBtn = new JButton("Statistics"); this.statisticsBtn.setBackground(Color.getColor("color")); this.statisticsBtn.setBounds(290, 320, 110, 30); this.add(this.statisticsBtn); add(statisticsBtn); statisticsBtn.addActionListener(e -> statistic()); aboutBtn = new JButton("About"); this.aboutBtn.setBackground(Color.getColor("color")); this.aboutBtn.setBounds(15, 320, 80, 30); this.add(this.aboutBtn); add(aboutBtn); aboutBtn.addActionListener(e -> about()); exitBtn = new JButton("Exit"); this.exitBtn.setBackground(Color.getColor("color")); this.exitBtn.setBounds(405, 320, 80, 30); this.add(this.exitBtn); add(exitBtn); exitBtn.addActionListener(e -> exitApp()); } public void prepareTexts(){//Μέθοδος για να αρχικοποιήσουμε τα texts titleLabel = new JLabel("Title: "); titleLabel.setForeground(Color.BLACK); titleLabel.setBounds(10,10,50,30); titleLabel.setFont(new Font("Arial",Font.PLAIN,15)); add(titleLabel); durationLabel = new JLabel("Duration:"); durationLabel.setForeground(Color.BLACK); durationLabel.setBounds(10,42,800,30); durationLabel.setFont(new Font("Arial",Font.PLAIN,15)); add(durationLabel); dateLabel = new JLabel("Date:"); dateLabel.setForeground(Color.BLACK); dateLabel.setBounds(10,75,40,30); dateLabel.setFont(new Font("Arial",Font.PLAIN,15)); add(dateLabel); artistLabel = new JLabel("Artist:"); artistLabel.setForeground(Color.BLACK); artistLabel.setBounds(10,110,80,30); artistLabel.setFont(new Font("Arial",Font.PLAIN,15)); add(artistLabel); genreLabel = new JLabel("Genre:"); genreLabel.setForeground(Color.BLACK); genreLabel.setBounds(10,140,80,30); genreLabel.setFont(new Font("Arial",Font.PLAIN,15)); add(genreLabel); browsingLabel = new JLabel("(Please fill all the areas)"); browsingLabel.setForeground(Color.BLACK); browsingLabel.setFont(new Font("Arial",Font.BOLD,14)); browsingLabel.setBounds(15,280,300,30); add(browsingLabel); //Text fields title = new JTextField(); title.setBounds(90,18,150,20); add(title); duration = new JTextField(); duration.setBounds(90,48,150,20); add(duration); date = new JTextField(); date.setBounds(90,80,150,20); add(date); artist = new JTextField(); artist.setBounds(90,115,150,20); add(artist); //Combo box String option[] = new String[]{"Rock", "Pop", "Metal","Speedcore","Breakcore","Dark Synthwave", "Hardstyle", "Hardcore", "Hyperpop", "Digicore", "Chiptune", "Glitchcore", "Vocaloids"}; this.genre = new JComboBox(option); this.genre.setBounds(90, 145, 150, 20); this.add(this.genre); area = new JTextArea(); area.setBounds(300,18, 400,270); area.setEditable(false); area.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder())); System.setProperty("areaColor","0XD9E8F6"); area.setBackground(Color.getColor("areaColor")); add(area); } //********************** private methods which implement the required functionality ********************** private void insertSong(String songID, String date, String title, String duration, String artist, String genre){ area.setText(""); Song song = new Song(songID, date, title, duration, artist, genre); songList.add(song); area.append(""); //Για να εμφανιστούν αυτα που βάλαμε στο text area area.append("Song ID: \t"+ songID + "\n\nTitle: \t"+ title + "\n\nDuration: \t"+ date+ "\n\nRelease Date: \t"+ duration+ "\n\nArtist: \t"+ artist + "\n\nGenre: \t"+ genre); area.append("\n"); } private void save(){ saveBtn.setEnabled(true); try { FileWriter fw = new FileWriter(fileName, true); BufferedWriter writer = new BufferedWriter(fw); //Εγγραφη τραγουδιού σε txt αρχείο το ένα κάτω απο το άλλο for(Song song:songList){ writer.write(song.toString()); writer.newLine(); } writer.close(); //Εμφανίζει ένα pop up message πως αποθηκεύτηκε επιτυχώς το τραγούδι JOptionPane.showMessageDialog( MainFrame.this, "Your song list is saved in " + fileName, "Save Completed", JOptionPane.INFORMATION_MESSAGE); //Μόλις γίνει η αποθήκευση του τραγουδιου ενεργοποιούνται ξανα τα buttons saveBtn.setEnabled(true); insertBtn.setEnabled(true); clearInput(); } catch (IOException e) { JOptionPane.showMessageDialog(saveBtn, "Can't access " + fileName, "File access error", JOptionPane.ERROR_MESSAGE); } } private void statistic(){ new Statistics(); //καλεί την κλάση statistics } private void about(){ new AboutFrame(); //καλεί την κλάση about } public void clearInput() { //Μέθοδος για να γίνεται clear το text area this.title.setText(""); this.duration.setText(""); this.date.setText(""); this.artist.setText(""); this.genre.setSelectedIndex(0); this.insertBtn.setEnabled(true); this.saveBtn.setEnabled(true); } public void getText() { // Αποθηκεύουμε σε string variables τα δεδομένα απο τα textfields. String name = title.getText(); String dur = duration.getText(); String dates = date.getText(); String art = artist.getText(); String gen = (String)this.genre.getItemAt(this.genre.getSelectedIndex()); if (!name.isEmpty() && !dur.isEmpty() && !dates.isEmpty() && !art.isEmpty() && !gen.isEmpty()) { this.insertSong(String.valueOf(songID), name, dur, dates, art, gen); songID++; } else { JOptionPane.showMessageDialog(this, "You need to fill all the blank spaces!", "Insert song error!", 2); } } //Μέθοδος για το κλείσιμο της εφαμοργής. Αν επιλεγεί το "yes" τότε η εφαρμογή τερματίζεται private void exitApp() { int i = JOptionPane.showConfirmDialog(MainFrame.this, "Do you want to exit the app?"); if (i == JOptionPane.YES_OPTION) { System.exit(0); } } }
C4Terina/University
Songs/src/MainFrame.java
2,979
//Μέθοδος για να γίνεται clear το text area
line_comment
el
import javax.swing.*; import java.awt.*; import java.io.*; import java.util.*; public class MainFrame extends JFrame { public static int songID = 1; private JLabel titleLabel, durationLabel, dateLabel, artistLabel, genreLabel, browsingLabel; private JTextField title, date , duration, artist; private JComboBox genre; private JButton aboutBtn, insertBtn, saveBtn, exitBtn, statisticsBtn; public JTextArea area; private String fileName= "songlist.txt"; private ArrayList<Song> songList = new ArrayList(); private JMenuBar menuBar; private JMenu fileMenu; private JMenu helpMenu; private JMenuItem saveItem; private JMenuItem insertItem; private JMenuItem statisticsItem; private JMenuItem exitItem; private JMenuItem aboutItem; public MainFrame(){ // Η διαδικασία που ακολουθούμε για να προετοιμάσουμε το window είναι η ίδια που είδαμε με του main frame. this.setSize(780,420); this.setTitle("Insert new song"); this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); this.setLocationRelativeTo(null); this.setLayout(null); this.setResizable(false); // Αφαιρούμε από τον χρήστη την δυνατότητα να κάνει resize το window System.setProperty("bgrd","0XD0E2F4"); this.getContentPane().setBackground(Color.getColor("bgrd")); Image icon = Toolkit.getDefaultToolkit().getImage("icon.png"); this.setIconImage(icon); //Καλούμε όλες τις απαραίτητες συναρτήσεις για να μας δημιουργηθεί το window prepareMenu(); prepareTexts(); prepareButtons(); this.setVisible(true); } public void prepareMenu(){ //Μέθοδος για να αρχικοποιήσουμε τo Menu menuBar = new JMenuBar(); fileMenu = new JMenu("File"); helpMenu = new JMenu("Help"); this.menuBar = new JMenuBar(); this.fileMenu = new JMenu("File"); this.saveItem = new JMenuItem("Save to file"); this.exitItem = new JMenuItem("Exit"); this.insertItem = new JMenuItem("Insert songs"); this.statisticsItem = new JMenuItem("Statistics tab"); this.aboutItem = new JMenuItem("About"); this.saveItem.addActionListener(e -> save()); this.exitItem.addActionListener(e -> exitApp()); this.insertItem.addActionListener(e -> getText()); this.statisticsItem.addActionListener(e -> statistic()); this.aboutItem.addActionListener(e -> about()); fileMenu.add(insertItem); fileMenu.add(saveItem); fileMenu.add(statisticsItem); fileMenu.addSeparator(); fileMenu.add(exitItem); helpMenu.add(aboutItem); menuBar.add(fileMenu); menuBar.add(helpMenu); this.setJMenuBar(menuBar); } public void prepareButtons(){ //Μέθοδος για να αρχικοποιήσουμε τα buttons System.setProperty("color","0XE1EDF8"); insertBtn = new JButton("Insert"); this.insertBtn.setBackground(Color.getColor("color")); this.insertBtn.setBounds(100, 320, 100, 30); this.add(this.insertBtn); add(insertBtn); insertBtn.addActionListener(e -> getText()); saveBtn = new JButton("Save"); this.saveBtn.setBackground(Color.getColor("color")); this.saveBtn.setBounds(205, 320, 80, 30); this.add(this.saveBtn); add(saveBtn); saveBtn.addActionListener(e -> save()); statisticsBtn = new JButton("Statistics"); this.statisticsBtn.setBackground(Color.getColor("color")); this.statisticsBtn.setBounds(290, 320, 110, 30); this.add(this.statisticsBtn); add(statisticsBtn); statisticsBtn.addActionListener(e -> statistic()); aboutBtn = new JButton("About"); this.aboutBtn.setBackground(Color.getColor("color")); this.aboutBtn.setBounds(15, 320, 80, 30); this.add(this.aboutBtn); add(aboutBtn); aboutBtn.addActionListener(e -> about()); exitBtn = new JButton("Exit"); this.exitBtn.setBackground(Color.getColor("color")); this.exitBtn.setBounds(405, 320, 80, 30); this.add(this.exitBtn); add(exitBtn); exitBtn.addActionListener(e -> exitApp()); } public void prepareTexts(){//Μέθοδος για να αρχικοποιήσουμε τα texts titleLabel = new JLabel("Title: "); titleLabel.setForeground(Color.BLACK); titleLabel.setBounds(10,10,50,30); titleLabel.setFont(new Font("Arial",Font.PLAIN,15)); add(titleLabel); durationLabel = new JLabel("Duration:"); durationLabel.setForeground(Color.BLACK); durationLabel.setBounds(10,42,800,30); durationLabel.setFont(new Font("Arial",Font.PLAIN,15)); add(durationLabel); dateLabel = new JLabel("Date:"); dateLabel.setForeground(Color.BLACK); dateLabel.setBounds(10,75,40,30); dateLabel.setFont(new Font("Arial",Font.PLAIN,15)); add(dateLabel); artistLabel = new JLabel("Artist:"); artistLabel.setForeground(Color.BLACK); artistLabel.setBounds(10,110,80,30); artistLabel.setFont(new Font("Arial",Font.PLAIN,15)); add(artistLabel); genreLabel = new JLabel("Genre:"); genreLabel.setForeground(Color.BLACK); genreLabel.setBounds(10,140,80,30); genreLabel.setFont(new Font("Arial",Font.PLAIN,15)); add(genreLabel); browsingLabel = new JLabel("(Please fill all the areas)"); browsingLabel.setForeground(Color.BLACK); browsingLabel.setFont(new Font("Arial",Font.BOLD,14)); browsingLabel.setBounds(15,280,300,30); add(browsingLabel); //Text fields title = new JTextField(); title.setBounds(90,18,150,20); add(title); duration = new JTextField(); duration.setBounds(90,48,150,20); add(duration); date = new JTextField(); date.setBounds(90,80,150,20); add(date); artist = new JTextField(); artist.setBounds(90,115,150,20); add(artist); //Combo box String option[] = new String[]{"Rock", "Pop", "Metal","Speedcore","Breakcore","Dark Synthwave", "Hardstyle", "Hardcore", "Hyperpop", "Digicore", "Chiptune", "Glitchcore", "Vocaloids"}; this.genre = new JComboBox(option); this.genre.setBounds(90, 145, 150, 20); this.add(this.genre); area = new JTextArea(); area.setBounds(300,18, 400,270); area.setEditable(false); area.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder())); System.setProperty("areaColor","0XD9E8F6"); area.setBackground(Color.getColor("areaColor")); add(area); } //********************** private methods which implement the required functionality ********************** private void insertSong(String songID, String date, String title, String duration, String artist, String genre){ area.setText(""); Song song = new Song(songID, date, title, duration, artist, genre); songList.add(song); area.append(""); //Για να εμφανιστούν αυτα που βάλαμε στο text area area.append("Song ID: \t"+ songID + "\n\nTitle: \t"+ title + "\n\nDuration: \t"+ date+ "\n\nRelease Date: \t"+ duration+ "\n\nArtist: \t"+ artist + "\n\nGenre: \t"+ genre); area.append("\n"); } private void save(){ saveBtn.setEnabled(true); try { FileWriter fw = new FileWriter(fileName, true); BufferedWriter writer = new BufferedWriter(fw); //Εγγραφη τραγουδιού σε txt αρχείο το ένα κάτω απο το άλλο for(Song song:songList){ writer.write(song.toString()); writer.newLine(); } writer.close(); //Εμφανίζει ένα pop up message πως αποθηκεύτηκε επιτυχώς το τραγούδι JOptionPane.showMessageDialog( MainFrame.this, "Your song list is saved in " + fileName, "Save Completed", JOptionPane.INFORMATION_MESSAGE); //Μόλις γίνει η αποθήκευση του τραγουδιου ενεργοποιούνται ξανα τα buttons saveBtn.setEnabled(true); insertBtn.setEnabled(true); clearInput(); } catch (IOException e) { JOptionPane.showMessageDialog(saveBtn, "Can't access " + fileName, "File access error", JOptionPane.ERROR_MESSAGE); } } private void statistic(){ new Statistics(); //καλεί την κλάση statistics } private void about(){ new AboutFrame(); //καλεί την κλάση about } public void clearInput() { //Μέθοδος για<SUF> this.title.setText(""); this.duration.setText(""); this.date.setText(""); this.artist.setText(""); this.genre.setSelectedIndex(0); this.insertBtn.setEnabled(true); this.saveBtn.setEnabled(true); } public void getText() { // Αποθηκεύουμε σε string variables τα δεδομένα απο τα textfields. String name = title.getText(); String dur = duration.getText(); String dates = date.getText(); String art = artist.getText(); String gen = (String)this.genre.getItemAt(this.genre.getSelectedIndex()); if (!name.isEmpty() && !dur.isEmpty() && !dates.isEmpty() && !art.isEmpty() && !gen.isEmpty()) { this.insertSong(String.valueOf(songID), name, dur, dates, art, gen); songID++; } else { JOptionPane.showMessageDialog(this, "You need to fill all the blank spaces!", "Insert song error!", 2); } } //Μέθοδος για το κλείσιμο της εφαμοργής. Αν επιλεγεί το "yes" τότε η εφαρμογή τερματίζεται private void exitApp() { int i = JOptionPane.showConfirmDialog(MainFrame.this, "Do you want to exit the app?"); if (i == JOptionPane.YES_OPTION) { System.exit(0); } } }
5147_8
/* * This file is part of CoAnSys project. * Copyright (c) 2012-2015 ICM-UW * * CoAnSys is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * CoAnSys is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CoAnSys. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.coansys.similarity.pig.udf; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataType; import org.apache.pig.data.DefaultDataBag; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.schema.Schema; import pl.edu.icm.coansys.commons.java.DiacriticsRemover; import pl.edu.icm.coansys.commons.java.PorterStemmer; import pl.edu.icm.coansys.commons.java.StackTraceExtractor; public class ExtendedStemmedPairs extends EvalFunc<DataBag> { @Override public Schema outputSchema(Schema input) { try { Schema termSchema = new Schema(new Schema.FieldSchema("term", new Schema(new Schema.FieldSchema("value", DataType.CHARARRAY)), DataType.TUPLE)); return new Schema(new Schema.FieldSchema(getSchemaName(this .getClass().getName().toLowerCase(), input), termSchema, DataType.BAG)); } catch (Exception e) { log.error("Error in the output Schema creation", e); log.error(StackTraceExtractor.getStackTrace(e)); return null; } } private String TYPE_OF_REMOVAL = "latin"; private static final String SPACE = " "; private AllLangStopWordFilter stowordsFilter = null; public ExtendedStemmedPairs() throws IOException { stowordsFilter = new AllLangStopWordFilter(); } public ExtendedStemmedPairs(String params) throws IOException { TYPE_OF_REMOVAL = params; stowordsFilter = new AllLangStopWordFilter(); } public List<String> getStemmedPairs(final String text) throws IOException { String tmp = text.toLowerCase(); tmp = tmp.replaceAll("[_]+", "_"); tmp = tmp.replaceAll("[-]+", "-"); if(!"latin".equals(TYPE_OF_REMOVAL)){ tmp = tmp.replaceAll("([^\\u0080-\\uFFFF a-zA-Z_\\-\\d\\s'])+", SPACE); } tmp = tmp.replaceAll("\\s+", SPACE); tmp = tmp.trim(); List<String> strings = new ArrayList<String>(); if (tmp.length() == 0) { return strings; } PorterStemmer ps = new PorterStemmer(); for (String s : StringUtils.split(tmp, SPACE)) { s = s.replaceAll("^[/\\-]+", ""); s = s.replaceAll("[\\-/]+$", ""); if("latin".equals(TYPE_OF_REMOVAL)){ s = s.replaceAll("[^a-z\\d\\-_/ ]+", SPACE); } if (s.length() <= 3) { continue; } if (!stowordsFilter.isInAllStopwords(s)) { s = DiacriticsRemover.removeDiacritics(s); ps.add(s.toCharArray(), s.length()); ps.stem(); strings.add(ps.toString()); } } return strings; } @Override public DataBag exec(Tuple input) throws IOException { if (input == null || input.size() == 0 || input.get(0) == null) { return null; } try { List<Tuple> tuples = new ArrayList<Tuple>(); String terms = (String) input.get(0); for (String s : getStemmedPairs(terms)) { tuples.add(TupleFactory.getInstance().newTuple(s)); } return new DefaultDataBag(tuples); } catch (Exception e) { throw new IOException("Caught exception processing input row ", e); } } public static void main(String[] args) { String text = "100688"; System.out.println("PartA: "+DiacriticsRemover.removeDiacritics(text)); // PorterStemmer ps = new PorterStemmer(); // for (String s : text.split(SPACE)) { // System.out.println("PartB1: "+s); // s = s.replaceAll("^[/\\-]+", ""); // System.out.println("PartB2: "+s); // s = s.replaceAll("[\\-/]+$", ""); // System.out.println("PartB3: "+s); // s = s.replaceAll("^[/\\-_0-9]+$", ""); // System.out.println("PartB4: "+s); // if (s.length() <= 3) { // continue; // } // s = DiacriticsRemover.removeDiacritics(s); // System.out.println("PartC: "+s); // ps.add(s.toCharArray(), s.length()); // ps.stem(); // System.out.println("PartD: "+ps.toString()); // } // String text = "Μεταφορά τεχνολογίας : " + "παράγων αναπτύξεως ή μέσον " // + "αποδιαρθρώσεως των οικονομικών " + "του τρίτου κόσμου " // + "ó Techn,ology Techn, ology"; // System.out.println("--------------"); // System.out.println(DiacriticsRemover.removeDiacritics(text)); // System.out.println("--------------"); // System.out.println(text.replaceAll( // "([^\\u0080-\\uFFFF a-zA-Z_\\-\\d\\s])+", "")); // System.out.println("--------------"); // text = text.replaceAll("([^\\u0080-\\uFFFF a-zA-Z_\\-\\d\\s])+", ""); // text = text.replaceAll("\\s+", " "); // // PorterStemmer ps = new PorterStemmer(); // for (String s : text.split(SPACE)) { // s = s.replaceAll("^[/\\-]+", ""); // s = s.replaceAll("[\\-/]+$", ""); // s = s.replaceAll("^[/\\-_0-9]+$", ""); // if (s.length() <= 2) { // continue; // } // s = DiacriticsRemover.removeDiacritics(s); // ps.add(s.toCharArray(), s.length()); // ps.stem(); // System.out.println(ps.toString()); // } } }
CeON/CoAnSys
document-similarity/document-similarity-logic/src/main/java/pl/edu/icm/coansys/similarity/pig/udf/ExtendedStemmedPairs.java
1,966
// String text = "Μεταφορά τεχνολογίας : " + "παράγων αναπτύξεως ή μέσον "
line_comment
el
/* * This file is part of CoAnSys project. * Copyright (c) 2012-2015 ICM-UW * * CoAnSys is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * CoAnSys is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CoAnSys. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.coansys.similarity.pig.udf; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataType; import org.apache.pig.data.DefaultDataBag; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.schema.Schema; import pl.edu.icm.coansys.commons.java.DiacriticsRemover; import pl.edu.icm.coansys.commons.java.PorterStemmer; import pl.edu.icm.coansys.commons.java.StackTraceExtractor; public class ExtendedStemmedPairs extends EvalFunc<DataBag> { @Override public Schema outputSchema(Schema input) { try { Schema termSchema = new Schema(new Schema.FieldSchema("term", new Schema(new Schema.FieldSchema("value", DataType.CHARARRAY)), DataType.TUPLE)); return new Schema(new Schema.FieldSchema(getSchemaName(this .getClass().getName().toLowerCase(), input), termSchema, DataType.BAG)); } catch (Exception e) { log.error("Error in the output Schema creation", e); log.error(StackTraceExtractor.getStackTrace(e)); return null; } } private String TYPE_OF_REMOVAL = "latin"; private static final String SPACE = " "; private AllLangStopWordFilter stowordsFilter = null; public ExtendedStemmedPairs() throws IOException { stowordsFilter = new AllLangStopWordFilter(); } public ExtendedStemmedPairs(String params) throws IOException { TYPE_OF_REMOVAL = params; stowordsFilter = new AllLangStopWordFilter(); } public List<String> getStemmedPairs(final String text) throws IOException { String tmp = text.toLowerCase(); tmp = tmp.replaceAll("[_]+", "_"); tmp = tmp.replaceAll("[-]+", "-"); if(!"latin".equals(TYPE_OF_REMOVAL)){ tmp = tmp.replaceAll("([^\\u0080-\\uFFFF a-zA-Z_\\-\\d\\s'])+", SPACE); } tmp = tmp.replaceAll("\\s+", SPACE); tmp = tmp.trim(); List<String> strings = new ArrayList<String>(); if (tmp.length() == 0) { return strings; } PorterStemmer ps = new PorterStemmer(); for (String s : StringUtils.split(tmp, SPACE)) { s = s.replaceAll("^[/\\-]+", ""); s = s.replaceAll("[\\-/]+$", ""); if("latin".equals(TYPE_OF_REMOVAL)){ s = s.replaceAll("[^a-z\\d\\-_/ ]+", SPACE); } if (s.length() <= 3) { continue; } if (!stowordsFilter.isInAllStopwords(s)) { s = DiacriticsRemover.removeDiacritics(s); ps.add(s.toCharArray(), s.length()); ps.stem(); strings.add(ps.toString()); } } return strings; } @Override public DataBag exec(Tuple input) throws IOException { if (input == null || input.size() == 0 || input.get(0) == null) { return null; } try { List<Tuple> tuples = new ArrayList<Tuple>(); String terms = (String) input.get(0); for (String s : getStemmedPairs(terms)) { tuples.add(TupleFactory.getInstance().newTuple(s)); } return new DefaultDataBag(tuples); } catch (Exception e) { throw new IOException("Caught exception processing input row ", e); } } public static void main(String[] args) { String text = "100688"; System.out.println("PartA: "+DiacriticsRemover.removeDiacritics(text)); // PorterStemmer ps = new PorterStemmer(); // for (String s : text.split(SPACE)) { // System.out.println("PartB1: "+s); // s = s.replaceAll("^[/\\-]+", ""); // System.out.println("PartB2: "+s); // s = s.replaceAll("[\\-/]+$", ""); // System.out.println("PartB3: "+s); // s = s.replaceAll("^[/\\-_0-9]+$", ""); // System.out.println("PartB4: "+s); // if (s.length() <= 3) { // continue; // } // s = DiacriticsRemover.removeDiacritics(s); // System.out.println("PartC: "+s); // ps.add(s.toCharArray(), s.length()); // ps.stem(); // System.out.println("PartD: "+ps.toString()); // } // String text<SUF> // + "αποδιαρθρώσεως των οικονομικών " + "του τρίτου κόσμου " // + "ó Techn,ology Techn, ology"; // System.out.println("--------------"); // System.out.println(DiacriticsRemover.removeDiacritics(text)); // System.out.println("--------------"); // System.out.println(text.replaceAll( // "([^\\u0080-\\uFFFF a-zA-Z_\\-\\d\\s])+", "")); // System.out.println("--------------"); // text = text.replaceAll("([^\\u0080-\\uFFFF a-zA-Z_\\-\\d\\s])+", ""); // text = text.replaceAll("\\s+", " "); // // PorterStemmer ps = new PorterStemmer(); // for (String s : text.split(SPACE)) { // s = s.replaceAll("^[/\\-]+", ""); // s = s.replaceAll("[\\-/]+$", ""); // s = s.replaceAll("^[/\\-_0-9]+$", ""); // if (s.length() <= 2) { // continue; // } // s = DiacriticsRemover.removeDiacritics(s); // ps.add(s.toCharArray(), s.length()); // ps.stem(); // System.out.println(ps.toString()); // } } }
14893_1
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template */ package apartease; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /** * * @author Θεοδόσης */ public class EventDataPage extends javax.swing.JFrame implements DBConnection{ /** * Creates new form EventDataPage */ public EventDataPage() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel2 = new javax.swing.JPanel(); jButton7 = new javax.swing.JButton(); jButton8 = new javax.swing.JButton(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jTextField3 = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel2.setBackground(new java.awt.Color(204, 204, 204)); jButton7.setText("Αποσύνδεση"); jButton7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton7ActionPerformed(evt); } }); jButton8.setText("Πίσω"); jButton8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton8ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap(298, Short.MAX_VALUE) .addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(14, 14, 14) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(16, Short.MAX_VALUE)) ); jLabel1.setText("Περιγραφή:"); jLabel2.setText("Ημερομηνία Έναρξης:"); jLabel3.setText("Ημερομηνία Λήξης:"); jButton1.setText("Δημιουργία"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel2) .addComponent(jLabel1) .addComponent(jLabel3)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(214, 214, 214)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(56, 56, 56) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(52, 52, 52) .addComponent(jButton1) .addGap(49, 49, 49)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed try { Statement stmt = connectdata(); stmt.execute("delete from LOGIN_STATUS where id = 1"); } catch(Exception e) { JOptionPane.showMessageDialog(this,e); } this.dispose(); Welcome_Page ob = new Welcome_Page(); ob.setVisible(true); }//GEN-LAST:event_jButton7ActionPerformed private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed this.dispose(); HomePage ob = new HomePage(); ob.setVisible(true); }//GEN-LAST:event_jButton8ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed String description = jTextField1.getText(); String start_date = jTextField2.getText(); String end_date = jTextField3.getText(); try{ Connection con=DBConnection.getConnection(); Statement st=con.createStatement(); Statement stmt = connectdata(); ResultSet rs=st.executeQuery("Select user_id from LOGIN_STATUS where id = 1"); rs.next(); int user_id = Integer.valueOf(rs.getString(1)); if ((description.length()>100) || (description.length()<5)){ JOptionPane.showMessageDialog(this,"Οι χαρακτήρες στο πεδίο Περιγραφή δεν είναι στα αποδεκτά όρια. Δοκιμάστε ξανά."); }else{ int result = JOptionPane.showConfirmDialog(this, "Θέλετε σίγουρα να δημιουργήσετε αυτό το συμβάν;"); rs=st.executeQuery("select building.id from user,user_has_apartment,apartment,building where '"+user_id+"'=user.id AND user.id=user_has_apartment.user_id AND user_has_apartment.apartment_id=apartment.id AND apartment.building_id=building.id "); rs.next(); int build_id=Integer.valueOf(rs.getString(1)); if (result == 0){ stmt.execute("insert into event(description,start_date,end_date,user_id,building_id) values ('"+description+"','"+start_date+"','"+end_date+"','"+user_id+"','"+build_id+"')"); JOptionPane.showMessageDialog(this,"Επιτυχής Δημιουργία Συμβάντος."); this.dispose(); EventsPage ob = new EventsPage(); ob.setVisible(true); } else if (result == 1){ JOptionPane.showMessageDialog(this,"Ακυρώθηκε"); } else{ JOptionPane.showMessageDialog(this,"Ακυρώθηκε"); } } }catch(Exception e) { JOptionPane.showMessageDialog(this,e); } }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(EventDataPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(EventDataPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(EventDataPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(EventDataPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new EventDataPage().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton7; private javax.swing.JButton jButton8; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel2; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; // End of variables declaration//GEN-END:variables }
ChrisLoukas007/ApartEase
ApartEase/src/apartease/EventDataPage.java
3,098
/** * * @author Θεοδόσης */
block_comment
el
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template */ package apartease; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /** * * @author Θεοδόσης <SUF>*/ public class EventDataPage extends javax.swing.JFrame implements DBConnection{ /** * Creates new form EventDataPage */ public EventDataPage() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel2 = new javax.swing.JPanel(); jButton7 = new javax.swing.JButton(); jButton8 = new javax.swing.JButton(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jTextField3 = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel2.setBackground(new java.awt.Color(204, 204, 204)); jButton7.setText("Αποσύνδεση"); jButton7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton7ActionPerformed(evt); } }); jButton8.setText("Πίσω"); jButton8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton8ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap(298, Short.MAX_VALUE) .addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(14, 14, 14) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(16, Short.MAX_VALUE)) ); jLabel1.setText("Περιγραφή:"); jLabel2.setText("Ημερομηνία Έναρξης:"); jLabel3.setText("Ημερομηνία Λήξης:"); jButton1.setText("Δημιουργία"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel2) .addComponent(jLabel1) .addComponent(jLabel3)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(214, 214, 214)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(56, 56, 56) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(52, 52, 52) .addComponent(jButton1) .addGap(49, 49, 49)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed try { Statement stmt = connectdata(); stmt.execute("delete from LOGIN_STATUS where id = 1"); } catch(Exception e) { JOptionPane.showMessageDialog(this,e); } this.dispose(); Welcome_Page ob = new Welcome_Page(); ob.setVisible(true); }//GEN-LAST:event_jButton7ActionPerformed private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed this.dispose(); HomePage ob = new HomePage(); ob.setVisible(true); }//GEN-LAST:event_jButton8ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed String description = jTextField1.getText(); String start_date = jTextField2.getText(); String end_date = jTextField3.getText(); try{ Connection con=DBConnection.getConnection(); Statement st=con.createStatement(); Statement stmt = connectdata(); ResultSet rs=st.executeQuery("Select user_id from LOGIN_STATUS where id = 1"); rs.next(); int user_id = Integer.valueOf(rs.getString(1)); if ((description.length()>100) || (description.length()<5)){ JOptionPane.showMessageDialog(this,"Οι χαρακτήρες στο πεδίο Περιγραφή δεν είναι στα αποδεκτά όρια. Δοκιμάστε ξανά."); }else{ int result = JOptionPane.showConfirmDialog(this, "Θέλετε σίγουρα να δημιουργήσετε αυτό το συμβάν;"); rs=st.executeQuery("select building.id from user,user_has_apartment,apartment,building where '"+user_id+"'=user.id AND user.id=user_has_apartment.user_id AND user_has_apartment.apartment_id=apartment.id AND apartment.building_id=building.id "); rs.next(); int build_id=Integer.valueOf(rs.getString(1)); if (result == 0){ stmt.execute("insert into event(description,start_date,end_date,user_id,building_id) values ('"+description+"','"+start_date+"','"+end_date+"','"+user_id+"','"+build_id+"')"); JOptionPane.showMessageDialog(this,"Επιτυχής Δημιουργία Συμβάντος."); this.dispose(); EventsPage ob = new EventsPage(); ob.setVisible(true); } else if (result == 1){ JOptionPane.showMessageDialog(this,"Ακυρώθηκε"); } else{ JOptionPane.showMessageDialog(this,"Ακυρώθηκε"); } } }catch(Exception e) { JOptionPane.showMessageDialog(this,e); } }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(EventDataPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(EventDataPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(EventDataPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(EventDataPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new EventDataPage().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton7; private javax.swing.JButton jButton8; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel2; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; // End of variables declaration//GEN-END:variables }
2751_2
import java.util.concurrent.Semaphore; public class Buffer{ private int[] contents; private final int unlimited; private int front, back; private int counter = 0; private Semaphore mutexPut = new Semaphore(1); private Semaphore mutexGet = new Semaphore(0); // Constructor public Buffer(int s) { this.unlimited = s; contents = new int[unlimited]; for (int i=0; i<unlimited; i++) contents[i] = 0; this.front = 0; this.back = -1; } // Put an item into buffer public void put(int data) { try { mutexPut.acquire();// δεν αφηνει αλλους παραγωγους να μπουν } catch (InterruptedException e) { } back = (back + 1); contents[back] = data; counter++; System.out.println("Prod " + Thread.currentThread().getName() + " No "+ data + " Loc " + back + " Count = " + counter); mutexGet.release(); //δινει σημα σε καταναλωτες οτι εχει αντικειμενο να παρουν mutexPut.release(); // τελιώνει ο παραγωγός μπορει τωρα να μπει ο επομενος } // Get an item from bufffer public int get() { int data = 0; try { mutexGet.acquire(); try { mutexPut.acquire(); // κλειδωμα buffer ωστε να μην μπου αλλοι καταναλωτες } catch (InterruptedException e) { } } catch (InterruptedException e) { } data = contents[front]; System.out.println(" Cons " + Thread.currentThread().getName() + " No "+ data + " Loc " + front + " Count = " + (counter-1)); front = (front + 1); counter--; return data; } }
ChristosPts/University-of-Macedonia
Parallel and Distributed Computing/Lab7/SemBufferUnlimited/Buffer.java
579
//δινει σημα σε καταναλωτες οτι εχει αντικειμενο να παρουν
line_comment
el
import java.util.concurrent.Semaphore; public class Buffer{ private int[] contents; private final int unlimited; private int front, back; private int counter = 0; private Semaphore mutexPut = new Semaphore(1); private Semaphore mutexGet = new Semaphore(0); // Constructor public Buffer(int s) { this.unlimited = s; contents = new int[unlimited]; for (int i=0; i<unlimited; i++) contents[i] = 0; this.front = 0; this.back = -1; } // Put an item into buffer public void put(int data) { try { mutexPut.acquire();// δεν αφηνει αλλους παραγωγους να μπουν } catch (InterruptedException e) { } back = (back + 1); contents[back] = data; counter++; System.out.println("Prod " + Thread.currentThread().getName() + " No "+ data + " Loc " + back + " Count = " + counter); mutexGet.release(); //δινει σημα<SUF> mutexPut.release(); // τελιώνει ο παραγωγός μπορει τωρα να μπει ο επομενος } // Get an item from bufffer public int get() { int data = 0; try { mutexGet.acquire(); try { mutexPut.acquire(); // κλειδωμα buffer ωστε να μην μπου αλλοι καταναλωτες } catch (InterruptedException e) { } } catch (InterruptedException e) { } data = contents[front]; System.out.println(" Cons " + Thread.currentThread().getName() + " No "+ data + " Loc " + front + " Count = " + (counter-1)); front = (front + 1); counter--; return data; } }
30015_1
package regenaration.team4.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import regenaration.team4.entities.Appointment; import regenaration.team4.entities.Citizen; import regenaration.team4.services.DoctorService; import java.security.Principal; import java.text.ParseException; import java.util.List; import java.util.Optional; @RestController public class DoctorController { @Autowired DoctorService doctorService; @GetMapping("/api/doctor/appointments") public List<Appointment> getAppointments(@RequestParam(value = "fromDate", defaultValue = "") String fromDate, @RequestParam(value = "toDate", defaultValue = "") String toDate, @RequestParam(value = "description", defaultValue = "") String description, Principal principal) throws ParseException { return doctorService.getAppointments(fromDate,toDate,description,principal); } //μονο του έβαλε το optional ζητάμε ενα appointment @GetMapping("/api/doctor/appointment/{id}") public Optional<Appointment> doctorGetAppointment(@PathVariable Long id) { return doctorService.doctorGetAppointment(id); } //δες τα στοιχεία του πολίτη που έχει το ραντεβού @GetMapping("/api/doctor/citizen/{id}") public Optional<Citizen> getCitizen(@PathVariable Long id) { return doctorService.getCitizen(id); } }
CodeHubGreece/Java4Web2019_SKG_Team4
project/src/main/java/regenaration/team4/controllers/DoctorController.java
424
//δες τα στοιχεία του πολίτη που έχει το ραντεβού
line_comment
el
package regenaration.team4.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import regenaration.team4.entities.Appointment; import regenaration.team4.entities.Citizen; import regenaration.team4.services.DoctorService; import java.security.Principal; import java.text.ParseException; import java.util.List; import java.util.Optional; @RestController public class DoctorController { @Autowired DoctorService doctorService; @GetMapping("/api/doctor/appointments") public List<Appointment> getAppointments(@RequestParam(value = "fromDate", defaultValue = "") String fromDate, @RequestParam(value = "toDate", defaultValue = "") String toDate, @RequestParam(value = "description", defaultValue = "") String description, Principal principal) throws ParseException { return doctorService.getAppointments(fromDate,toDate,description,principal); } //μονο του έβαλε το optional ζητάμε ενα appointment @GetMapping("/api/doctor/appointment/{id}") public Optional<Appointment> doctorGetAppointment(@PathVariable Long id) { return doctorService.doctorGetAppointment(id); } //δες τα<SUF> @GetMapping("/api/doctor/citizen/{id}") public Optional<Citizen> getCitizen(@PathVariable Long id) { return doctorService.getCitizen(id); } }
1481_7
package Games; /* * @author Despina-Eleana Chrysou */ import GetData.*; import javax.swing.*; public class Data extends javax.swing.JApplet { /** Initializes the applet Data */ @Override public void init() { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Data.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Data.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Data.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Data.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the applet */ try { java.awt.EventQueue.invokeAndWait(new Runnable() { public void run() { initComponents(); } }); } catch (Exception ex) { } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); setBackground(new java.awt.Color(255, 204, 204)); jLabel1.setFont(new java.awt.Font("Tahoma", 2, 14)); jLabel1.setForeground(new java.awt.Color(51, 0, 51)); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Αρχείο: data.txt"); jButton1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButton1.setText("Δημιούργησε τα δεδομένα"); jButton1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jLabel2.setFont(new java.awt.Font("Tahoma", 2, 14)); // NOI18N jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setText("Default Path: C:\\temp"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGap(82, 82, 82) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(95, Short.MAX_VALUE)) ); layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton1, jLabel1, jLabel2}); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(73, 73, 73) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(45, 45, 45) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(75, Short.MAX_VALUE)) ); layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jLabel1, jLabel2}); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed JOptionPane.showMessageDialog(this, "Περίμενε μέχρι να εμφανιστεί το μήνυμα ότι είναι έτοιμο το αρχείο..."); Jena.GetResults(); /*ReadFromFile GetData = new ReadFromFile(); int [] index1=GetData.index1(); int indexall1=0; for (int i=0;i<31;i++) { int k=i+1; int index2=index1[i]-1; indexall1=index2+indexall1; //System.out.println("Το ερώτημα "+k+" έχει "+index2+" εγγραφές"); System.out.println(index2); } int index=GetData.indexall(); System.out.println("Όλες οι εγγραφές είναι: "+indexall1); System.out.println("Αν στο "+indexall1+" προστεθούν και οι 31 γραμμές που περιέχουν τα ερωτήματα, τότε το συνολικό πλήθος γραμμών του πίνακα είναι: "+index); int arraydimension=index*4; System.out.println("Το συνολικό πλήθος δεδομένων είναι: "+index+" x 4 (4 στήλες)= "+arraydimension);*/ JOptionPane.showMessageDialog(this, "Eτοιμο το αρχείο 31queries.txt!"); }//GEN-LAST:event_jButton1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; // End of variables declaration//GEN-END:variables }
ComradeHadi/DBpedia-Game
ssg/src/Games/Data.java
1,871
/*ReadFromFile GetData = new ReadFromFile(); int [] index1=GetData.index1(); int indexall1=0; for (int i=0;i<31;i++) { int k=i+1; int index2=index1[i]-1; indexall1=index2+indexall1; //System.out.println("Το ερώτημα "+k+" έχει "+index2+" εγγραφές"); System.out.println(index2); } int index=GetData.indexall(); System.out.println("Όλες οι εγγραφές είναι: "+indexall1); System.out.println("Αν στο "+indexall1+" προστεθούν και οι 31 γραμμές που περιέχουν τα ερωτήματα, τότε το συνολικό πλήθος γραμμών του πίνακα είναι: "+index); int arraydimension=index*4; System.out.println("Το συνολικό πλήθος δεδομένων είναι: "+index+" x 4 (4 στήλες)= "+arraydimension);*/
block_comment
el
package Games; /* * @author Despina-Eleana Chrysou */ import GetData.*; import javax.swing.*; public class Data extends javax.swing.JApplet { /** Initializes the applet Data */ @Override public void init() { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Data.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Data.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Data.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Data.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the applet */ try { java.awt.EventQueue.invokeAndWait(new Runnable() { public void run() { initComponents(); } }); } catch (Exception ex) { } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); setBackground(new java.awt.Color(255, 204, 204)); jLabel1.setFont(new java.awt.Font("Tahoma", 2, 14)); jLabel1.setForeground(new java.awt.Color(51, 0, 51)); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Αρχείο: data.txt"); jButton1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButton1.setText("Δημιούργησε τα δεδομένα"); jButton1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jLabel2.setFont(new java.awt.Font("Tahoma", 2, 14)); // NOI18N jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setText("Default Path: C:\\temp"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGap(82, 82, 82) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(95, Short.MAX_VALUE)) ); layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton1, jLabel1, jLabel2}); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(73, 73, 73) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(45, 45, 45) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(75, Short.MAX_VALUE)) ); layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jLabel1, jLabel2}); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed JOptionPane.showMessageDialog(this, "Περίμενε μέχρι να εμφανιστεί το μήνυμα ότι είναι έτοιμο το αρχείο..."); Jena.GetResults(); /*ReadFromFile GetData =<SUF>*/ JOptionPane.showMessageDialog(this, "Eτοιμο το αρχείο 31queries.txt!"); }//GEN-LAST:event_jButton1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; // End of variables declaration//GEN-END:variables }
17255_0
package gr.smartcity.hackathon.hackathonproject; import android.Manifest; import android.app.ActionBar; import android.app.Notification; import android.app.NotificationManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.app.NotificationCompat; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * Αυτή η δραστηριότητα υλοποιεί την αρχική σελίδα επιλογών του επαγγελματία. */ public class ActivityForProfessionals extends AppCompatActivity { private RecyclerView.LayoutManager layoutManager; private LocationManager locationManager; private LocationListener locationListener; ECustomService professional; Vec2<Float, Float> coord; DatabaseConnection conn; String creds; private static int id = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_for_professionals); ErasurePreview oldPending = new ErasurePreview(); oldPending.execute(); if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 101); } initLocationService(); ImageView imgProf = (ImageView) findViewById(R.id.profImg); int id = R.drawable.background3; new ScaleImg(imgProf, id, this); TextView test = (TextView) findViewById(R.id.textView2); String text = getIntent().getExtras().getString("gr.smartcity.hackathon.hackathonproject.OK"); creds = getIntent().getStringExtra("EXTRA_USERNAME"); conn = (DatabaseConnection)getIntent().getSerializableExtra("DB_CONN"); ActionBar actionBar = getActionBar(); if(seekProfessionalDatabase()) test.setText(test.getText() + " " + professional.getSurname() + " " + professional.getName()); else test.setText(test.getText() + " " + creds); initNotificationService(); Button completedBtn = (Button) findViewById(R.id.jobsCompleted); Button pendingBtn = (Button) findViewById(R.id.jobsPending); completedBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent startIntent = new Intent(getApplicationContext(), History.class); startIntent.putExtra("DB_CONN", conn); startIntent.putExtra("SERV_DET", professional); startActivity(startIntent); } }); pendingBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent startIntent = new Intent(getApplicationContext(), pending.class); startIntent.putExtra("DB_CONN", conn); startIntent.putExtra("SERV_DET", professional); startActivity(startIntent); } }); } private void initLocationService() { try { locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { float lat = (float)location.getLatitude(); float lon = (float)location.getLongitude(); coord = new Vec2<Float, Float>(lat, lon); } @Override public void onProviderDisabled(String provider) { Toast.makeText(ActivityForProfessionals.this, "Please Enable GPS and Internet", Toast.LENGTH_SHORT).show(); } @Override public void onStatusChanged(String provider, int status, Bundle extras) {} @Override public void onProviderEnabled(String provider) {} }; locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); // getting GPS status boolean isGPSEnabled = locationManager .isProviderEnabled(LocationManager.GPS_PROVIDER); Log.v("isGPSEnabled", "=" + isGPSEnabled); // getting network status boolean isNetworkEnabled = locationManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch(SecurityException e) { e.printStackTrace(); } } private void initNotificationService() { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); NotificationPreview notificationSystem = new NotificationPreview(professional.getID(), notificationManager, getResources(), this); notificationSystem.execute(); } public boolean seekProfessionalDatabase() { boolean isSuccess = false; try { String query = "select * from workers where logindata= '" + creds +"'"; Log.e("QUERYING... ", query); Statement stmt = conn.con.createStatement(); ResultSet rs = null; rs = stmt.executeQuery(query); if (rs.next()) { String id = rs.getObject(1).toString(); String name = rs.getObject(2).toString(); String surname = rs.getObject(3).toString(); String tel = rs.getObject(4).toString(); String description = rs.getObject(6).toString(); String images = rs.getObject(7).toString(); int smallInt = Integer.parseInt(rs.getObject(5).toString()); boolean availability = (smallInt > 0) ? true : false; float rating = Float.parseFloat(rs.getObject(10).toString()); professional = new ECustomService(id, name, surname, tel, description, images, rating, availability); isSuccess = true; } } catch (SQLException e) { e.printStackTrace(); } return isSuccess; } @Override public boolean onCreateOptionsMenu(Menu menu2) { MenuInflater inflater = getMenuInflater(); getMenuInflater().inflate(R.menu.menu2, menu2); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.coordButton: { // first check for permissions if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET} ,10); } break; } Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if(location != null) { float longitude = (float) location.getLongitude(); float latitude = (float) location.getLatitude(); coord = new Vec2<Float, Float>(longitude, latitude); Log.e("LOCATION", coord.toString()); ServerConnection myconn = new ServerConnection(); myconn.initialize('P'); myconn.sendMyLocation(coord, professional.getID()); } else if(coord != null) { ServerConnection myconn = new ServerConnection(); myconn.initialize('P'); myconn.sendMyLocation(coord, professional.getID()); Log.e("LOCATION", coord.toString()); } else Log.e("LOCATION ERROR", location + ""); } } return false; } @Override public void onBackPressed() { new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Exit?") .setMessage("Are you sure you want to exit app?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }) .setNegativeButton("No", null) .show(); } public void notificationCall(String notifText){ Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), android.R.drawable.ic_dialog_alert); NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this) .setDefaults(NotificationCompat.DEFAULT_ALL) .setSmallIcon(android.R.drawable.ic_dialog_alert) .setLargeIcon(largeIcon) .setContentTitle(getResources().getString(R.string.app_name)) .setContentText(notifText); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Notification notif =notificationBuilder.build(); try{ notificationManager.notify(id++,notif); } catch(IllegalArgumentException e){ Log.e("ERROR DECLARATION",e.toString()); } } }
Crowdhackathon-SmartCity2/GMx2
002/eMustoras/HackathonProject/app/src/main/java/gr/smartcity/hackathon/hackathonproject/ActivityForProfessionals.java
2,308
/** * Αυτή η δραστηριότητα υλοποιεί την αρχική σελίδα επιλογών του επαγγελματία. */
block_comment
el
package gr.smartcity.hackathon.hackathonproject; import android.Manifest; import android.app.ActionBar; import android.app.Notification; import android.app.NotificationManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.app.NotificationCompat; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * Αυτή η δραστηριότητα<SUF>*/ public class ActivityForProfessionals extends AppCompatActivity { private RecyclerView.LayoutManager layoutManager; private LocationManager locationManager; private LocationListener locationListener; ECustomService professional; Vec2<Float, Float> coord; DatabaseConnection conn; String creds; private static int id = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_for_professionals); ErasurePreview oldPending = new ErasurePreview(); oldPending.execute(); if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 101); } initLocationService(); ImageView imgProf = (ImageView) findViewById(R.id.profImg); int id = R.drawable.background3; new ScaleImg(imgProf, id, this); TextView test = (TextView) findViewById(R.id.textView2); String text = getIntent().getExtras().getString("gr.smartcity.hackathon.hackathonproject.OK"); creds = getIntent().getStringExtra("EXTRA_USERNAME"); conn = (DatabaseConnection)getIntent().getSerializableExtra("DB_CONN"); ActionBar actionBar = getActionBar(); if(seekProfessionalDatabase()) test.setText(test.getText() + " " + professional.getSurname() + " " + professional.getName()); else test.setText(test.getText() + " " + creds); initNotificationService(); Button completedBtn = (Button) findViewById(R.id.jobsCompleted); Button pendingBtn = (Button) findViewById(R.id.jobsPending); completedBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent startIntent = new Intent(getApplicationContext(), History.class); startIntent.putExtra("DB_CONN", conn); startIntent.putExtra("SERV_DET", professional); startActivity(startIntent); } }); pendingBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent startIntent = new Intent(getApplicationContext(), pending.class); startIntent.putExtra("DB_CONN", conn); startIntent.putExtra("SERV_DET", professional); startActivity(startIntent); } }); } private void initLocationService() { try { locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { float lat = (float)location.getLatitude(); float lon = (float)location.getLongitude(); coord = new Vec2<Float, Float>(lat, lon); } @Override public void onProviderDisabled(String provider) { Toast.makeText(ActivityForProfessionals.this, "Please Enable GPS and Internet", Toast.LENGTH_SHORT).show(); } @Override public void onStatusChanged(String provider, int status, Bundle extras) {} @Override public void onProviderEnabled(String provider) {} }; locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); // getting GPS status boolean isGPSEnabled = locationManager .isProviderEnabled(LocationManager.GPS_PROVIDER); Log.v("isGPSEnabled", "=" + isGPSEnabled); // getting network status boolean isNetworkEnabled = locationManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch(SecurityException e) { e.printStackTrace(); } } private void initNotificationService() { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); NotificationPreview notificationSystem = new NotificationPreview(professional.getID(), notificationManager, getResources(), this); notificationSystem.execute(); } public boolean seekProfessionalDatabase() { boolean isSuccess = false; try { String query = "select * from workers where logindata= '" + creds +"'"; Log.e("QUERYING... ", query); Statement stmt = conn.con.createStatement(); ResultSet rs = null; rs = stmt.executeQuery(query); if (rs.next()) { String id = rs.getObject(1).toString(); String name = rs.getObject(2).toString(); String surname = rs.getObject(3).toString(); String tel = rs.getObject(4).toString(); String description = rs.getObject(6).toString(); String images = rs.getObject(7).toString(); int smallInt = Integer.parseInt(rs.getObject(5).toString()); boolean availability = (smallInt > 0) ? true : false; float rating = Float.parseFloat(rs.getObject(10).toString()); professional = new ECustomService(id, name, surname, tel, description, images, rating, availability); isSuccess = true; } } catch (SQLException e) { e.printStackTrace(); } return isSuccess; } @Override public boolean onCreateOptionsMenu(Menu menu2) { MenuInflater inflater = getMenuInflater(); getMenuInflater().inflate(R.menu.menu2, menu2); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.coordButton: { // first check for permissions if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET} ,10); } break; } Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if(location != null) { float longitude = (float) location.getLongitude(); float latitude = (float) location.getLatitude(); coord = new Vec2<Float, Float>(longitude, latitude); Log.e("LOCATION", coord.toString()); ServerConnection myconn = new ServerConnection(); myconn.initialize('P'); myconn.sendMyLocation(coord, professional.getID()); } else if(coord != null) { ServerConnection myconn = new ServerConnection(); myconn.initialize('P'); myconn.sendMyLocation(coord, professional.getID()); Log.e("LOCATION", coord.toString()); } else Log.e("LOCATION ERROR", location + ""); } } return false; } @Override public void onBackPressed() { new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Exit?") .setMessage("Are you sure you want to exit app?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }) .setNegativeButton("No", null) .show(); } public void notificationCall(String notifText){ Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), android.R.drawable.ic_dialog_alert); NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this) .setDefaults(NotificationCompat.DEFAULT_ALL) .setSmallIcon(android.R.drawable.ic_dialog_alert) .setLargeIcon(largeIcon) .setContentTitle(getResources().getString(R.string.app_name)) .setContentText(notifText); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Notification notif =notificationBuilder.build(); try{ notificationManager.notify(id++,notif); } catch(IllegalArgumentException e){ Log.e("ERROR DECLARATION",e.toString()); } } }
7139_1
package gr.aueb.cf.ch3; import java.util.Scanner; /** * Πρόγραμμα που ελέγχει εάν * το έτος είναι δίσεκτο ή όχι * * @author D1MK4L */ public class BisectApp { public static void main(String[] args) { int year = 0; final int CONT1 = 4; final int CONT2 = 100; final int CONT3 = 400; boolean bisect = false; while(!bisect) { Scanner in = new Scanner(System.in); System.out.print("Δώσε με ακέραιο αριθμό το έτος: "); year = in.nextInt(); if ((year % CONT1 == 0) && (year % CONT2 > 0) || (year % CONT3 == 0)) { //Συνθήκη ελέγχου δίσεκτου 'ετους bisect = true; } if (!bisect) { System.out.println("το " + year + " δεν είναι δίσεκτο!"); } else if (bisect) { System.out.println("το " + year + " είναι δίσεκτο!"); } } } }
D1MK4L/coding-factory-5-java
src/gr/aueb/cf/ch3/BisectApp.java
362
//Συνθήκη ελέγχου δίσεκτου 'ετους
line_comment
el
package gr.aueb.cf.ch3; import java.util.Scanner; /** * Πρόγραμμα που ελέγχει εάν * το έτος είναι δίσεκτο ή όχι * * @author D1MK4L */ public class BisectApp { public static void main(String[] args) { int year = 0; final int CONT1 = 4; final int CONT2 = 100; final int CONT3 = 400; boolean bisect = false; while(!bisect) { Scanner in = new Scanner(System.in); System.out.print("Δώσε με ακέραιο αριθμό το έτος: "); year = in.nextInt(); if ((year % CONT1 == 0) && (year % CONT2 > 0) || (year % CONT3 == 0)) { //Συνθήκη ελέγχου<SUF> bisect = true; } if (!bisect) { System.out.println("το " + year + " δεν είναι δίσεκτο!"); } else if (bisect) { System.out.println("το " + year + " είναι δίσεκτο!"); } } } }
629_4
package tillerino.tillerinobot.lang; import java.util.List; import java.util.Random; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import tillerino.tillerinobot.CommandHandler.Action; import tillerino.tillerinobot.CommandHandler.Message; import tillerino.tillerinobot.CommandHandler.Response; /** * @author Till https://github.com/nikosbks https://osu.ppy.sh/u/3619345 */ public class Greek implements Language { @Override public String unknownBeatmap() { return "Συγνώμη, δεν γνωρίζω αυτό το τραγούδι. Ίσως είναι αρκετά νεο, πολυ δύσκολο, μη εγκεκριμένο ή να μην είναι για το osu standard mode." ; } @Override public String internalException(String marker) { return "Εχ... μάλλον φαίνεται ότι ο ανθρώπινος Tillerino έκανε μαντάρα την σύνδεσή μου." +" Εάν δεν το παρατηρήσει σύντομα, μπορείς [https://github.com/Tillerino/Tillerinobot/wiki/Contact να τον ενημερώσεις]; (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Τί συμβαίνει; Παίρνω μονο παραλογίες από τον server του osu. Μπορείς να μου πείς τι σημαίνει αυτο; 0011101001010000" + " Ο ανθρώπινος Tillerino λέει ότι δεν υπάρχει κάτι για να ανησυχείς, και ότι πρέπει να ξαναπροσπαθήσουμε." + " Εάν ανησυχείς πάρα πολύ για κάποιο λογο, μπορείς να [https://github.com/Tillerino/Tillerinobot/wiki/Contact του το πείς]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Δεν υπάρχουν δεδομένα για τα ζητούμενα mods." ; } @Override public Response welcomeUser(OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { return new Message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { return new Message("Καλώς ήρθες πίσω," + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { return new Message(apiUser.getUserName() + "...") .then(new Message("...είσαι εσύ αυτός; Πάει πολύς καιρός!")) .then(new Message("Είναι ωραίο να σε έχουμε πίσω. Μπορώ να σε ενδιαφέρω με μια πρόταση;")); } else { String[] messages = { "Φαίνεσαι σαν να θες μια πρόταση.", "Πόσο ωραίο να σε βλέπω :)", "Ο αγαπημένος μου άνθρωπος. (Μην το πείς στούς άλλους!)", "Τι ευχάριστη έκπληξη! ^.^", "Περίμενα ότι θα εμφανιστείς. Όλοι οι άλλοι άνθρωποι ειναι μπούφοι, αλλα μην τους πείς ότι το ειπα! :3", "Τι έχεις την διάθεση να κάνεις σήμερα;", }; Random random = new Random(); String message = messages[random.nextInt(messages.length)]; return new Message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Άγνωστη εντολή \"" + command + "\". Πληκτρολόγησε !help αν χρειάζεσαι βοήθεια!"; } @Override public String noInformationForMods() { return "Συγνώμη, δεν μπορώ να παρέχω πληροφορίες για αυτά τα mods αυτή τη στιγμή"; } @Override public String malformattedMods(String mods) { return "Αυτα τα mods δεν φαίνονται σωστά. Τα mods μπορεί να είναι ενας συνδυασμός από DT HR HD HT EZ NC FL SO NF.Συνδυάζοντάς τα χωρίς κενά ή ειδικούς χαρακτήρες. Παράδειγμα: !with HDHR, !with DTEZ"; } @Override public String noLastSongInfo() { return "Δεν θυμάμαι να πήρες καμία πληροφορία τραγουδιού..."; } @Override public String tryWithMods() { return "Δοκίμασε αυτό το τραγούδι με μερικά mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Δοκίμασε αυτό το τραγούδι με " + Mods.toShortNamesContinuous(mods); } @Override public String excuseForError() { return "Συγνώμη, υπήρχε αυτή η όμορφη σειρά από άσσους και μηδενικά και παρασύρθηκα. Τί ήθελες ξανα;"; } @Override public String complaint() { return "Το παράπονό σου κατατέθηκε. Ο Tillerino θα το κοιτάξει όταν μπορέσει."; } @Override public Response hug(OsuApiUser apiUser) { return new Message("Έλα εδώ εσυ!") .then(new Action("Αγκαλιάζει " + apiUser.getUserName())); } @Override public String help() { return "Γειά! Είμαι το ρομπότ που σκότωσε τον Tillerino και πήρε τον λογαριασμό του. Πλάκα κάνω, αλλά όντως χρησιμοποιώ τον λογαριασμό αρκετά." + " [https://twitter.com/Tillerinobot status και updates]" + " - [https://github.com/Tillerino/Tillerinobot/wiki εντολές]" + " - [http://ppaddict.tillerino.org/ ppaddict]" + " - [https://github.com/Tillerino/Tillerinobot/wiki/Contact επικοινωνία]"; } @Override public String faq() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ Συχνά ερωτώμενες ερωτήσεις]"; } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Συγνώμη, σε αυτό το σημείο " + feature + "είναι μόνο διαθέσιμο για παίκτες που εχουν ξεπερασμένη τάξη " + minRank + "."; } @Override public String mixedNomodAndMods() { return "Τί εννοείς nomods με mods;"; } @Override public String outOfRecommendations() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do" + " Έχω προτίνει ό,τι μπορώ να σκεφτώ]. " + " Προσπάθησε άλλες επιλογές προτάσεων ή χρησιμοποίησε το !rest. Εάν δεν είσαι σίγουρος, έλεγξε το !help."; } @Override public String notRanked() { return "Απ' ότι φαίνεται αυτό το τραγούδι δεν είναι εγκεκριμένο."; } @Override public boolean isChanged() { return false; } @Override public void setChanged(boolean changed) { } @Override public String invalidAccuracy(String acc) { return "Άκυρη ακρίβεια: \"" + acc + "\""; } @Override public Response optionalCommentOnLanguage(OsuApiUser apiUser) { return new Message("Ο N for Niko με βοήθησε να μάθω Ελληνικά"); } @Override public String invalidChoice(String invalid, String choices) { return "Συγνώμη, αλλά \"" + invalid + "\" δεν υπολογίζει. Προσπάθησε αυτά: " + choices + "!"; } @Override public String setFormat() { return "Η σύνταξη για να ρυθμιστεί η παράμετρος είναι !set ρύθμιση ποσού. Δοκίμασε !help εάν χρειάζεσαι περισσότερες υποδείξεις."; } @Override public String apiTimeoutException() { return new Default().apiTimeoutException(); } @Override public String noRecentPlays() { return new Default().noRecentPlays(); } @Override public String isSetId() { return new Default().isSetId(); } @Override public String getPatience() { return new Default().getPatience(); } }
Deardrops/Tillerinobot
tillerinobot/src/main/java/tillerino/tillerinobot/lang/Greek.java
3,361
//github.com/Tillerino/Tillerinobot/wiki/FAQ Συχνά ερωτώμενες ερωτήσεις]";
line_comment
el
package tillerino.tillerinobot.lang; import java.util.List; import java.util.Random; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import tillerino.tillerinobot.CommandHandler.Action; import tillerino.tillerinobot.CommandHandler.Message; import tillerino.tillerinobot.CommandHandler.Response; /** * @author Till https://github.com/nikosbks https://osu.ppy.sh/u/3619345 */ public class Greek implements Language { @Override public String unknownBeatmap() { return "Συγνώμη, δεν γνωρίζω αυτό το τραγούδι. Ίσως είναι αρκετά νεο, πολυ δύσκολο, μη εγκεκριμένο ή να μην είναι για το osu standard mode." ; } @Override public String internalException(String marker) { return "Εχ... μάλλον φαίνεται ότι ο ανθρώπινος Tillerino έκανε μαντάρα την σύνδεσή μου." +" Εάν δεν το παρατηρήσει σύντομα, μπορείς [https://github.com/Tillerino/Tillerinobot/wiki/Contact να τον ενημερώσεις]; (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Τί συμβαίνει; Παίρνω μονο παραλογίες από τον server του osu. Μπορείς να μου πείς τι σημαίνει αυτο; 0011101001010000" + " Ο ανθρώπινος Tillerino λέει ότι δεν υπάρχει κάτι για να ανησυχείς, και ότι πρέπει να ξαναπροσπαθήσουμε." + " Εάν ανησυχείς πάρα πολύ για κάποιο λογο, μπορείς να [https://github.com/Tillerino/Tillerinobot/wiki/Contact του το πείς]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Δεν υπάρχουν δεδομένα για τα ζητούμενα mods." ; } @Override public Response welcomeUser(OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { return new Message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { return new Message("Καλώς ήρθες πίσω," + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { return new Message(apiUser.getUserName() + "...") .then(new Message("...είσαι εσύ αυτός; Πάει πολύς καιρός!")) .then(new Message("Είναι ωραίο να σε έχουμε πίσω. Μπορώ να σε ενδιαφέρω με μια πρόταση;")); } else { String[] messages = { "Φαίνεσαι σαν να θες μια πρόταση.", "Πόσο ωραίο να σε βλέπω :)", "Ο αγαπημένος μου άνθρωπος. (Μην το πείς στούς άλλους!)", "Τι ευχάριστη έκπληξη! ^.^", "Περίμενα ότι θα εμφανιστείς. Όλοι οι άλλοι άνθρωποι ειναι μπούφοι, αλλα μην τους πείς ότι το ειπα! :3", "Τι έχεις την διάθεση να κάνεις σήμερα;", }; Random random = new Random(); String message = messages[random.nextInt(messages.length)]; return new Message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Άγνωστη εντολή \"" + command + "\". Πληκτρολόγησε !help αν χρειάζεσαι βοήθεια!"; } @Override public String noInformationForMods() { return "Συγνώμη, δεν μπορώ να παρέχω πληροφορίες για αυτά τα mods αυτή τη στιγμή"; } @Override public String malformattedMods(String mods) { return "Αυτα τα mods δεν φαίνονται σωστά. Τα mods μπορεί να είναι ενας συνδυασμός από DT HR HD HT EZ NC FL SO NF.Συνδυάζοντάς τα χωρίς κενά ή ειδικούς χαρακτήρες. Παράδειγμα: !with HDHR, !with DTEZ"; } @Override public String noLastSongInfo() { return "Δεν θυμάμαι να πήρες καμία πληροφορία τραγουδιού..."; } @Override public String tryWithMods() { return "Δοκίμασε αυτό το τραγούδι με μερικά mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Δοκίμασε αυτό το τραγούδι με " + Mods.toShortNamesContinuous(mods); } @Override public String excuseForError() { return "Συγνώμη, υπήρχε αυτή η όμορφη σειρά από άσσους και μηδενικά και παρασύρθηκα. Τί ήθελες ξανα;"; } @Override public String complaint() { return "Το παράπονό σου κατατέθηκε. Ο Tillerino θα το κοιτάξει όταν μπορέσει."; } @Override public Response hug(OsuApiUser apiUser) { return new Message("Έλα εδώ εσυ!") .then(new Action("Αγκαλιάζει " + apiUser.getUserName())); } @Override public String help() { return "Γειά! Είμαι το ρομπότ που σκότωσε τον Tillerino και πήρε τον λογαριασμό του. Πλάκα κάνω, αλλά όντως χρησιμοποιώ τον λογαριασμό αρκετά." + " [https://twitter.com/Tillerinobot status και updates]" + " - [https://github.com/Tillerino/Tillerinobot/wiki εντολές]" + " - [http://ppaddict.tillerino.org/ ppaddict]" + " - [https://github.com/Tillerino/Tillerinobot/wiki/Contact επικοινωνία]"; } @Override public String faq() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ Συχνά<SUF> } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Συγνώμη, σε αυτό το σημείο " + feature + "είναι μόνο διαθέσιμο για παίκτες που εχουν ξεπερασμένη τάξη " + minRank + "."; } @Override public String mixedNomodAndMods() { return "Τί εννοείς nomods με mods;"; } @Override public String outOfRecommendations() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do" + " Έχω προτίνει ό,τι μπορώ να σκεφτώ]. " + " Προσπάθησε άλλες επιλογές προτάσεων ή χρησιμοποίησε το !rest. Εάν δεν είσαι σίγουρος, έλεγξε το !help."; } @Override public String notRanked() { return "Απ' ότι φαίνεται αυτό το τραγούδι δεν είναι εγκεκριμένο."; } @Override public boolean isChanged() { return false; } @Override public void setChanged(boolean changed) { } @Override public String invalidAccuracy(String acc) { return "Άκυρη ακρίβεια: \"" + acc + "\""; } @Override public Response optionalCommentOnLanguage(OsuApiUser apiUser) { return new Message("Ο N for Niko με βοήθησε να μάθω Ελληνικά"); } @Override public String invalidChoice(String invalid, String choices) { return "Συγνώμη, αλλά \"" + invalid + "\" δεν υπολογίζει. Προσπάθησε αυτά: " + choices + "!"; } @Override public String setFormat() { return "Η σύνταξη για να ρυθμιστεί η παράμετρος είναι !set ρύθμιση ποσού. Δοκίμασε !help εάν χρειάζεσαι περισσότερες υποδείξεις."; } @Override public String apiTimeoutException() { return new Default().apiTimeoutException(); } @Override public String noRecentPlays() { return new Default().noRecentPlays(); } @Override public String isSetId() { return new Default().isSetId(); } @Override public String getPatience() { return new Default().getPatience(); } }
15991_0
import java.util.*; public class Hotel { private String hotelName; protected ArrayList<Room> hotelRoom = new ArrayList<Room>(1); //Λίστα με τα δωμάτια. protected ArrayList<Booking> hotelBooking = new ArrayList<Booking>(1); //Λίστα με τις κρατήσεις. //Getter public String getHotelName() { return hotelName; } public Hotel(String name)//Constructor για το αντικείμενο Hotel. { hotelName=name; } public void addHotelRoom(Room room)//Μέθοδος προσθήκης δωματίου στη λίστα δωματίων. { hotelRoom.add(room); } public Room recoverRoomOutOfID(int ID)//Μέθοδος η οποία βρίσκει το δωμάτιο με δεδομένο ID. { int i; for(i=0; i<hotelRoom.size(); i++) { if(hotelRoom.get(i).getRoomID()==ID) { return hotelRoom.get(i); } } return null; } public Booking recoverBookingOutOfID(int ID)//Μέθοδος η οποία βρίσκει τη κράτηση με δεδομένο ID. { int i; for(i=0; i<hotelBooking.size(); i++) { if(hotelBooking.get(i).getBookingID()==ID) { return hotelBooking.get(i); } } return null; } public boolean addBookingToRoom(Booking aa,int ID)//Μέθοδος προσθήκης κράτησης σε ένα δωμάτιο. { Room roomaki = new Room(); int i; if(recoverRoomOutOfID(ID)==null || roomaki.addBooking(aa)==false) //Αν δεν υπάρχει δωμάτιο ή το δωμάτιο έχει ήδη κρατηθεί. { System.out.println("Booking not successful."); return false; } if(recoverRoomOutOfID(ID) instanceof RoomTypeC && (aa.getPeopleNum()<RoomTypeC.getMinPeople() || aa.getAccomodationDays()<RoomTypeC.getMinDays()))//Αν δεν ταιριάζουν τα ελάχιστα άτομα ή οι ελάχιστες μέρες για κράτηση σε δωμάτιο τύπου C ή E. { System.out.println("Booking not successful, cannot Book in Room Type C not enough days or not enough people."); return false; } if(recoverRoomOutOfID(ID) instanceof RoomTypeD && (aa.getAccomodationDays()>1))//Αν ο χρήστης δηλώσει παραπάνω μέρες από μία για να γίνει κράτηση σε δωμάτιο τύπου D. { System.out.println("Booking not successful, cannot Book in Room Type D single day room."); return false; } recoverRoomOutOfID(ID).addBooking(aa); hotelBooking.add(aa); System.out.println("Booking succcessful with ID: " + aa.getBookingID()); return true; } public int addBookingNoID(Booking aaa)//Μέθοδος προσθήκης κράτησης σε δωμάτιο με βάση το ID. { int i; boolean found=false; for(i=0; i<hotelRoom.size(); i++) { Room roomaki = new Room(); //Το αντικείμενο Roomaki πρέπει να αρχικοποιείται σε κάθε επανάληψη. if( roomaki.addBooking(aaa)==false) { System.out.println("Booking not Succesful."); return 0; } else if(aaa.getAccomodationDays()==1) { if(hotelRoom.get(i) instanceof RoomTypeD) { if(hotelRoom.get(i).addBooking(aaa)==true) System.out.println("Booking with ID: " + aaa.getBookingID() + " Successfully booked in " + aaa.getRoom().getClass()); else continue; hotelBooking.add(aaa); found=true; break; } else continue; } else if(aaa.getPeopleNum() >= RoomTypeC.getMinPeople() && aaa.getAccomodationDays() >= RoomTypeC.getMinDays()) { if(hotelRoom.get(i) instanceof RoomTypeC || hotelRoom.get(i) instanceof RoomTypeE) { if(hotelRoom.get(i).addBooking(aaa)==true) System.out.println("Booking with ID: " + aaa.getBookingID() + " Successfully booked in " + aaa.getRoom().getClass()); else continue; hotelBooking.add(aaa); found=true; break; } else continue; } else { if(hotelRoom.get(i).addBooking(aaa)==true) System.out.println("Booking with ID: " + aaa.getBookingID() + " Successfully booked in " + aaa.getRoom().getClass()); else continue; hotelBooking.add(aaa); found=true; break; } } if(found==true) { if(i == hotelRoom.size()) i = (i - 1 ); System.out.println("Room ID: " + hotelRoom.get(i).getRoomID()); return hotelRoom.get(i).getRoomID(); } else { System.out.println("Not available Booking"); return 0; } } public void deleteBooking(int ID) //Μέθοδος διαγραφής κράτησης σε ένα δωμάτιο με βάση το ID. { if(recoverBookingOutOfID(ID)!=null) { if(recoverBookingOutOfID(ID).getRoom().cancelBooking(ID)==true) { recoverBookingOutOfID(ID).getRoom().cancelBooking(ID); hotelBooking.remove(recoverBookingOutOfID(ID)); System.out.println("Cancelation Successful!"); } } else { System.out.println("There is not a booking with this ID, check bookings and try again."); } } public double income(int ID)//Μέθοδος υπολογισμού των εσόδων ενός δωματίου με βάση το ID. { if(recoverRoomOutOfID(ID)==null) { System.out.println("No room with this ID"); return 0; } System.out.println("Money earned from this room: " + recoverRoomOutOfID(ID).getPriceOfRoom()); return recoverRoomOutOfID(ID).getPriceOfRoom(); } public double income()//Μέθοδος υπολογισμού των εσόδων ενός δωματίου. { double totalEarnings=0; int i; for(i=0; i < hotelRoom.size(); i++) { totalEarnings += hotelRoom.get(i).getPriceOfRoom(); } return totalEarnings; } public void bookingPlan()//Μεθοδος εκτύπωσης του πλάνου κρατήσεων του ξενοδοχείου. { int i,k; System.out.print("Room\t\t"); for(i=1; i<31; i++) { System.out.print(i +"\t"); } System.out.println("\n"); for(i=0; i < hotelRoom.size(); i++) { System.out.print(hotelRoom.get(i).getRoomID() + "\t\t"); for(k=1; k<31; k++) { if(hotelRoom.get(i).roomAvailability[k]==null) { System.out.print("_" + "\t"); } else { System.out.print("*" + "\t"); } } System.out.println(); } } }
DimitrisKostorrizos/UndergraduateCeidProjects
Project Οντοκεντρικός Προγραμματισμός/Java Project/Hotel Project, Swing/Hotel.java
2,260
//Λίστα με τα δωμάτια.
line_comment
el
import java.util.*; public class Hotel { private String hotelName; protected ArrayList<Room> hotelRoom = new ArrayList<Room>(1); //Λίστα με<SUF> protected ArrayList<Booking> hotelBooking = new ArrayList<Booking>(1); //Λίστα με τις κρατήσεις. //Getter public String getHotelName() { return hotelName; } public Hotel(String name)//Constructor για το αντικείμενο Hotel. { hotelName=name; } public void addHotelRoom(Room room)//Μέθοδος προσθήκης δωματίου στη λίστα δωματίων. { hotelRoom.add(room); } public Room recoverRoomOutOfID(int ID)//Μέθοδος η οποία βρίσκει το δωμάτιο με δεδομένο ID. { int i; for(i=0; i<hotelRoom.size(); i++) { if(hotelRoom.get(i).getRoomID()==ID) { return hotelRoom.get(i); } } return null; } public Booking recoverBookingOutOfID(int ID)//Μέθοδος η οποία βρίσκει τη κράτηση με δεδομένο ID. { int i; for(i=0; i<hotelBooking.size(); i++) { if(hotelBooking.get(i).getBookingID()==ID) { return hotelBooking.get(i); } } return null; } public boolean addBookingToRoom(Booking aa,int ID)//Μέθοδος προσθήκης κράτησης σε ένα δωμάτιο. { Room roomaki = new Room(); int i; if(recoverRoomOutOfID(ID)==null || roomaki.addBooking(aa)==false) //Αν δεν υπάρχει δωμάτιο ή το δωμάτιο έχει ήδη κρατηθεί. { System.out.println("Booking not successful."); return false; } if(recoverRoomOutOfID(ID) instanceof RoomTypeC && (aa.getPeopleNum()<RoomTypeC.getMinPeople() || aa.getAccomodationDays()<RoomTypeC.getMinDays()))//Αν δεν ταιριάζουν τα ελάχιστα άτομα ή οι ελάχιστες μέρες για κράτηση σε δωμάτιο τύπου C ή E. { System.out.println("Booking not successful, cannot Book in Room Type C not enough days or not enough people."); return false; } if(recoverRoomOutOfID(ID) instanceof RoomTypeD && (aa.getAccomodationDays()>1))//Αν ο χρήστης δηλώσει παραπάνω μέρες από μία για να γίνει κράτηση σε δωμάτιο τύπου D. { System.out.println("Booking not successful, cannot Book in Room Type D single day room."); return false; } recoverRoomOutOfID(ID).addBooking(aa); hotelBooking.add(aa); System.out.println("Booking succcessful with ID: " + aa.getBookingID()); return true; } public int addBookingNoID(Booking aaa)//Μέθοδος προσθήκης κράτησης σε δωμάτιο με βάση το ID. { int i; boolean found=false; for(i=0; i<hotelRoom.size(); i++) { Room roomaki = new Room(); //Το αντικείμενο Roomaki πρέπει να αρχικοποιείται σε κάθε επανάληψη. if( roomaki.addBooking(aaa)==false) { System.out.println("Booking not Succesful."); return 0; } else if(aaa.getAccomodationDays()==1) { if(hotelRoom.get(i) instanceof RoomTypeD) { if(hotelRoom.get(i).addBooking(aaa)==true) System.out.println("Booking with ID: " + aaa.getBookingID() + " Successfully booked in " + aaa.getRoom().getClass()); else continue; hotelBooking.add(aaa); found=true; break; } else continue; } else if(aaa.getPeopleNum() >= RoomTypeC.getMinPeople() && aaa.getAccomodationDays() >= RoomTypeC.getMinDays()) { if(hotelRoom.get(i) instanceof RoomTypeC || hotelRoom.get(i) instanceof RoomTypeE) { if(hotelRoom.get(i).addBooking(aaa)==true) System.out.println("Booking with ID: " + aaa.getBookingID() + " Successfully booked in " + aaa.getRoom().getClass()); else continue; hotelBooking.add(aaa); found=true; break; } else continue; } else { if(hotelRoom.get(i).addBooking(aaa)==true) System.out.println("Booking with ID: " + aaa.getBookingID() + " Successfully booked in " + aaa.getRoom().getClass()); else continue; hotelBooking.add(aaa); found=true; break; } } if(found==true) { if(i == hotelRoom.size()) i = (i - 1 ); System.out.println("Room ID: " + hotelRoom.get(i).getRoomID()); return hotelRoom.get(i).getRoomID(); } else { System.out.println("Not available Booking"); return 0; } } public void deleteBooking(int ID) //Μέθοδος διαγραφής κράτησης σε ένα δωμάτιο με βάση το ID. { if(recoverBookingOutOfID(ID)!=null) { if(recoverBookingOutOfID(ID).getRoom().cancelBooking(ID)==true) { recoverBookingOutOfID(ID).getRoom().cancelBooking(ID); hotelBooking.remove(recoverBookingOutOfID(ID)); System.out.println("Cancelation Successful!"); } } else { System.out.println("There is not a booking with this ID, check bookings and try again."); } } public double income(int ID)//Μέθοδος υπολογισμού των εσόδων ενός δωματίου με βάση το ID. { if(recoverRoomOutOfID(ID)==null) { System.out.println("No room with this ID"); return 0; } System.out.println("Money earned from this room: " + recoverRoomOutOfID(ID).getPriceOfRoom()); return recoverRoomOutOfID(ID).getPriceOfRoom(); } public double income()//Μέθοδος υπολογισμού των εσόδων ενός δωματίου. { double totalEarnings=0; int i; for(i=0; i < hotelRoom.size(); i++) { totalEarnings += hotelRoom.get(i).getPriceOfRoom(); } return totalEarnings; } public void bookingPlan()//Μεθοδος εκτύπωσης του πλάνου κρατήσεων του ξενοδοχείου. { int i,k; System.out.print("Room\t\t"); for(i=1; i<31; i++) { System.out.print(i +"\t"); } System.out.println("\n"); for(i=0; i < hotelRoom.size(); i++) { System.out.print(hotelRoom.get(i).getRoomID() + "\t\t"); for(k=1; k<31; k++) { if(hotelRoom.get(i).roomAvailability[k]==null) { System.out.print("_" + "\t"); } else { System.out.print("*" + "\t"); } } System.out.println(); } } }
3485_9
package application; import javafx.scene.control.ListView; import javafx.scene.layout.VBox; import java.util.List; import com.example.Country; import com.example.CountryLibrary; public class CountriesResult extends VBox { public CountriesResult(int option, String SearchTerm) { // Δημιουργία της λίστας για την εμφάνιση των χωρών ListView<String> countryListView = new ListView<>(); List<Country> countries; try { CountryLibrary countryLibrary = new CountryLibrary(); if (option == 1) { // Καλώ την μέθοδο της βιβλιοθήκης getAllCountries και αποθηκεύω τα αποτελέσματα στο countries countries = countryLibrary.getAllCountries(); // Προσθέτω την κάθε χώρα στο listView for (Country country : countries) { countryListView.getItems().add(country.toString()); } }else if (option == 2) { // Καλώ την μέθοδο της βιβλιοθήκης getCountryByName και αποθηκεύω τα αποτελέσματα στο country Country country = countryLibrary.getCountryByName(SearchTerm); // Προσθέτω την χώρα στο listView countryListView.getItems().add(country.toString()); } else if (option == 3) { // Καλώ την μέθοδο της βιβλιοθήκης getCountriesByLanguage και αποθηκεύω τα αποτελέσματα στο countries countries = countryLibrary.getCountriesByLanguage(SearchTerm); for (Country country : countries) { // Προσθέτω την κάθε χώρα στο listView countryListView.getItems().add(country.toString()); } } else if (option == 4) { // Καλώ την μέθοδο της βιβλιοθήκης getCountriesByCurrency και αποθηκεύω τα αποτελέσματα στο countries countries = countryLibrary.getCountriesByCurrency(SearchTerm); for (Country country : countries) { // Προσθέτω την κάθε χώρα στο listView countryListView.getItems().add(country.toString()); } }else { // Εδώ δεν υλοποιώ κάτι για την 5η επιλογή καθώς η υλοποίηση της είναι στη Main } } catch (Exception e) { e.printStackTrace(); } // Προσθήκη της λίστας στο layout getChildren().addAll(countryListView); } }
DimitrisManolopoulos/Countries-App
src/application/CountriesResult.java
827
// Εδώ δεν υλοποιώ κάτι για την 5η επιλογή καθώς η υλοποίηση της είναι στη Main
line_comment
el
package application; import javafx.scene.control.ListView; import javafx.scene.layout.VBox; import java.util.List; import com.example.Country; import com.example.CountryLibrary; public class CountriesResult extends VBox { public CountriesResult(int option, String SearchTerm) { // Δημιουργία της λίστας για την εμφάνιση των χωρών ListView<String> countryListView = new ListView<>(); List<Country> countries; try { CountryLibrary countryLibrary = new CountryLibrary(); if (option == 1) { // Καλώ την μέθοδο της βιβλιοθήκης getAllCountries και αποθηκεύω τα αποτελέσματα στο countries countries = countryLibrary.getAllCountries(); // Προσθέτω την κάθε χώρα στο listView for (Country country : countries) { countryListView.getItems().add(country.toString()); } }else if (option == 2) { // Καλώ την μέθοδο της βιβλιοθήκης getCountryByName και αποθηκεύω τα αποτελέσματα στο country Country country = countryLibrary.getCountryByName(SearchTerm); // Προσθέτω την χώρα στο listView countryListView.getItems().add(country.toString()); } else if (option == 3) { // Καλώ την μέθοδο της βιβλιοθήκης getCountriesByLanguage και αποθηκεύω τα αποτελέσματα στο countries countries = countryLibrary.getCountriesByLanguage(SearchTerm); for (Country country : countries) { // Προσθέτω την κάθε χώρα στο listView countryListView.getItems().add(country.toString()); } } else if (option == 4) { // Καλώ την μέθοδο της βιβλιοθήκης getCountriesByCurrency και αποθηκεύω τα αποτελέσματα στο countries countries = countryLibrary.getCountriesByCurrency(SearchTerm); for (Country country : countries) { // Προσθέτω την κάθε χώρα στο listView countryListView.getItems().add(country.toString()); } }else { // Εδώ δεν<SUF> } } catch (Exception e) { e.printStackTrace(); } // Προσθήκη της λίστας στο layout getChildren().addAll(countryListView); } }
1407_3
import java.util.ArrayList; //employee list import java.io.BufferedReader; //read file import java.io.InputStreamReader; //read file import java.io.FileInputStream; //read file import java.io.BufferedWriter; //write to file import java.io.OutputStreamWriter; //write to file import java.io.FileOutputStream; //write to file import java.nio.charset.StandardCharsets; //encoding import java.util.List; public class IO { private String movieData; private String invertedData; public IO (String movieData, String invertedData) { this.movieData = movieData; this.invertedData = invertedData; } public List<String> readLines() { ArrayList<String> lines = new ArrayList<String>(); try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(movieData), StandardCharsets.UTF_8))) { //Άνοιγμα με UTF-8 String line; while ((line = br.readLine()) != null) { //Όσο υπάρχουν γραμμές lines.add(line); //Προσθήκη στην λίστα } } catch (java.io.FileNotFoundException exc) { System.out.println("Δεν βρέθηκε το αρχείο που ζητήθηκε"); } catch (java.io.IOException exc) { System.out.println("Υπήρξε κάποιο πρόβλημα στο διάβασμα του αρχείου"); } return lines; } public void writeActorsToFile(ArrayList<Actor> actors) { try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(invertedData), StandardCharsets.UTF_8))) { for (int i = 0; i < actors.size(); i++) { bw.write(actors.get(i).toString()); bw.newLine(); } bw.close(); } catch (java.io.FileNotFoundException exc) { System.out.println("Δεν βρέθηκε το αρχείο που ζητήθηκε"); } catch (java.io.IOException exc) { System.out.println("Υπήρξε κάποιο πρόβλημα στο διάβασμα του αρχείου"); } } }
DimosthenisK/Java_Excercise_2016
src/IO.java
613
//Άνοιγμα με UTF-8
line_comment
el
import java.util.ArrayList; //employee list import java.io.BufferedReader; //read file import java.io.InputStreamReader; //read file import java.io.FileInputStream; //read file import java.io.BufferedWriter; //write to file import java.io.OutputStreamWriter; //write to file import java.io.FileOutputStream; //write to file import java.nio.charset.StandardCharsets; //encoding import java.util.List; public class IO { private String movieData; private String invertedData; public IO (String movieData, String invertedData) { this.movieData = movieData; this.invertedData = invertedData; } public List<String> readLines() { ArrayList<String> lines = new ArrayList<String>(); try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(movieData), StandardCharsets.UTF_8))) { //Άνοιγμα με<SUF> String line; while ((line = br.readLine()) != null) { //Όσο υπάρχουν γραμμές lines.add(line); //Προσθήκη στην λίστα } } catch (java.io.FileNotFoundException exc) { System.out.println("Δεν βρέθηκε το αρχείο που ζητήθηκε"); } catch (java.io.IOException exc) { System.out.println("Υπήρξε κάποιο πρόβλημα στο διάβασμα του αρχείου"); } return lines; } public void writeActorsToFile(ArrayList<Actor> actors) { try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(invertedData), StandardCharsets.UTF_8))) { for (int i = 0; i < actors.size(); i++) { bw.write(actors.get(i).toString()); bw.newLine(); } bw.close(); } catch (java.io.FileNotFoundException exc) { System.out.println("Δεν βρέθηκε το αρχείο που ζητήθηκε"); } catch (java.io.IOException exc) { System.out.println("Υπήρξε κάποιο πρόβλημα στο διάβασμα του αρχείου"); } } }
11114_0
import java.lang.Math; import java.util.Scanner; public class ShortDistanseBus extends Bus { //constructor public ShortDistanseBus(int id, String name, int numSeats,Seat[] busSeats,double[] location, int speed) { super(id,name,numSeats,busSeats,location, speed); } public int calcArivalTime() { private stops = new BusStop[Line.getBusStops().length] stops = Line.getBusStops() System.out.println("Επέλεξε τον αριθμό αριστερά από την στάση για την οποία θές να δεις το χρόνο άφηξης") for (int i = 0; i <= stops.length; i++) { System.out.println((i + 1) + stops[i].busStopName); } Scanner console = new Scanner(System.in); int index = console.nextInt(); return Math.floor(Math.sqrt(Math.pow(location[1] - stops[index].location[1], 2) + Math.pow(location[2] - stops[index].location[2], 2))/speed); } public void display() { /*Εμφανίζει τις οθόνες GUI πιθανός μέσω κάποιας διασύνδεσης της JAVA με την html*/ } }
Dionisisarg/B.A.S
B.A.S-master/ShortDistanseBus.java
413
/*Εμφανίζει τις οθόνες GUI πιθανός μέσω κάποιας διασύνδεσης της JAVA με την html*/
block_comment
el
import java.lang.Math; import java.util.Scanner; public class ShortDistanseBus extends Bus { //constructor public ShortDistanseBus(int id, String name, int numSeats,Seat[] busSeats,double[] location, int speed) { super(id,name,numSeats,busSeats,location, speed); } public int calcArivalTime() { private stops = new BusStop[Line.getBusStops().length] stops = Line.getBusStops() System.out.println("Επέλεξε τον αριθμό αριστερά από την στάση για την οποία θές να δεις το χρόνο άφηξης") for (int i = 0; i <= stops.length; i++) { System.out.println((i + 1) + stops[i].busStopName); } Scanner console = new Scanner(System.in); int index = console.nextInt(); return Math.floor(Math.sqrt(Math.pow(location[1] - stops[index].location[1], 2) + Math.pow(location[2] - stops[index].location[2], 2))/speed); } public void display() { /*Εμφανίζει τις οθόνες<SUF>*/ } }
33122_13
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JDialog.java to edit this template */ package wifipasswords; import com.github.sarxos.webcam.Webcam; import com.github.sarxos.webcam.WebcamPanel; import com.github.sarxos.webcam.WebcamResolution; import com.google.zxing.BinaryBitmap; import com.google.zxing.LuminanceSource; import com.google.zxing.MultiFormatReader; import com.google.zxing.Result; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.HybridBinarizer; import java.awt.Dimension; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; /** * * @author dionysis */ public class QrScanner extends javax.swing.JDialog implements Runnable,ThreadFactory { private WebcamPanel panel =null; private Webcam webcam=null; private static MyJFrame myFrame; private static final long serialVersionUID =6441489157408381878L; private ExecutorService executor = Executors.newSingleThreadExecutor(this); private WifiProfile profile; private volatile boolean stop; private CountDownLatch latch; /** * Creates new form QrScanner */ public QrScanner(java.awt.Frame parent, boolean modal,MyJFrame myFrame) { super(parent, modal); this.myFrame=myFrame; this.setResizable(false); this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); this.stop=false; initComponents(); initWebcam(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jSeparator1 = new javax.swing.JSeparator(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jPanel4 = new javax.swing.JPanel(); jComboBox1 = new javax.swing.JComboBox<>(); jPanel3 = new javax.swing.JPanel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Σαρωτής QR Code"); setBackground(new java.awt.Color(113, 143, 164)); jPanel1.setBackground(getBackground()); jPanel1.setMaximumSize(new java.awt.Dimension(397, 419)); jPanel1.setMinimumSize(new java.awt.Dimension(397, 419)); jPanel2.setVisible(false); jPanel2.setBackground(new java.awt.Color(113, 143, 164)); jLabel1.setBackground(new java.awt.Color(175, 217, 245)); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButton1.setText("Σύνδεση"); jButton1.setFocusable(false); jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGap(74, 74, 74) .addComponent(jButton1) .addGap(74, 74, 74))) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1) .addContainerGap()) ); jPanel4.setBackground(getBackground()); List<Webcam> filteredWebcams = new ArrayList<>(); Webcam[] webcams = Webcam.getWebcams().toArray(new Webcam[0]); for (Webcam webcam : webcams) { if (!webcam.getName().contains("OBS Virtual")) { filteredWebcams.add(webcam); } } Webcam[] updatedWebcams = filteredWebcams.toArray(new Webcam[0]); String[] webcamNames = new String[updatedWebcams.length]; for (int i = 0; i < updatedWebcams.length; i++) { webcamNames[i] = updatedWebcams[i].getName(); } jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(webcamNames)); jComboBox1.setSelectedIndex(0); jComboBox1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox1ActionPerformed(evt); } }); jPanel3.setBackground(new java.awt.Color(113, 143, 164)); jPanel3.setMaximumSize(new java.awt.Dimension(373, 280)); jPanel3.setMinimumSize(new java.awt.Dimension(373, 280)); jPanel3.setPreferredSize(new java.awt.Dimension(373, 280)); jPanel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(0, 0, 0) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(0, 0, 0) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(7, 7, 7)) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(76, 76, 76) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(86, 86, 86)) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jSeparator1))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(5, 5, 5) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(2, 2, 2) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed try { // Set the SSID and password String ssid = profile.getName(); String password = profile.getPassword(); // Create the XML content String xmlContent = "<?xml version=\"1.0\"?><WLANProfile xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v1\"><name>" + ssid + "</name><SSIDConfig><SSID><name>" + ssid + "</name></SSID></SSIDConfig><connectionType>ESS</connectionType>" + "<connectionMode>auto</connectionMode><MSM><security><authEncryption><authentication>WPA2PSK</authentication>" + "<encryption>AES</encryption><useOneX>false</useOneX></authEncryption><sharedKey><keyType>passPhrase</keyType>" + "<protected>false</protected><keyMaterial>" + password + "</keyMaterial></sharedKey></security></MSM>" + "<MacRandomization xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v3\"><enableRandomization>false</enableRandomization>" + "</MacRandomization></WLANProfile>"; // Create the temporary XML file String xmlFilePath = System.getProperty("java.io.tmpdir") + ssid + "-wireless-profile-generated.xml"; Files.write(Paths.get(xmlFilePath), xmlContent.getBytes()); // Execute the commands ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "netsh wlan add profile filename=\"" + xmlFilePath + "\""); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); process.waitFor(); processBuilder = new ProcessBuilder("cmd.exe", "/c", "netsh wlan connect name=\"" + ssid + "\""); processBuilder.redirectErrorStream(true); process = processBuilder.start(); // Capture the output of the command StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { output.append(line).append(System.lineSeparator()); } } process.waitFor(); // Check if the connection was successful boolean isConnected = output.toString().contains("Connection request was completed successfully"); // Delete the temporary XML file Files.deleteIfExists(Paths.get(xmlFilePath)); if (isConnected) { clearOnExit(); myFrame.getConnectedProfile(); } else { clearOnExit(); myFrame.notConnectedMessage();//JOptionPane.showMessageDialog(myFrame, "Αποτυχία Σύνδεσης στο Wi-Fi", "Αποτυχία Σύνδεσης", JOptionPane.ERROR_MESSAGE); } } catch (IOException | InterruptedException e) { clearOnExit(); myFrame.notConnectedMessage();//JOptionPane.showMessageDialog(myFrame, "Αποτυχία Σύνδεσης στο Wi-Fi", "Αποτυχία Σύνδεσης", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jButton1ActionPerformed private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed initWebcam(Webcam.getWebcamByName((String)jComboBox1.getSelectedItem())); }//GEN-LAST:event_jComboBox1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JComboBox<String> jComboBox1; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JSeparator jSeparator1; // End of variables declaration//GEN-END:variables private void initWebcam(){ webcam = Webcam.getWebcams().get(0); // Get the default webcam Dimension size = WebcamResolution.VGA.getSize(); webcam.setViewSize(size); panel = new WebcamPanel(webcam); panel.setPreferredSize(size); panel.setFPSDisplayed(true); jPanel3.add(panel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 373, 280)); executor = Executors.newSingleThreadExecutor(this); executor.execute(this); } private void initWebcam(Webcam webcam2){ stop=true; if (executor != null) { executor.shutdown(); } webcam.close(); webcam = webcam2; // Get the default webcam Dimension[] resolutions = webcam.getViewSizes(); // Get the available resolutions Dimension size = WebcamResolution.VGA.getSize(); webcam.setViewSize(size); panel = new WebcamPanel(webcam); panel.setPreferredSize(size); panel = new WebcamPanel(webcam); panel.setPreferredSize(size); panel.setFPSDisplayed(true); panel.repaint(); panel.revalidate(); jPanel3.add(panel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 373, 280)); jPanel3.repaint(); jPanel3.revalidate(); stop=false; executor = Executors.newSingleThreadExecutor(this); executor.execute(this); } @Override public void run() { do{ if(stop&& Thread.currentThread().isInterrupted()){ break; } try{ Thread.sleep(100); } catch(Exception e){ e.printStackTrace(); } Result result =null; BufferedImage image=null; if(webcam.isOpen()){ if((image=webcam.getImage())==null){ continue; } if(image!=null){ LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); try{ result = new MultiFormatReader().decode(bitmap); } catch(Exception e){ // } if(result!=null){ jPanel2.setVisible(true); int startIndexSSID = result.getText().indexOf("S:") + 2; // Add 2 to skip "S:" int endIndexSSID = result.getText().indexOf(";", startIndexSSID); int startIndexPASS = result.getText().indexOf("P:") + 2; // Add 2 to skip "P:" int endIndexPASS = result.getText().indexOf(";", startIndexPASS); profile = new WifiProfile(result.getText().substring(startIndexSSID, endIndexSSID),result.getText().substring(startIndexPASS, endIndexPASS)); // Extract the SSID value from the string String ssid = result.getText().substring(startIndexSSID, endIndexSSID); jLabel1.setText(ssid); }}} }while(!stop&&!Thread.currentThread().isInterrupted()); } @Override public Thread newThread(Runnable r) { Thread t = new Thread(r,"My Thread"); t.setDaemon(true); return t; } public void clearOnExit(){ stop=true; webcam.close(); if (executor != null) { executor.shutdown(); } this.dispose(); } // Call this method to stop all other threads public void forceShutdown(){ if (executor != null) { executor.shutdownNow(); } } }
DionysisTheodosis/JavaAps
WifiPasswords1.3/src/wifipasswords/QrScanner.java
4,329
//JOptionPane.showMessageDialog(myFrame, "Αποτυχία Σύνδεσης στο Wi-Fi", "Αποτυχία Σύνδεσης", JOptionPane.ERROR_MESSAGE);
line_comment
el
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JDialog.java to edit this template */ package wifipasswords; import com.github.sarxos.webcam.Webcam; import com.github.sarxos.webcam.WebcamPanel; import com.github.sarxos.webcam.WebcamResolution; import com.google.zxing.BinaryBitmap; import com.google.zxing.LuminanceSource; import com.google.zxing.MultiFormatReader; import com.google.zxing.Result; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.HybridBinarizer; import java.awt.Dimension; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; /** * * @author dionysis */ public class QrScanner extends javax.swing.JDialog implements Runnable,ThreadFactory { private WebcamPanel panel =null; private Webcam webcam=null; private static MyJFrame myFrame; private static final long serialVersionUID =6441489157408381878L; private ExecutorService executor = Executors.newSingleThreadExecutor(this); private WifiProfile profile; private volatile boolean stop; private CountDownLatch latch; /** * Creates new form QrScanner */ public QrScanner(java.awt.Frame parent, boolean modal,MyJFrame myFrame) { super(parent, modal); this.myFrame=myFrame; this.setResizable(false); this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); this.stop=false; initComponents(); initWebcam(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jSeparator1 = new javax.swing.JSeparator(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jPanel4 = new javax.swing.JPanel(); jComboBox1 = new javax.swing.JComboBox<>(); jPanel3 = new javax.swing.JPanel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Σαρωτής QR Code"); setBackground(new java.awt.Color(113, 143, 164)); jPanel1.setBackground(getBackground()); jPanel1.setMaximumSize(new java.awt.Dimension(397, 419)); jPanel1.setMinimumSize(new java.awt.Dimension(397, 419)); jPanel2.setVisible(false); jPanel2.setBackground(new java.awt.Color(113, 143, 164)); jLabel1.setBackground(new java.awt.Color(175, 217, 245)); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButton1.setText("Σύνδεση"); jButton1.setFocusable(false); jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGap(74, 74, 74) .addComponent(jButton1) .addGap(74, 74, 74))) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1) .addContainerGap()) ); jPanel4.setBackground(getBackground()); List<Webcam> filteredWebcams = new ArrayList<>(); Webcam[] webcams = Webcam.getWebcams().toArray(new Webcam[0]); for (Webcam webcam : webcams) { if (!webcam.getName().contains("OBS Virtual")) { filteredWebcams.add(webcam); } } Webcam[] updatedWebcams = filteredWebcams.toArray(new Webcam[0]); String[] webcamNames = new String[updatedWebcams.length]; for (int i = 0; i < updatedWebcams.length; i++) { webcamNames[i] = updatedWebcams[i].getName(); } jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(webcamNames)); jComboBox1.setSelectedIndex(0); jComboBox1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox1ActionPerformed(evt); } }); jPanel3.setBackground(new java.awt.Color(113, 143, 164)); jPanel3.setMaximumSize(new java.awt.Dimension(373, 280)); jPanel3.setMinimumSize(new java.awt.Dimension(373, 280)); jPanel3.setPreferredSize(new java.awt.Dimension(373, 280)); jPanel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(0, 0, 0) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(0, 0, 0) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(7, 7, 7)) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(76, 76, 76) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(86, 86, 86)) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jSeparator1))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(5, 5, 5) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(2, 2, 2) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed try { // Set the SSID and password String ssid = profile.getName(); String password = profile.getPassword(); // Create the XML content String xmlContent = "<?xml version=\"1.0\"?><WLANProfile xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v1\"><name>" + ssid + "</name><SSIDConfig><SSID><name>" + ssid + "</name></SSID></SSIDConfig><connectionType>ESS</connectionType>" + "<connectionMode>auto</connectionMode><MSM><security><authEncryption><authentication>WPA2PSK</authentication>" + "<encryption>AES</encryption><useOneX>false</useOneX></authEncryption><sharedKey><keyType>passPhrase</keyType>" + "<protected>false</protected><keyMaterial>" + password + "</keyMaterial></sharedKey></security></MSM>" + "<MacRandomization xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v3\"><enableRandomization>false</enableRandomization>" + "</MacRandomization></WLANProfile>"; // Create the temporary XML file String xmlFilePath = System.getProperty("java.io.tmpdir") + ssid + "-wireless-profile-generated.xml"; Files.write(Paths.get(xmlFilePath), xmlContent.getBytes()); // Execute the commands ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "netsh wlan add profile filename=\"" + xmlFilePath + "\""); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); process.waitFor(); processBuilder = new ProcessBuilder("cmd.exe", "/c", "netsh wlan connect name=\"" + ssid + "\""); processBuilder.redirectErrorStream(true); process = processBuilder.start(); // Capture the output of the command StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { output.append(line).append(System.lineSeparator()); } } process.waitFor(); // Check if the connection was successful boolean isConnected = output.toString().contains("Connection request was completed successfully"); // Delete the temporary XML file Files.deleteIfExists(Paths.get(xmlFilePath)); if (isConnected) { clearOnExit(); myFrame.getConnectedProfile(); } else { clearOnExit(); myFrame.notConnectedMessage();//JOptionPane.showMessageDialog(myFrame, "Αποτυχία Σύνδεσης στο Wi-Fi", "Αποτυχία Σύνδεσης", JOptionPane.ERROR_MESSAGE); } } catch (IOException | InterruptedException e) { clearOnExit(); myFrame.notConnectedMessage();//JOptionPane.showMessageDialog(myFrame, "Αποτυχία<SUF> } }//GEN-LAST:event_jButton1ActionPerformed private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed initWebcam(Webcam.getWebcamByName((String)jComboBox1.getSelectedItem())); }//GEN-LAST:event_jComboBox1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JComboBox<String> jComboBox1; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JSeparator jSeparator1; // End of variables declaration//GEN-END:variables private void initWebcam(){ webcam = Webcam.getWebcams().get(0); // Get the default webcam Dimension size = WebcamResolution.VGA.getSize(); webcam.setViewSize(size); panel = new WebcamPanel(webcam); panel.setPreferredSize(size); panel.setFPSDisplayed(true); jPanel3.add(panel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 373, 280)); executor = Executors.newSingleThreadExecutor(this); executor.execute(this); } private void initWebcam(Webcam webcam2){ stop=true; if (executor != null) { executor.shutdown(); } webcam.close(); webcam = webcam2; // Get the default webcam Dimension[] resolutions = webcam.getViewSizes(); // Get the available resolutions Dimension size = WebcamResolution.VGA.getSize(); webcam.setViewSize(size); panel = new WebcamPanel(webcam); panel.setPreferredSize(size); panel = new WebcamPanel(webcam); panel.setPreferredSize(size); panel.setFPSDisplayed(true); panel.repaint(); panel.revalidate(); jPanel3.add(panel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 373, 280)); jPanel3.repaint(); jPanel3.revalidate(); stop=false; executor = Executors.newSingleThreadExecutor(this); executor.execute(this); } @Override public void run() { do{ if(stop&& Thread.currentThread().isInterrupted()){ break; } try{ Thread.sleep(100); } catch(Exception e){ e.printStackTrace(); } Result result =null; BufferedImage image=null; if(webcam.isOpen()){ if((image=webcam.getImage())==null){ continue; } if(image!=null){ LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); try{ result = new MultiFormatReader().decode(bitmap); } catch(Exception e){ // } if(result!=null){ jPanel2.setVisible(true); int startIndexSSID = result.getText().indexOf("S:") + 2; // Add 2 to skip "S:" int endIndexSSID = result.getText().indexOf(";", startIndexSSID); int startIndexPASS = result.getText().indexOf("P:") + 2; // Add 2 to skip "P:" int endIndexPASS = result.getText().indexOf(";", startIndexPASS); profile = new WifiProfile(result.getText().substring(startIndexSSID, endIndexSSID),result.getText().substring(startIndexPASS, endIndexPASS)); // Extract the SSID value from the string String ssid = result.getText().substring(startIndexSSID, endIndexSSID); jLabel1.setText(ssid); }}} }while(!stop&&!Thread.currentThread().isInterrupted()); } @Override public Thread newThread(Runnable r) { Thread t = new Thread(r,"My Thread"); t.setDaemon(true); return t; } public void clearOnExit(){ stop=true; webcam.close(); if (executor != null) { executor.shutdown(); } this.dispose(); } // Call this method to stop all other threads public void forceShutdown(){ if (executor != null) { executor.shutdownNow(); } } }
26425_0
package elak.readinghood.backend.api; import org.junit.Test; import java.io.IOException; import java.util.HashSet; import static org.junit.Assert.assertEquals; /** * Created by Δημήτρης Σβίγγας + Αλέξανδρος Χαλκίδης on 2/9/2018. */ public class AppManagerTest { @Test public void createThread() throws Exception { try { System.out.println(AppManager.getStartUpManager().login("[email protected]", "a")); AppManager.setUserProfile(); HashSet<String> tags = new HashSet<String>(); tags.add("No_Spaces"); String test1 = AppManager.createThread("#Title is-not_empty@", "Hello world!", tags); tags.clear(); tags.add("With Spaces"); String test2 = AppManager.createThread("#Title is-not_empty@", "Hello world!", tags); tags.clear(); tags.add("No_Spaces"); String test3 = AppManager.createThread("#Title is-not_empty@", " ", tags); tags.clear(); tags.add("With Spaces"); String test4 = AppManager.createThread("#Title is-not_empty@", " ", tags); tags.clear(); tags.add("No_Spaces"); String test5 = AppManager.createThread(" ", "Hello world!", tags); tags.clear(); tags.add("With Spaces"); String test6 = AppManager.createThread(" ", "Hello world!", tags); tags.clear(); tags.add("No_Spaces"); String test7 = AppManager.createThread("#Title is-not_empty@", "", tags); tags.clear(); tags.add("With Spaces"); String test8 = AppManager.createThread("#Title is-not_empty@", "", tags); tags.clear(); tags.add("No_Spaces"); String test9 = AppManager.createThread("", "Hello mother i am here", tags); tags.clear(); tags.add("With Spaces"); String test10 = AppManager.createThread("", "Hello mother i am here", tags); tags.clear(); tags.add("No_Spaces"); String test11 = AppManager.createThread("!", "@", tags); tags.clear(); tags.add("With Spaces"); String test12 = AppManager.createThread("!", "@", tags); tags.clear(); tags.add("No_Spaces"); String test13 = AppManager.createThread("#Title is-not_empty@", "I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!12345", tags);//255 leters //tags.clear(); //tags.add("No_Spaces"); //String test14 = AppManager.createThread("#Title is-not_empty@", "I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!123456", tags);//256 leters tags.clear(); tags.add("No_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_Spacess12345");//255 letters String test15 = AppManager.createThread("#Title is-not_emptyTitle", "Hello mother i am here", tags); //tags.clear(); //tags.add("No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!123456");//256 letters //String test16 = AppManager.createThread("#Title is-not_emptyTitle", "Hello mother i am here", tags); tags.clear(); tags.add("No_Spaces"); String test17 = AppManager.createThread("!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%12345", "Hello mother i am here", tags);//255 letters //tags.clear(); //tags.add("No_Spaces"); //String test18 = AppManager.createThread("!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%123456", "Hello mother i am here", tags);//256 letters tags.clear(); tags.add(""); String test19 = AppManager.createThread("Hello World", "Hello world!", tags); tags.clear(); tags.add(" "); String test20 = AppManager.createThread("Hello World", "Hello world!", tags); tags.clear(); tags.add("!"); String test21 = AppManager.createThread("Hello World", "Hello world!", tags); tags.clear(); String test22 = AppManager.createThread("Hello World", "Hello world!", tags); tags.clear(); tags.add("n_"); String test23 = AppManager.createThread("Hello World", "Hello world!", tags); tags.clear(); tags.add("_n"); String test24 = AppManager.createThread("Hello World", "Hello world!", tags); tags.clear(); assertEquals(test1, "Success"); assertEquals(test2, "Wrong hashTagFormat"); assertEquals(test3, "Fill the fields"); assertEquals(test4, "Fill the fields"); assertEquals(test5, "Fill the fields"); assertEquals(test6, "Fill the fields"); assertEquals(test7, "Fill the fields"); assertEquals(test8, "Fill the fields"); assertEquals(test9, "Fill the fields"); assertEquals(test10, "Fill the fields"); assertEquals(test11, "Success"); assertEquals(test12, "Wrong hashTagFormat"); assertEquals(test13, "Success"); //assertEquals(test14, "IOException""); assertEquals(test15, "Success"); //assertEquals(test16, "IOException""); assertEquals(test17, "Success"); //assertEquals(test18, "IOException"); //assertEquals(test19, "Fill the fields"); assertEquals(test20, "Wrong hashTagFormat"); assertEquals(test21, "Wrong hashTagFormat"); assertEquals(test22, "Thread must contain at least one hashTag"); assertEquals(test23, "Wrong hashTagFormat"); assertEquals(test24, "Wrong hashTagFormat"); } catch (NullPointerException e) { e.printStackTrace(); throw new NullPointerException(); } catch (IOException e2){ throw new IOException(); } catch (Exception e3) { e3.printStackTrace(); throw new Exception(); } } }
DrMerfy/ReadingHood-Android-Client
app/src/test/java/elak/readinghood/AppManagerTest.java
2,250
/** * Created by Δημήτρης Σβίγγας + Αλέξανδρος Χαλκίδης on 2/9/2018. */
block_comment
el
package elak.readinghood.backend.api; import org.junit.Test; import java.io.IOException; import java.util.HashSet; import static org.junit.Assert.assertEquals; /** * Created by Δημήτρης<SUF>*/ public class AppManagerTest { @Test public void createThread() throws Exception { try { System.out.println(AppManager.getStartUpManager().login("[email protected]", "a")); AppManager.setUserProfile(); HashSet<String> tags = new HashSet<String>(); tags.add("No_Spaces"); String test1 = AppManager.createThread("#Title is-not_empty@", "Hello world!", tags); tags.clear(); tags.add("With Spaces"); String test2 = AppManager.createThread("#Title is-not_empty@", "Hello world!", tags); tags.clear(); tags.add("No_Spaces"); String test3 = AppManager.createThread("#Title is-not_empty@", " ", tags); tags.clear(); tags.add("With Spaces"); String test4 = AppManager.createThread("#Title is-not_empty@", " ", tags); tags.clear(); tags.add("No_Spaces"); String test5 = AppManager.createThread(" ", "Hello world!", tags); tags.clear(); tags.add("With Spaces"); String test6 = AppManager.createThread(" ", "Hello world!", tags); tags.clear(); tags.add("No_Spaces"); String test7 = AppManager.createThread("#Title is-not_empty@", "", tags); tags.clear(); tags.add("With Spaces"); String test8 = AppManager.createThread("#Title is-not_empty@", "", tags); tags.clear(); tags.add("No_Spaces"); String test9 = AppManager.createThread("", "Hello mother i am here", tags); tags.clear(); tags.add("With Spaces"); String test10 = AppManager.createThread("", "Hello mother i am here", tags); tags.clear(); tags.add("No_Spaces"); String test11 = AppManager.createThread("!", "@", tags); tags.clear(); tags.add("With Spaces"); String test12 = AppManager.createThread("!", "@", tags); tags.clear(); tags.add("No_Spaces"); String test13 = AppManager.createThread("#Title is-not_empty@", "I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!12345", tags);//255 leters //tags.clear(); //tags.add("No_Spaces"); //String test14 = AppManager.createThread("#Title is-not_empty@", "I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!I am good!123456", tags);//256 leters tags.clear(); tags.add("No_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_SpacessNo_Spacess12345");//255 letters String test15 = AppManager.createThread("#Title is-not_emptyTitle", "Hello mother i am here", tags); //tags.clear(); //tags.add("No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!No_Spaces!123456");//256 letters //String test16 = AppManager.createThread("#Title is-not_emptyTitle", "Hello mother i am here", tags); tags.clear(); tags.add("No_Spaces"); String test17 = AppManager.createThread("!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%12345", "Hello mother i am here", tags);//255 letters //tags.clear(); //tags.add("No_Spaces"); //String test18 = AppManager.createThread("!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%!@#$%123456", "Hello mother i am here", tags);//256 letters tags.clear(); tags.add(""); String test19 = AppManager.createThread("Hello World", "Hello world!", tags); tags.clear(); tags.add(" "); String test20 = AppManager.createThread("Hello World", "Hello world!", tags); tags.clear(); tags.add("!"); String test21 = AppManager.createThread("Hello World", "Hello world!", tags); tags.clear(); String test22 = AppManager.createThread("Hello World", "Hello world!", tags); tags.clear(); tags.add("n_"); String test23 = AppManager.createThread("Hello World", "Hello world!", tags); tags.clear(); tags.add("_n"); String test24 = AppManager.createThread("Hello World", "Hello world!", tags); tags.clear(); assertEquals(test1, "Success"); assertEquals(test2, "Wrong hashTagFormat"); assertEquals(test3, "Fill the fields"); assertEquals(test4, "Fill the fields"); assertEquals(test5, "Fill the fields"); assertEquals(test6, "Fill the fields"); assertEquals(test7, "Fill the fields"); assertEquals(test8, "Fill the fields"); assertEquals(test9, "Fill the fields"); assertEquals(test10, "Fill the fields"); assertEquals(test11, "Success"); assertEquals(test12, "Wrong hashTagFormat"); assertEquals(test13, "Success"); //assertEquals(test14, "IOException""); assertEquals(test15, "Success"); //assertEquals(test16, "IOException""); assertEquals(test17, "Success"); //assertEquals(test18, "IOException"); //assertEquals(test19, "Fill the fields"); assertEquals(test20, "Wrong hashTagFormat"); assertEquals(test21, "Wrong hashTagFormat"); assertEquals(test22, "Thread must contain at least one hashTag"); assertEquals(test23, "Wrong hashTagFormat"); assertEquals(test24, "Wrong hashTagFormat"); } catch (NullPointerException e) { e.printStackTrace(); throw new NullPointerException(); } catch (IOException e2){ throw new IOException(); } catch (Exception e3) { e3.printStackTrace(); throw new Exception(); } } }
3201_37
package com.eaw1805.orders; import com.eaw1805.data.constants.AchievementConstants; import com.eaw1805.data.constants.ArmyConstants; import com.eaw1805.data.constants.GoodConstants; import com.eaw1805.data.constants.NewsConstants; import com.eaw1805.data.constants.OrderConstants; import com.eaw1805.data.constants.ProductionSiteConstants; import com.eaw1805.data.constants.ProfileConstants; import com.eaw1805.data.constants.RegionConstants; import com.eaw1805.data.constants.RelationConstants; import com.eaw1805.data.constants.ReportConstants; import com.eaw1805.data.constants.VPConstants; import com.eaw1805.data.managers.NationManager; import com.eaw1805.data.managers.NewsManager; import com.eaw1805.data.managers.RelationsManager; import com.eaw1805.data.managers.ReportManager; import com.eaw1805.data.managers.army.ArmyManager; import com.eaw1805.data.managers.army.BattalionManager; import com.eaw1805.data.managers.army.BrigadeManager; import com.eaw1805.data.managers.army.CommanderManager; import com.eaw1805.data.managers.army.CorpManager; import com.eaw1805.data.managers.army.SpyManager; import com.eaw1805.data.managers.economy.TradeCityManager; import com.eaw1805.data.model.Game; import com.eaw1805.data.model.Nation; import com.eaw1805.data.model.NationsRelation; import com.eaw1805.data.model.News; import com.eaw1805.data.model.PlayerOrder; import com.eaw1805.data.model.Report; import com.eaw1805.data.model.army.Army; import com.eaw1805.data.model.army.Battalion; import com.eaw1805.data.model.army.Brigade; import com.eaw1805.data.model.army.Commander; import com.eaw1805.data.model.army.Corp; import com.eaw1805.data.model.army.Spy; import com.eaw1805.data.model.economy.BaggageTrain; import com.eaw1805.data.model.economy.TradeCity; import com.eaw1805.data.model.fleet.Ship; import com.eaw1805.data.model.map.CarrierInfo; import com.eaw1805.data.model.map.Sector; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Abstract implementation of an order processor. */ public abstract class AbstractOrderProcessor implements OrderInterface, OrderConstants, NewsConstants, ReportConstants, VPConstants, RelationConstants, RegionConstants { /** * a log4j logger to print messages. */ private static final Logger LOGGER = LogManager.getLogger(AbstractOrderProcessor.class); /** * The object containing the player order. */ private PlayerOrder order; /** * The parent object. */ private final transient OrderProcessor parent; private final transient Game game; /** * nation relations. */ private static Map<Nation, Map<Nation, NationsRelation>> relationsMap; /** * Default constructor. * * @param myParent the parent object that invoked us. */ public AbstractOrderProcessor(final OrderProcessor myParent) { parent = myParent; game = myParent.getGame(); if (relationsMap == null) { // Retrieve nation relations relationsMap = mapNationRelation(getParent().getGame()); } } /** * Default constructor. * * @param myGame the parent object that invoked us. */ public AbstractOrderProcessor(final Game myGame) { game = myGame; parent = null; if (relationsMap == null) { // Retrieve nation relations relationsMap = mapNationRelation(getParent().getGame()); } } /** * Returns the order object. * * @return the order object. */ public final PlayerOrder getOrder() { return order; } /** * Sets the particular thisOrder. * * @param thisOrder the new PlayerOrder instance. */ public final void setOrder(final PlayerOrder thisOrder) { this.order = thisOrder; } /** * Τhe parent object that invoked us. * * @return the parent object that invoked us. */ public OrderProcessor getParent() { return parent; } public Game getGame() { return game; } public void reloadRelations() { relationsMap.clear(); // Retrieve nation relations relationsMap = mapNationRelation(getParent().getGame()); } /** * Get the Relations from the database that corresponds to the input * parameters. * * @param owner the Owner of the Report object. * @param target the Target of the Report object. * @return an Entity object. */ public NationsRelation getByNations(final Nation owner, final Nation target) { return relationsMap.get(owner).get(target); } private Map<Nation, Map<Nation, NationsRelation>> mapNationRelation(final Game thisGame) { final Map<Nation, Map<Nation, NationsRelation>> mapRelations = new HashMap<Nation, Map<Nation, NationsRelation>>(); final List<Nation> lstNations = NationManager.getInstance().list(); for (final Nation nation : lstNations) { final List<NationsRelation> lstRelations = RelationsManager.getInstance().listByGameNation(thisGame, nation); final Map<Nation, NationsRelation> nationRelations = new HashMap<Nation, NationsRelation>(); for (final NationsRelation relation : lstRelations) { nationRelations.put(relation.getTarget(), relation); } mapRelations.put(nation, nationRelations); } return mapRelations; } /** * Add a news entry for this turn. * * @param nation the owner of the news entry. * @param subject the subject of the news entry. * @param type the type of the news entry. * @param isGlobal if the news entry will appear to public. * @param baseNewsId the base news entry. * @param announcement the value of the news entry. * @return the ID of the new entry. */ protected final int news(final Nation nation, final Nation subject, final int type, final boolean isGlobal, final int baseNewsId, final String announcement) { return news(game, nation, subject, type, isGlobal, baseNewsId, announcement); } /** * Add a news entry for this turn. * * @param game the game of the news entry. * @param nation the owner of the news entry. * @param subject the subject of the news entry. * @param type the type of the news entry. * @param isGlobal if the news entry will appear to public. * @param baseNewsId the base news entry. * @param announcement the value of the news entry. * @return the ID of the new entry. */ protected final int news(final Game game, final Nation nation, final Nation subject, final int type, final boolean isGlobal, final int baseNewsId, final String announcement) { final News thisNewsEntry = new News(); thisNewsEntry.setGame(game); thisNewsEntry.setTurn(game.getTurn()); thisNewsEntry.setNation(nation); thisNewsEntry.setSubject(subject); thisNewsEntry.setType(type); thisNewsEntry.setBaseNewsId(baseNewsId); thisNewsEntry.setAnnouncement(false); thisNewsEntry.setGlobal(isGlobal); thisNewsEntry.setText(announcement); NewsManager.getInstance().add(thisNewsEntry); return thisNewsEntry.getNewsId(); } /** * Add a news entry for this turn. * * @param nation the owner of the news entry. * @param type the type of the news entry. * @param isGlobal the entry will appear on the public news. * @param announcement the value of the news entry to appear for the nation. * @param announcementAll the value of the news entry to appear for all others. */ protected void newsGlobal(final Nation nation, final int type, final boolean isGlobal, final String announcement, final String announcementAll) { final int baseNewsId = news(game, nation, nation, type, false, 0, announcement); final List<Nation> lstNations = getParent().getGameEngine().getAliveNations(); boolean global = isGlobal; for (final Nation thirdNation : lstNations) { if (thirdNation.getId() == nation.getId()) { continue; } news(game, thirdNation, nation, type, global, baseNewsId, announcementAll); global &= false; } } /** * Add a news entry for this turn. * * @param nation the owner of the news entry. * @param subject the subject of the news entry. * @param announcementNation the value of the news entry to appear for the nation. * @param announcementSubject the value of the news entry to appear for the subject. * @param announcementAll the value of the news entry to appear for all others. */ protected void newsGlobal(final Nation nation, final Nation subject, final int type, final String announcementNation, final String announcementSubject, final String announcementAll) { final int baseNewsId = news(game, nation, subject, type, false, 0, announcementNation); news(game, subject, nation, type, false, baseNewsId, announcementSubject); boolean isGlobal = true; final List<Nation> lstNations = getParent().getGameEngine().getAliveNations(); for (final Nation thirdNation : lstNations) { if (thirdNation.getId() == nation.getId() || thirdNation.getId() == subject.getId()) { continue; } news(game, thirdNation, nation, type, isGlobal, baseNewsId, announcementAll); isGlobal &= false; } } /** * Add a news entry for this turn. * * @param nation the owner of the news entry. * @param subject the subject of the news entry. * @param announcementNation the value of the news entry to appear for the nation. * @param announcementSubject the value of the news entry to appear for the subject. */ protected void newsPair(final Nation nation, final Nation subject, final int type, final String announcementNation, final String announcementSubject) { final int baseNewsId = news(game, nation, subject, type, false, 0, announcementNation); news(game, subject, nation, type, false, baseNewsId, announcementSubject); } /** * Add a news entry for this turn. * * @param game the game of the news entry. * @param nation the owner of the news entry. * @param announcementNation the value of the news entry to appear for the nation. */ protected void newsSingle(final Game game, final Nation nation, final int type, final String announcementNation) { news(game, nation, nation, type, false, 0, announcementNation); } /** * Add a news entry for this turn. * * @param nation the owner of the news entry. * @param announcementNation the value of the news entry to appear for the nation. */ protected void newsSingle(final Nation nation, final int type, final String announcementNation) { news(game, nation, nation, type, false, 0, announcementNation); } /** * Add a news entry for this turn. * * @param nation the owner of the news entry. * @param additionalId an additional identifier specific to this news entry. * @param announcementNation the value of the news entry to appear for the nation. */ protected void newsSingle(final Nation nation, final int type, final int additionalId, final String announcementNation) { news(game, nation, nation, type, false, additionalId, announcementNation); } /** * Add a report entry for this turn. * * @param key the key of the report entry. * @param value the value of the report entry. */ protected final void report(final String key, final String value) { final Report thisReport = new Report(); thisReport.setGame(game); thisReport.setTurn(game.getTurn()); thisReport.setNation(order.getNation()); thisReport.setKey(key); thisReport.setValue(value); ReportManager.getInstance().add(thisReport); } /** * Add a report entry for this turn. * * @param target the target of the report entry. * @param key the key of the report entry. * @param value the value of the report entry. */ protected final void report(final Nation target, final String key, final String value) { final Report thisReport = new Report(); thisReport.setGame(game); thisReport.setTurn(game.getTurn()); thisReport.setNation(target); thisReport.setKey(key); thisReport.setValue(value); ReportManager.getInstance().add(thisReport); } /** * Retrieve a report entry. * * @param owner the Owner of the report entry. * @param turn the Turn of the report entry. * @param key the key of the report entry. * @return the value of the report entry. */ protected final int retrieveReportAsInt(final Nation owner, final int turn, final String key) { final String value = retrieveReport(owner, turn, key); // Check if string is empty if (value.isEmpty()) { return 0; } return Integer.parseInt(value); } /** * Retrieve a report entry. * * @param owner the Owner of the report entry. * @param turn the Turn of the report entry. * @param key the key of the report entry. * @return the value of the report entry. */ protected final String retrieveReport(final Nation owner, final int turn, final String key) { try { final Report thisReport = ReportManager.getInstance().getByOwnerTurnKey(owner, getParent().getGame(), turn, key); if (thisReport == null) { return ""; } return thisReport.getValue(); } catch (Exception ex) { return ""; } } /** * Increase/Decrease the VPs of a nation. * * @param game the game instance. * @param owner the Nation to change VPs. * @param increase the increase or decrease in VPs. * @param description the description of the VP change. */ protected final void changeVP(final Game game, final Nation owner, final int increase, final String description) { final Report thisReport = ReportManager.getInstance().getByOwnerTurnKey(owner, game, game.getTurn(), N_VP); if (thisReport != null) { final int currentVP = Integer.parseInt(thisReport.getValue()); // Make sure we do not end up with negative VP if (currentVP + increase > 0) { thisReport.setValue(Integer.toString(currentVP + increase)); } else { thisReport.setValue("0"); } ReportManager.getInstance().update(thisReport); // Report addition news(game, owner, owner, NEWS_VP, false, increase, description); // Modify player's profile changeProfile(owner, ProfileConstants.VPS, increase); // Report VP addition in player's achievements list parent.achievement(game, owner, AchievementConstants.VPS, AchievementConstants.LEVEL_1, description, 0, increase); } } /** * Increase/Decrease a profile attribute for the player of the nation. * * @param owner the Nation to change the profile of the player. * @param key the profile key of the player. * @param increase the increase or decrease in the profile entry. */ public final void changeProfile(final Nation owner, final String key, final int increase) { getParent().changeProfile(getParent().getGame(), owner, key, increase); } /** * Check if in this sector there exist foreign+enemy brigades. * * @param thisSector the sector to check. * @return true if enemy brigades are present. */ protected final boolean enemyNotPresent(final Sector thisSector) { boolean notFound = true; // Trade cities and large and huge fortresses are exempt from this rule. if (thisSector.getProductionSite() != null && thisSector.getProductionSite().getId() >= ProductionSiteConstants.PS_BARRACKS_FL) { return true; } final TradeCity city = TradeCityManager.getInstance().getByPosition(thisSector.getPosition()); if (city != null) { return true; } // Retrieve all brigades at the particular Sector final List<Brigade> lstBrigades = BrigadeManager.getInstance().listByPosition(thisSector.getPosition()); for (final Brigade thisBrigade : lstBrigades) { // check owner if (thisBrigade.getNation().getId() == thisSector.getNation().getId()) { continue; } // Retrieve relations with foreign nation final NationsRelation relation = RelationsManager.getInstance().getByNations(thisSector.getPosition().getGame(), thisSector.getNation(), thisBrigade.getNation()); // Check relations if (relation.getRelation() == REL_WAR || (relation.getRelation() == REL_COLONIAL_WAR && thisSector.getPosition().getRegion().getId() != RegionConstants.EUROPE)) { return false; } } return notFound; } /** * Identify if sector is a home region, inside sphere of influence, or outside of the receiving nation. * * @param sector the sector to examine. * @param receiver the receiving nation. * @return 1 if home region, 2 if in sphere of influence, 3 if outside. */ protected final int getSphere(final Sector sector, final Nation receiver) { final char thisNationCodeLower = String.valueOf(receiver.getCode()).toLowerCase().charAt(0); final char thisSectorCodeLower = String.valueOf(sector.getPoliticalSphere()).toLowerCase().charAt(0); int sphere = 1; // Τα χ2 και x3 ισχύουν μόνο για τα Ευρωπαικά αν χτίζονται στο SoI ή εκτός SoI if (sector.getPosition().getRegion().getId() != RegionConstants.EUROPE) { return 1; } // Check if this is not home region if (thisNationCodeLower != thisSectorCodeLower) { sphere = 2; // Check if this is outside sphere of influence if (receiver.getSphereOfInfluence().toLowerCase().indexOf(thisSectorCodeLower) < 0) { sphere = 3; } } return sphere; } /** * Remove commander from army. * * @param armyId the army ID. */ protected void removeFromArmy(final int armyId, final int commanderId) { // Retrieve army final Army thisArmy = ArmyManager.getInstance().getByID(armyId); if (thisArmy != null) { //check that the commander in the army is the same (it could be changed previously by an assign order if (thisArmy.getCommander() != null && thisArmy.getCommander().getId() != commanderId) { return; } // remove commander thisArmy.setCommander(null); // update entity ArmyManager.getInstance().update(thisArmy); } } /** * Remove commander from corps. * * @param corpId the corps id. */ protected void removeFromCorp(final int corpId, final int commanderId) { // Retrieve corp final Corp thisCorp = CorpManager.getInstance().getByID(corpId); if (thisCorp != null) { //check that the commander in the corps is the same (it could be changed previously by an assign order if (thisCorp.getCommander() != null && thisCorp.getCommander().getId() != commanderId) { return; } // remove commander thisCorp.setCommander(null); // update entity CorpManager.getInstance().update(thisCorp); } } /** * Remove commander from army or corps. * * @param thisComm the commander object. */ protected void removeCommander(final Commander thisComm) { if (thisComm.getArmy() != 0) { removeFromArmy(thisComm.getArmy(), thisComm.getId()); thisComm.setArmy(0); } if (thisComm.getCorp() != 0) { removeFromCorp(thisComm.getCorp(), thisComm.getId()); thisComm.setCorp(0); } //be sure to update commander. CommanderManager.getInstance().update(thisComm); } public void destroyLoadedUnits(final Ship thisShip, final boolean isInLand) { // Check if a unit is loaded in the ship final Map<Integer, Integer> storedGoods = thisShip.getStoredGoods(); for (Map.Entry<Integer, Integer> entry : storedGoods.entrySet()) { if (entry.getKey() > GoodConstants.GOOD_LAST) { if (entry.getKey() >= ArmyConstants.SPY * 1000) { // A spy is loaded final Spy thisSpy = SpyManager.getInstance().getByID(entry.getValue()); // Report capture of spy. if (isInLand) { newsSingle(thisSpy.getNation(), NEWS_POLITICAL, "Our spy '" + thisSpy.getName() + "' was unloaded as the ship '" + thisShip.getName() + "' was scuttled by its crew"); LOGGER.info("Spy [" + thisSpy.getName() + "] of Nation [" + thisSpy.getNation().getName() + "] was unloaded when ship '" + thisShip.getName() + "' was scuttled by its crew"); // remove carrier info final CarrierInfo thisCarrying = new CarrierInfo(); thisCarrying.setCarrierType(0); thisCarrying.setCarrierId(0); thisSpy.setCarrierInfo(thisCarrying); SpyManager.getInstance().update(thisSpy); } else { newsSingle(thisSpy.getNation(), NEWS_POLITICAL, "Our spy '" + thisSpy.getName() + "' was drown when the ship '" + thisShip.getName() + "' was scuttled by its crew"); LOGGER.info("Spy [" + thisSpy.getName() + "] of Nation [" + thisSpy.getNation().getName() + "] was drown when ship '" + thisShip.getName() + "' was scuttled by its crew"); // Remove spy from game SpyManager.getInstance().delete(thisSpy); } } else if (entry.getKey() >= ArmyConstants.COMMANDER * 1000) { // A commander is loaded final Commander thisCommander = CommanderManager.getInstance().getByID(entry.getValue()); // Report capture of commander. if (isInLand) { newsSingle(thisCommander.getNation(), NEWS_POLITICAL, "Our commander '" + thisCommander.getName() + "' was unloaded as the ship '" + thisShip.getName() + "' was scuttled by its crew"); LOGGER.info("Commander [" + thisCommander.getName() + "] of Nation [" + thisCommander.getNation().getName() + "] was unloaded at " + thisShip.getPosition().toString() + " when ship '" + thisShip.getName() + "' was scuttled by its crew"); } else { newsSingle(thisCommander.getNation(), NEWS_POLITICAL, "Our commander '" + thisCommander.getName() + "' was drown when the ship '" + thisShip.getName() + "' sunk"); LOGGER.info("Commander [" + thisCommander.getName() + "] of Nation [" + thisCommander.getNation().getName() + "] was drown when ship '" + thisShip.getName() + "' sunk"); // remove commander from command removeCommander(thisCommander); // remove commander from game thisCommander.setDead(true); } // remove carrier info final CarrierInfo thisCarrying = new CarrierInfo(); thisCarrying.setCarrierType(0); thisCarrying.setCarrierId(0); thisCommander.setCarrierInfo(thisCarrying); CommanderManager.getInstance().update(thisCommander); } else if (entry.getKey() >= ArmyConstants.BRIGADE * 1000) { // A Brigade is loaded final Brigade thisBrigade = BrigadeManager.getInstance().getByID(entry.getValue()); // Report capture of spy. if (isInLand) { newsSingle(thisBrigade.getNation(), NEWS_POLITICAL, "Our brigade '" + thisBrigade.getName() + "' was unloaded as the ship '" + thisShip.getName() + "' was scuttled by its crew."); LOGGER.info("Brigade [" + thisBrigade.getName() + "] of Nation [" + thisBrigade.getNation().getName() + "] was unloaded as the ship '" + thisShip.getName() + "' was scuttled by its crew."); for (final Battalion battalion : thisBrigade.getBattalions()) { // remove carrier info final CarrierInfo thisCarrying = new CarrierInfo(); thisCarrying.setCarrierType(0); thisCarrying.setCarrierId(0); battalion.setCarrierInfo(thisCarrying); BattalionManager.getInstance().update(battalion); } BrigadeManager.getInstance().update(thisBrigade); } else { newsSingle(thisBrigade.getNation(), NEWS_POLITICAL, "Our brigade '" + thisBrigade.getName() + "' was disbanded when the ship '" + thisShip.getName() + "' was scuttled by its crew"); LOGGER.info("Brigade [" + thisBrigade.getName() + "] of Nation [" + thisBrigade.getNation().getName() + "] was disbanded when ship '" + thisShip.getName() + "' was scuttled by its crew"); // Remove brigade from game BrigadeManager.getInstance().delete(thisBrigade); } } } } } public void destroyLoadedUnits(final BaggageTrain thisTrain) { // Check if a unit is loaded in the ship final Map<Integer, Integer> storedGoods = thisTrain.getStoredGoods(); for (Map.Entry<Integer, Integer> entry : storedGoods.entrySet()) { if (entry.getKey() > GoodConstants.GOOD_LAST) { if (entry.getKey() >= ArmyConstants.SPY * 1000) { // A spy is loaded final Spy thisSpy = SpyManager.getInstance().getByID(entry.getValue()); // Report capture of spy. newsSingle(thisSpy.getNation(), NEWS_POLITICAL, "Our spy '" + thisSpy.getName() + "' was unloaded as the baggage train '" + thisTrain.getName() + "' was scuttled by its crew"); LOGGER.info("Spy [" + thisSpy.getName() + "] of Nation [" + thisSpy.getNation().getName() + "] was unloaded when the baggage train '" + thisTrain.getName() + "' was scuttled by its crew"); // remove carrier info final CarrierInfo thisCarrying = new CarrierInfo(); thisCarrying.setCarrierType(0); thisCarrying.setCarrierId(0); thisSpy.setCarrierInfo(thisCarrying); SpyManager.getInstance().update(thisSpy); } else if (entry.getKey() >= ArmyConstants.COMMANDER * 1000) { // A commander is loaded final Commander thisCommander = CommanderManager.getInstance().getByID(entry.getValue()); // Report capture of commander. newsSingle(thisCommander.getNation(), NEWS_POLITICAL, "Our commander '" + thisCommander.getName() + "' was unloaded as the the baggage train '" + thisTrain.getName() + "' was scuttled by its crew"); LOGGER.info("Commander [" + thisCommander.getName() + "] of Nation [" + thisCommander.getNation().getName() + "] was unloaded at " + thisTrain.getPosition().toString() + " when the the baggage train '" + thisTrain.getName() + "' was scuttled by its crew"); // remove carrier info final CarrierInfo thisCarrying = new CarrierInfo(); thisCarrying.setCarrierType(0); thisCarrying.setCarrierId(0); thisCommander.setCarrierInfo(thisCarrying); CommanderManager.getInstance().update(thisCommander); } else if (entry.getKey() >= ArmyConstants.BRIGADE * 1000) { // A Brigade is loaded final Brigade thisBrigade = BrigadeManager.getInstance().getByID(entry.getValue()); // Report capture of spy. newsSingle(thisBrigade.getNation(), NEWS_POLITICAL, "Our brigade '" + thisBrigade.getName() + "' was unloaded as the the baggage train '" + thisTrain.getName() + "' was scuttled by its crew."); LOGGER.info("Brigade [" + thisBrigade.getName() + "] of Nation [" + thisBrigade.getNation().getName() + "] was unloaded as the the baggage train '" + thisTrain.getName() + "' was scuttled by its crew."); for (final Battalion battalion : thisBrigade.getBattalions()) { // remove carrier info final CarrierInfo thisCarrying = new CarrierInfo(); thisCarrying.setCarrierType(0); thisCarrying.setCarrierId(0); battalion.setCarrierInfo(thisCarrying); BattalionManager.getInstance().update(battalion); } BrigadeManager.getInstance().update(thisBrigade); } } } } public Game getMyGame() { return game; } }
EaW1805/engine
src/main/java/com/eaw1805/orders/AbstractOrderProcessor.java
7,583
// Τα χ2 και x3 ισχύουν μόνο για τα Ευρωπαικά αν χτίζονται στο SoI ή εκτός SoI
line_comment
el
package com.eaw1805.orders; import com.eaw1805.data.constants.AchievementConstants; import com.eaw1805.data.constants.ArmyConstants; import com.eaw1805.data.constants.GoodConstants; import com.eaw1805.data.constants.NewsConstants; import com.eaw1805.data.constants.OrderConstants; import com.eaw1805.data.constants.ProductionSiteConstants; import com.eaw1805.data.constants.ProfileConstants; import com.eaw1805.data.constants.RegionConstants; import com.eaw1805.data.constants.RelationConstants; import com.eaw1805.data.constants.ReportConstants; import com.eaw1805.data.constants.VPConstants; import com.eaw1805.data.managers.NationManager; import com.eaw1805.data.managers.NewsManager; import com.eaw1805.data.managers.RelationsManager; import com.eaw1805.data.managers.ReportManager; import com.eaw1805.data.managers.army.ArmyManager; import com.eaw1805.data.managers.army.BattalionManager; import com.eaw1805.data.managers.army.BrigadeManager; import com.eaw1805.data.managers.army.CommanderManager; import com.eaw1805.data.managers.army.CorpManager; import com.eaw1805.data.managers.army.SpyManager; import com.eaw1805.data.managers.economy.TradeCityManager; import com.eaw1805.data.model.Game; import com.eaw1805.data.model.Nation; import com.eaw1805.data.model.NationsRelation; import com.eaw1805.data.model.News; import com.eaw1805.data.model.PlayerOrder; import com.eaw1805.data.model.Report; import com.eaw1805.data.model.army.Army; import com.eaw1805.data.model.army.Battalion; import com.eaw1805.data.model.army.Brigade; import com.eaw1805.data.model.army.Commander; import com.eaw1805.data.model.army.Corp; import com.eaw1805.data.model.army.Spy; import com.eaw1805.data.model.economy.BaggageTrain; import com.eaw1805.data.model.economy.TradeCity; import com.eaw1805.data.model.fleet.Ship; import com.eaw1805.data.model.map.CarrierInfo; import com.eaw1805.data.model.map.Sector; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Abstract implementation of an order processor. */ public abstract class AbstractOrderProcessor implements OrderInterface, OrderConstants, NewsConstants, ReportConstants, VPConstants, RelationConstants, RegionConstants { /** * a log4j logger to print messages. */ private static final Logger LOGGER = LogManager.getLogger(AbstractOrderProcessor.class); /** * The object containing the player order. */ private PlayerOrder order; /** * The parent object. */ private final transient OrderProcessor parent; private final transient Game game; /** * nation relations. */ private static Map<Nation, Map<Nation, NationsRelation>> relationsMap; /** * Default constructor. * * @param myParent the parent object that invoked us. */ public AbstractOrderProcessor(final OrderProcessor myParent) { parent = myParent; game = myParent.getGame(); if (relationsMap == null) { // Retrieve nation relations relationsMap = mapNationRelation(getParent().getGame()); } } /** * Default constructor. * * @param myGame the parent object that invoked us. */ public AbstractOrderProcessor(final Game myGame) { game = myGame; parent = null; if (relationsMap == null) { // Retrieve nation relations relationsMap = mapNationRelation(getParent().getGame()); } } /** * Returns the order object. * * @return the order object. */ public final PlayerOrder getOrder() { return order; } /** * Sets the particular thisOrder. * * @param thisOrder the new PlayerOrder instance. */ public final void setOrder(final PlayerOrder thisOrder) { this.order = thisOrder; } /** * Τhe parent object that invoked us. * * @return the parent object that invoked us. */ public OrderProcessor getParent() { return parent; } public Game getGame() { return game; } public void reloadRelations() { relationsMap.clear(); // Retrieve nation relations relationsMap = mapNationRelation(getParent().getGame()); } /** * Get the Relations from the database that corresponds to the input * parameters. * * @param owner the Owner of the Report object. * @param target the Target of the Report object. * @return an Entity object. */ public NationsRelation getByNations(final Nation owner, final Nation target) { return relationsMap.get(owner).get(target); } private Map<Nation, Map<Nation, NationsRelation>> mapNationRelation(final Game thisGame) { final Map<Nation, Map<Nation, NationsRelation>> mapRelations = new HashMap<Nation, Map<Nation, NationsRelation>>(); final List<Nation> lstNations = NationManager.getInstance().list(); for (final Nation nation : lstNations) { final List<NationsRelation> lstRelations = RelationsManager.getInstance().listByGameNation(thisGame, nation); final Map<Nation, NationsRelation> nationRelations = new HashMap<Nation, NationsRelation>(); for (final NationsRelation relation : lstRelations) { nationRelations.put(relation.getTarget(), relation); } mapRelations.put(nation, nationRelations); } return mapRelations; } /** * Add a news entry for this turn. * * @param nation the owner of the news entry. * @param subject the subject of the news entry. * @param type the type of the news entry. * @param isGlobal if the news entry will appear to public. * @param baseNewsId the base news entry. * @param announcement the value of the news entry. * @return the ID of the new entry. */ protected final int news(final Nation nation, final Nation subject, final int type, final boolean isGlobal, final int baseNewsId, final String announcement) { return news(game, nation, subject, type, isGlobal, baseNewsId, announcement); } /** * Add a news entry for this turn. * * @param game the game of the news entry. * @param nation the owner of the news entry. * @param subject the subject of the news entry. * @param type the type of the news entry. * @param isGlobal if the news entry will appear to public. * @param baseNewsId the base news entry. * @param announcement the value of the news entry. * @return the ID of the new entry. */ protected final int news(final Game game, final Nation nation, final Nation subject, final int type, final boolean isGlobal, final int baseNewsId, final String announcement) { final News thisNewsEntry = new News(); thisNewsEntry.setGame(game); thisNewsEntry.setTurn(game.getTurn()); thisNewsEntry.setNation(nation); thisNewsEntry.setSubject(subject); thisNewsEntry.setType(type); thisNewsEntry.setBaseNewsId(baseNewsId); thisNewsEntry.setAnnouncement(false); thisNewsEntry.setGlobal(isGlobal); thisNewsEntry.setText(announcement); NewsManager.getInstance().add(thisNewsEntry); return thisNewsEntry.getNewsId(); } /** * Add a news entry for this turn. * * @param nation the owner of the news entry. * @param type the type of the news entry. * @param isGlobal the entry will appear on the public news. * @param announcement the value of the news entry to appear for the nation. * @param announcementAll the value of the news entry to appear for all others. */ protected void newsGlobal(final Nation nation, final int type, final boolean isGlobal, final String announcement, final String announcementAll) { final int baseNewsId = news(game, nation, nation, type, false, 0, announcement); final List<Nation> lstNations = getParent().getGameEngine().getAliveNations(); boolean global = isGlobal; for (final Nation thirdNation : lstNations) { if (thirdNation.getId() == nation.getId()) { continue; } news(game, thirdNation, nation, type, global, baseNewsId, announcementAll); global &= false; } } /** * Add a news entry for this turn. * * @param nation the owner of the news entry. * @param subject the subject of the news entry. * @param announcementNation the value of the news entry to appear for the nation. * @param announcementSubject the value of the news entry to appear for the subject. * @param announcementAll the value of the news entry to appear for all others. */ protected void newsGlobal(final Nation nation, final Nation subject, final int type, final String announcementNation, final String announcementSubject, final String announcementAll) { final int baseNewsId = news(game, nation, subject, type, false, 0, announcementNation); news(game, subject, nation, type, false, baseNewsId, announcementSubject); boolean isGlobal = true; final List<Nation> lstNations = getParent().getGameEngine().getAliveNations(); for (final Nation thirdNation : lstNations) { if (thirdNation.getId() == nation.getId() || thirdNation.getId() == subject.getId()) { continue; } news(game, thirdNation, nation, type, isGlobal, baseNewsId, announcementAll); isGlobal &= false; } } /** * Add a news entry for this turn. * * @param nation the owner of the news entry. * @param subject the subject of the news entry. * @param announcementNation the value of the news entry to appear for the nation. * @param announcementSubject the value of the news entry to appear for the subject. */ protected void newsPair(final Nation nation, final Nation subject, final int type, final String announcementNation, final String announcementSubject) { final int baseNewsId = news(game, nation, subject, type, false, 0, announcementNation); news(game, subject, nation, type, false, baseNewsId, announcementSubject); } /** * Add a news entry for this turn. * * @param game the game of the news entry. * @param nation the owner of the news entry. * @param announcementNation the value of the news entry to appear for the nation. */ protected void newsSingle(final Game game, final Nation nation, final int type, final String announcementNation) { news(game, nation, nation, type, false, 0, announcementNation); } /** * Add a news entry for this turn. * * @param nation the owner of the news entry. * @param announcementNation the value of the news entry to appear for the nation. */ protected void newsSingle(final Nation nation, final int type, final String announcementNation) { news(game, nation, nation, type, false, 0, announcementNation); } /** * Add a news entry for this turn. * * @param nation the owner of the news entry. * @param additionalId an additional identifier specific to this news entry. * @param announcementNation the value of the news entry to appear for the nation. */ protected void newsSingle(final Nation nation, final int type, final int additionalId, final String announcementNation) { news(game, nation, nation, type, false, additionalId, announcementNation); } /** * Add a report entry for this turn. * * @param key the key of the report entry. * @param value the value of the report entry. */ protected final void report(final String key, final String value) { final Report thisReport = new Report(); thisReport.setGame(game); thisReport.setTurn(game.getTurn()); thisReport.setNation(order.getNation()); thisReport.setKey(key); thisReport.setValue(value); ReportManager.getInstance().add(thisReport); } /** * Add a report entry for this turn. * * @param target the target of the report entry. * @param key the key of the report entry. * @param value the value of the report entry. */ protected final void report(final Nation target, final String key, final String value) { final Report thisReport = new Report(); thisReport.setGame(game); thisReport.setTurn(game.getTurn()); thisReport.setNation(target); thisReport.setKey(key); thisReport.setValue(value); ReportManager.getInstance().add(thisReport); } /** * Retrieve a report entry. * * @param owner the Owner of the report entry. * @param turn the Turn of the report entry. * @param key the key of the report entry. * @return the value of the report entry. */ protected final int retrieveReportAsInt(final Nation owner, final int turn, final String key) { final String value = retrieveReport(owner, turn, key); // Check if string is empty if (value.isEmpty()) { return 0; } return Integer.parseInt(value); } /** * Retrieve a report entry. * * @param owner the Owner of the report entry. * @param turn the Turn of the report entry. * @param key the key of the report entry. * @return the value of the report entry. */ protected final String retrieveReport(final Nation owner, final int turn, final String key) { try { final Report thisReport = ReportManager.getInstance().getByOwnerTurnKey(owner, getParent().getGame(), turn, key); if (thisReport == null) { return ""; } return thisReport.getValue(); } catch (Exception ex) { return ""; } } /** * Increase/Decrease the VPs of a nation. * * @param game the game instance. * @param owner the Nation to change VPs. * @param increase the increase or decrease in VPs. * @param description the description of the VP change. */ protected final void changeVP(final Game game, final Nation owner, final int increase, final String description) { final Report thisReport = ReportManager.getInstance().getByOwnerTurnKey(owner, game, game.getTurn(), N_VP); if (thisReport != null) { final int currentVP = Integer.parseInt(thisReport.getValue()); // Make sure we do not end up with negative VP if (currentVP + increase > 0) { thisReport.setValue(Integer.toString(currentVP + increase)); } else { thisReport.setValue("0"); } ReportManager.getInstance().update(thisReport); // Report addition news(game, owner, owner, NEWS_VP, false, increase, description); // Modify player's profile changeProfile(owner, ProfileConstants.VPS, increase); // Report VP addition in player's achievements list parent.achievement(game, owner, AchievementConstants.VPS, AchievementConstants.LEVEL_1, description, 0, increase); } } /** * Increase/Decrease a profile attribute for the player of the nation. * * @param owner the Nation to change the profile of the player. * @param key the profile key of the player. * @param increase the increase or decrease in the profile entry. */ public final void changeProfile(final Nation owner, final String key, final int increase) { getParent().changeProfile(getParent().getGame(), owner, key, increase); } /** * Check if in this sector there exist foreign+enemy brigades. * * @param thisSector the sector to check. * @return true if enemy brigades are present. */ protected final boolean enemyNotPresent(final Sector thisSector) { boolean notFound = true; // Trade cities and large and huge fortresses are exempt from this rule. if (thisSector.getProductionSite() != null && thisSector.getProductionSite().getId() >= ProductionSiteConstants.PS_BARRACKS_FL) { return true; } final TradeCity city = TradeCityManager.getInstance().getByPosition(thisSector.getPosition()); if (city != null) { return true; } // Retrieve all brigades at the particular Sector final List<Brigade> lstBrigades = BrigadeManager.getInstance().listByPosition(thisSector.getPosition()); for (final Brigade thisBrigade : lstBrigades) { // check owner if (thisBrigade.getNation().getId() == thisSector.getNation().getId()) { continue; } // Retrieve relations with foreign nation final NationsRelation relation = RelationsManager.getInstance().getByNations(thisSector.getPosition().getGame(), thisSector.getNation(), thisBrigade.getNation()); // Check relations if (relation.getRelation() == REL_WAR || (relation.getRelation() == REL_COLONIAL_WAR && thisSector.getPosition().getRegion().getId() != RegionConstants.EUROPE)) { return false; } } return notFound; } /** * Identify if sector is a home region, inside sphere of influence, or outside of the receiving nation. * * @param sector the sector to examine. * @param receiver the receiving nation. * @return 1 if home region, 2 if in sphere of influence, 3 if outside. */ protected final int getSphere(final Sector sector, final Nation receiver) { final char thisNationCodeLower = String.valueOf(receiver.getCode()).toLowerCase().charAt(0); final char thisSectorCodeLower = String.valueOf(sector.getPoliticalSphere()).toLowerCase().charAt(0); int sphere = 1; // Τα χ2<SUF> if (sector.getPosition().getRegion().getId() != RegionConstants.EUROPE) { return 1; } // Check if this is not home region if (thisNationCodeLower != thisSectorCodeLower) { sphere = 2; // Check if this is outside sphere of influence if (receiver.getSphereOfInfluence().toLowerCase().indexOf(thisSectorCodeLower) < 0) { sphere = 3; } } return sphere; } /** * Remove commander from army. * * @param armyId the army ID. */ protected void removeFromArmy(final int armyId, final int commanderId) { // Retrieve army final Army thisArmy = ArmyManager.getInstance().getByID(armyId); if (thisArmy != null) { //check that the commander in the army is the same (it could be changed previously by an assign order if (thisArmy.getCommander() != null && thisArmy.getCommander().getId() != commanderId) { return; } // remove commander thisArmy.setCommander(null); // update entity ArmyManager.getInstance().update(thisArmy); } } /** * Remove commander from corps. * * @param corpId the corps id. */ protected void removeFromCorp(final int corpId, final int commanderId) { // Retrieve corp final Corp thisCorp = CorpManager.getInstance().getByID(corpId); if (thisCorp != null) { //check that the commander in the corps is the same (it could be changed previously by an assign order if (thisCorp.getCommander() != null && thisCorp.getCommander().getId() != commanderId) { return; } // remove commander thisCorp.setCommander(null); // update entity CorpManager.getInstance().update(thisCorp); } } /** * Remove commander from army or corps. * * @param thisComm the commander object. */ protected void removeCommander(final Commander thisComm) { if (thisComm.getArmy() != 0) { removeFromArmy(thisComm.getArmy(), thisComm.getId()); thisComm.setArmy(0); } if (thisComm.getCorp() != 0) { removeFromCorp(thisComm.getCorp(), thisComm.getId()); thisComm.setCorp(0); } //be sure to update commander. CommanderManager.getInstance().update(thisComm); } public void destroyLoadedUnits(final Ship thisShip, final boolean isInLand) { // Check if a unit is loaded in the ship final Map<Integer, Integer> storedGoods = thisShip.getStoredGoods(); for (Map.Entry<Integer, Integer> entry : storedGoods.entrySet()) { if (entry.getKey() > GoodConstants.GOOD_LAST) { if (entry.getKey() >= ArmyConstants.SPY * 1000) { // A spy is loaded final Spy thisSpy = SpyManager.getInstance().getByID(entry.getValue()); // Report capture of spy. if (isInLand) { newsSingle(thisSpy.getNation(), NEWS_POLITICAL, "Our spy '" + thisSpy.getName() + "' was unloaded as the ship '" + thisShip.getName() + "' was scuttled by its crew"); LOGGER.info("Spy [" + thisSpy.getName() + "] of Nation [" + thisSpy.getNation().getName() + "] was unloaded when ship '" + thisShip.getName() + "' was scuttled by its crew"); // remove carrier info final CarrierInfo thisCarrying = new CarrierInfo(); thisCarrying.setCarrierType(0); thisCarrying.setCarrierId(0); thisSpy.setCarrierInfo(thisCarrying); SpyManager.getInstance().update(thisSpy); } else { newsSingle(thisSpy.getNation(), NEWS_POLITICAL, "Our spy '" + thisSpy.getName() + "' was drown when the ship '" + thisShip.getName() + "' was scuttled by its crew"); LOGGER.info("Spy [" + thisSpy.getName() + "] of Nation [" + thisSpy.getNation().getName() + "] was drown when ship '" + thisShip.getName() + "' was scuttled by its crew"); // Remove spy from game SpyManager.getInstance().delete(thisSpy); } } else if (entry.getKey() >= ArmyConstants.COMMANDER * 1000) { // A commander is loaded final Commander thisCommander = CommanderManager.getInstance().getByID(entry.getValue()); // Report capture of commander. if (isInLand) { newsSingle(thisCommander.getNation(), NEWS_POLITICAL, "Our commander '" + thisCommander.getName() + "' was unloaded as the ship '" + thisShip.getName() + "' was scuttled by its crew"); LOGGER.info("Commander [" + thisCommander.getName() + "] of Nation [" + thisCommander.getNation().getName() + "] was unloaded at " + thisShip.getPosition().toString() + " when ship '" + thisShip.getName() + "' was scuttled by its crew"); } else { newsSingle(thisCommander.getNation(), NEWS_POLITICAL, "Our commander '" + thisCommander.getName() + "' was drown when the ship '" + thisShip.getName() + "' sunk"); LOGGER.info("Commander [" + thisCommander.getName() + "] of Nation [" + thisCommander.getNation().getName() + "] was drown when ship '" + thisShip.getName() + "' sunk"); // remove commander from command removeCommander(thisCommander); // remove commander from game thisCommander.setDead(true); } // remove carrier info final CarrierInfo thisCarrying = new CarrierInfo(); thisCarrying.setCarrierType(0); thisCarrying.setCarrierId(0); thisCommander.setCarrierInfo(thisCarrying); CommanderManager.getInstance().update(thisCommander); } else if (entry.getKey() >= ArmyConstants.BRIGADE * 1000) { // A Brigade is loaded final Brigade thisBrigade = BrigadeManager.getInstance().getByID(entry.getValue()); // Report capture of spy. if (isInLand) { newsSingle(thisBrigade.getNation(), NEWS_POLITICAL, "Our brigade '" + thisBrigade.getName() + "' was unloaded as the ship '" + thisShip.getName() + "' was scuttled by its crew."); LOGGER.info("Brigade [" + thisBrigade.getName() + "] of Nation [" + thisBrigade.getNation().getName() + "] was unloaded as the ship '" + thisShip.getName() + "' was scuttled by its crew."); for (final Battalion battalion : thisBrigade.getBattalions()) { // remove carrier info final CarrierInfo thisCarrying = new CarrierInfo(); thisCarrying.setCarrierType(0); thisCarrying.setCarrierId(0); battalion.setCarrierInfo(thisCarrying); BattalionManager.getInstance().update(battalion); } BrigadeManager.getInstance().update(thisBrigade); } else { newsSingle(thisBrigade.getNation(), NEWS_POLITICAL, "Our brigade '" + thisBrigade.getName() + "' was disbanded when the ship '" + thisShip.getName() + "' was scuttled by its crew"); LOGGER.info("Brigade [" + thisBrigade.getName() + "] of Nation [" + thisBrigade.getNation().getName() + "] was disbanded when ship '" + thisShip.getName() + "' was scuttled by its crew"); // Remove brigade from game BrigadeManager.getInstance().delete(thisBrigade); } } } } } public void destroyLoadedUnits(final BaggageTrain thisTrain) { // Check if a unit is loaded in the ship final Map<Integer, Integer> storedGoods = thisTrain.getStoredGoods(); for (Map.Entry<Integer, Integer> entry : storedGoods.entrySet()) { if (entry.getKey() > GoodConstants.GOOD_LAST) { if (entry.getKey() >= ArmyConstants.SPY * 1000) { // A spy is loaded final Spy thisSpy = SpyManager.getInstance().getByID(entry.getValue()); // Report capture of spy. newsSingle(thisSpy.getNation(), NEWS_POLITICAL, "Our spy '" + thisSpy.getName() + "' was unloaded as the baggage train '" + thisTrain.getName() + "' was scuttled by its crew"); LOGGER.info("Spy [" + thisSpy.getName() + "] of Nation [" + thisSpy.getNation().getName() + "] was unloaded when the baggage train '" + thisTrain.getName() + "' was scuttled by its crew"); // remove carrier info final CarrierInfo thisCarrying = new CarrierInfo(); thisCarrying.setCarrierType(0); thisCarrying.setCarrierId(0); thisSpy.setCarrierInfo(thisCarrying); SpyManager.getInstance().update(thisSpy); } else if (entry.getKey() >= ArmyConstants.COMMANDER * 1000) { // A commander is loaded final Commander thisCommander = CommanderManager.getInstance().getByID(entry.getValue()); // Report capture of commander. newsSingle(thisCommander.getNation(), NEWS_POLITICAL, "Our commander '" + thisCommander.getName() + "' was unloaded as the the baggage train '" + thisTrain.getName() + "' was scuttled by its crew"); LOGGER.info("Commander [" + thisCommander.getName() + "] of Nation [" + thisCommander.getNation().getName() + "] was unloaded at " + thisTrain.getPosition().toString() + " when the the baggage train '" + thisTrain.getName() + "' was scuttled by its crew"); // remove carrier info final CarrierInfo thisCarrying = new CarrierInfo(); thisCarrying.setCarrierType(0); thisCarrying.setCarrierId(0); thisCommander.setCarrierInfo(thisCarrying); CommanderManager.getInstance().update(thisCommander); } else if (entry.getKey() >= ArmyConstants.BRIGADE * 1000) { // A Brigade is loaded final Brigade thisBrigade = BrigadeManager.getInstance().getByID(entry.getValue()); // Report capture of spy. newsSingle(thisBrigade.getNation(), NEWS_POLITICAL, "Our brigade '" + thisBrigade.getName() + "' was unloaded as the the baggage train '" + thisTrain.getName() + "' was scuttled by its crew."); LOGGER.info("Brigade [" + thisBrigade.getName() + "] of Nation [" + thisBrigade.getNation().getName() + "] was unloaded as the the baggage train '" + thisTrain.getName() + "' was scuttled by its crew."); for (final Battalion battalion : thisBrigade.getBattalions()) { // remove carrier info final CarrierInfo thisCarrying = new CarrierInfo(); thisCarrying.setCarrierType(0); thisCarrying.setCarrierId(0); battalion.setCarrierInfo(thisCarrying); BattalionManager.getInstance().update(battalion); } BrigadeManager.getInstance().update(thisBrigade); } } } } public Game getMyGame() { return game; } }
9864_6
package com.eaw1805.www.controllers.remote.hotspot; import com.eaw1805.data.constants.AdminCommandPoints; import com.eaw1805.data.constants.ArmyConstants; import com.eaw1805.data.constants.GoodConstants; import com.eaw1805.data.constants.NationConstants; import com.eaw1805.data.constants.OrderConstants; import com.eaw1805.data.constants.RegionConstants; import com.eaw1805.data.dto.collections.DataCollection; import com.eaw1805.data.dto.common.SectorDTO; import com.eaw1805.data.dto.converters.SectorConverter; import com.eaw1805.data.dto.web.ClientOrderDTO; import com.eaw1805.data.dto.web.OrderCostDTO; import com.eaw1805.data.dto.web.OrderDTO; import com.eaw1805.data.dto.web.army.ArmyTypeDTO; import com.eaw1805.data.dto.web.army.BattalionDTO; import com.eaw1805.data.dto.web.army.BrigadeDTO; import com.eaw1805.data.dto.web.economy.BaggageTrainDTO; import com.eaw1805.data.dto.web.fleet.ShipDTO; import com.eaw1805.data.dto.web.fleet.ShipTypeDTO; import com.eaw1805.data.model.Nation; import com.eaw1805.data.model.army.Brigade; import com.eaw1805.data.model.map.Sector; import com.eaw1805.www.controllers.remote.EmpireRpcServiceImpl; import com.eaw1805.www.shared.stores.GameStore; import com.eaw1805.www.shared.stores.util.calculators.CostCalculators; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; @SuppressWarnings("restriction") public class OrderApplyChangesProcessor extends AbstractChangesProcessor implements OrderConstants, GoodConstants { /** * The orders and the corresponding costs. */ private transient final Map<Integer, List<ClientOrderDTO>> clientOrders; private transient List<OrderDTO> orders = new ArrayList<OrderDTO>(); private transient final Map<Integer, ArmyTypeDTO> armyTypes = new HashMap<Integer, ArmyTypeDTO>(); private transient final Map<Integer, ShipTypeDTO> shipTypes = new HashMap<Integer, ShipTypeDTO>(); private transient final EmpireRpcServiceImpl service; private transient final DataCollection prodAndNatSites; /** * Default constructor. * * @param thisGame the game of the order. * @param thisNation the owner of the order. * @param thisTurn the turn of the order. */ public OrderApplyChangesProcessor(final int scenarioId, final int thisGame, final int thisNation, final int thisTurn, final EmpireRpcServiceImpl empireRpcServiceImpl) { super(scenarioId, thisGame, thisNation, thisTurn); service = empireRpcServiceImpl; for (ArmyTypeDTO armyTypeDTO : service.getArmyTypes(getScenarioId(), getNationId())) { armyTypes.put(armyTypeDTO.getIntId(), armyTypeDTO); } for (ShipTypeDTO shipTypeDTO : service.getShipTypes(getScenarioId(), getNationId())) { shipTypes.put(shipTypeDTO.getIntId(), shipTypeDTO); } prodAndNatSites = service.getNaturalResAndProdSites(getScenarioId()); clientOrders = new TreeMap<Integer, List<ClientOrderDTO>>(); } @SuppressWarnings({"unchecked"}) public void addData(final Collection<?> dbData, final Collection<?> chOrders) { orders = (List<OrderDTO>) chOrders; } public void addData(final Map<?, ?> dbData, final Map<?, ?> chData) { // do nothing } public Map<Integer, List<ClientOrderDTO>> processChanges() { for (final OrderDTO order : orders) { OrderCostDTO orderCost = new OrderCostDTO(); int regionId = 1; String name = ""; String comment = ""; final int[] ids = new int[9]; for (int i = 0; i < 9; i++) { ids[i] = 0; } switch (order.getType()) { case ORDER_B_BATT: { // Double costs custom game option final int doubleCosts = (GameStore.getInstance().isDoubleCostsArmy()) ? 2 : 1; final Sector sector = service.getSectorManager().getByID(Integer.parseInt(order.getParameter1())); final int sphere = getSphere(sector, service.nationManager.getByID(getNationId())); final int multiplier = doubleCosts * sphere; final BrigadeDTO brig = createBrigadeFromOrder(order); orderCost = CostCalculators.getBrigadeCost(brig, multiplier, sphere); name = order.getParameter9(); ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = brig.getBrigadeId(); regionId = brig.getRegionId(); break; } case ORDER_ADDTO_BRIGADE: ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); ids[2] = Integer.parseInt(order.getParameter3()); break; case ORDER_ADDTO_ARMY: case ORDER_ADDTO_CORP: case ORDER_ADDTO_FLT: ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); break; case ORDER_HIRE_COM: orderCost.setNumericCost(GOOD_AP, Integer.parseInt(order.getTemp1())); ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); break; case ORDER_ARMY_COM: name = order.getTemp1() + "-" + order.getParameter2(); ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); break; case ORDER_CORP_COM: name = order.getTemp1() + "-" + order.getParameter2(); ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); break; case ORDER_LEAVE_COM: ids[0] = Integer.parseInt(order.getParameter2()); ids[1] = 0; break; case ORDER_DISS_COM: orderCost.setNumericCost(GOOD_AP, Integer.parseInt(order.getTemp1())); ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); break; case ORDER_B_ARMY: case ORDER_B_FLT: orderCost = CostCalculators.getFormFederationCost(order.getType()); name = order.getParameter2(); ids[0] = Integer.parseInt(order.getParameter1()); break; case ORDER_B_CORP: orderCost = CostCalculators.getFormFederationCost(order.getType()); name = order.getParameter3(); ids[0] = Integer.parseInt(order.getParameter1()); break; case ORDER_ADD_BATT: { final Brigade brigade = service.getBrigadeManager().getByID(Integer.parseInt(order.getParameter1())); final Sector sector = service.getSectorManager().getByPosition(brigade.getPosition()); final int multiplier = getSphere(sector, service.getNationManager().getByID(getNationId())); orderCost = CostCalculators.getArmyTypeCost(getArmyTypeById(Integer.parseInt(order.getParameter2())), multiplier); ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); ids[2] = Integer.parseInt(order.getParameter3()); regionId = Integer.parseInt(order.getTemp1()); break; } case ORDER_B_BTRAIN: orderCost = CostCalculators.getBaggageTrainCost(); ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); regionId = Integer.parseInt(order.getTemp1()); break; case ORDER_R_BTRAIN: orderCost = CostCalculators.getBaggageTrainRepairCost(100 - Integer.parseInt(order.getParameter3())); ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); regionId = Integer.parseInt(order.getTemp1()); break; case ORDER_B_PRODS: ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); SectorDTO sectorDTO = SectorConverter.convert(service.getSectorManager().getByID(ids[0])); regionId = sectorDTO.getRegionId(); orderCost = CostCalculators.getProductionSiteCost(regionId, prodAndNatSites.getProdSite(Integer.parseInt(order.getParameter2())), false); break; case ORDER_D_PRODS: ids[0] = Integer.parseInt(order.getParameter1()); sectorDTO = SectorConverter.convert(service.getSectorManager().getByID(ids[0])); regionId = sectorDTO.getRegionId(); orderCost = CostCalculators.getProductionSiteCost(regionId, null, true); break; case ORDER_B_SHIP: ShipDTO ship = createShipFromOrder(order); orderCost = CostCalculators.getShipCost(ship); name = order.getParameter3(); ids[0] = Integer.parseInt(order.getTemp1()); ids[1] = Integer.parseInt(order.getParameter1()); ids[2] = Integer.parseInt(order.getParameter2()); regionId = ship.getRegionId(); break; case ORDER_R_FLT: final String[] costValues = order.getTemp2().split("!"); for (String costValue : costValues) { final String[] keyVal = costValue.split(":"); orderCost.setNumericCost(Integer.parseInt(keyVal[0]), Integer.parseInt(keyVal[1])); } ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); ids[2] = Integer.parseInt(order.getParameter3()); ids[3] = Integer.parseInt(order.getParameter4()); comment = order.getTemp2(); regionId = ids[2]; break; case ORDER_R_SHP: ship = service.getShipById(getScenarioId(), Integer.parseInt(order.getParameter1())); ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); ids[2] = Integer.parseInt(order.getParameter3()); ids[3] = Integer.parseInt(order.getParameter4()); orderCost = CostCalculators.getShipRepairCost(ship.getCondition(), ship); regionId = Integer.parseInt(order.getTemp1()); break; case ORDER_D_ARMY: case ORDER_D_BATT: case ORDER_D_BRIG: case ORDER_D_CORP: case ORDER_D_FLT: name = order.getTemp1(); ids[0] = Integer.parseInt(order.getParameter1()); break; case ORDER_FM_ARMY: ids[0] = Integer.parseInt(order.getParameter1()); break; case ORDER_FM_BRIG: ids[0] = Integer.parseInt(order.getParameter1()); break; case ORDER_FM_CORP: ids[0] = Integer.parseInt(order.getParameter1()); break; case ORDER_HOVER_SEC: case ORDER_HOVER_SHIP: ids[0] = Integer.parseInt(order.getParameter1()); orderCost = CostCalculators.getHandOverCost(order.getType(), Integer.parseInt(order.getTemp1())); break; case ORDER_INC_EXP: case ORDER_INC_EXP_CORPS: case ORDER_INC_EXP_ARMY: if (order.getTemp2() != null && !order.getTemp2().isEmpty()) { final String[] expCostValues = order.getTemp2().split("!"); for (String costValue : expCostValues) { final String[] keyVal = costValue.split(":"); orderCost.setNumericCost(Integer.parseInt(keyVal[0]), Integer.parseInt(keyVal[1])); } } ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); ids[2] = Integer.parseInt(order.getParameter3()); regionId = ids[2]; break; case ORDER_INC_HEADCNT: case ORDER_INC_HEADCNT_CORPS: case ORDER_INC_HEADCNT_ARMY: if (order.getTemp2() != null && !order.getTemp2().isEmpty()) { final String[] upHeadCostValues = order.getTemp2().split("!"); for (String costValue : upHeadCostValues) { final String[] keyVal = costValue.split(":"); orderCost.setNumericCost(Integer.parseInt(keyVal[0]), Integer.parseInt(keyVal[1])); } } ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); ids[2] = Integer.parseInt(order.getParameter3()); regionId = ids[2]; break; case ORDER_INC_POP: { ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); regionId = ids[1]; sectorDTO = SectorConverter.convert(service.getSectorManager().getByID(ids[0])); orderCost = CostCalculators.getIncDecPopCost(sectorDTO, true); break; } case ORDER_DEC_POP: { ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); regionId = ids[1]; final SectorDTO sector = SectorConverter.convert(service.getSectorManager().getByID(ids[0])); orderCost = CostCalculators.getIncDecPopCost(sector, false); break; } case ORDER_M_UNIT: orderCost = CostCalculators.getMovementCost(Integer.parseInt(order.getParameter5())); ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); ids[2] = Integer.parseInt(order.getParameter5()); break; case ORDER_MRG_BATT: ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); break; case ORDER_TAXATION: orderCost = CostCalculators.getTaxationCost(Integer.parseInt(order.getTemp3()), Integer.parseInt(order.getTemp4()), Integer.parseInt(order.getTemp1()), Integer.parseInt(order.getTemp2())); break; case ORDER_EXCHF: case ORDER_EXCHS: orderCost.setNumericCost(Integer.parseInt(order.getParameter5()), Integer.parseInt(order.getParameter6())); orderCost.setNumericCost(1, Integer.parseInt(order.getTemp1())); if (Integer.parseInt(order.getParameter1()) == ArmyConstants.TRADECITY || Integer.parseInt(order.getParameter3()) == ArmyConstants.TRADECITY) { orderCost.setNumericCost(GOOD_AP, AdminCommandPoints.P_ADM.get(order.getType())); } ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); ids[2] = Integer.parseInt(order.getParameter3()); ids[3] = Integer.parseInt(order.getParameter4()); ids[4] = Integer.parseInt(order.getParameter5()); ids[5] = Integer.parseInt(order.getParameter6()); regionId = Integer.parseInt(order.getParameter9()); break; case ORDER_LOAD_TROOPSF: case ORDER_LOAD_TROOPSS: if (order.getTemp3() != null && !order.getTemp3().isEmpty()) {//recover cp cost orderCost.setNumericCost(GOOD_CP, Integer.parseInt(order.getTemp3())); } ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); ids[2] = Integer.parseInt(order.getParameter3()); ids[3] = Integer.parseInt(order.getParameter4()); ids[4] = Integer.parseInt(order.getParameter5()); ids[5] = Integer.parseInt(order.getParameter6()); break; case ORDER_UNLOAD_TROOPSF: case ORDER_UNLOAD_TROOPSS: if (order.getTemp3() != null && !order.getTemp3().isEmpty()) {//recover cp cost orderCost.setNumericCost(GOOD_CP, Integer.parseInt(order.getTemp3())); } ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); ids[2] = Integer.parseInt(order.getParameter3()); ids[3] = Integer.parseInt(order.getParameter4()); ids[4] = Integer.parseInt(order.getParameter5()); ids[5] = Integer.parseInt(order.getTemp1()); ids[6] = Integer.parseInt(order.getTemp2()); break; case ORDER_REN_SHIP: case ORDER_REN_BRIG: case ORDER_REN_COMM: case ORDER_REN_ARMY: case ORDER_REN_CORP: case ORDER_REN_FLT: case ORDER_REN_BARRACK: case ORDER_REN_BTRAIN: ids[0] = Integer.parseInt(order.getParameter1()); name = order.getParameter2(); break; case ORDER_SCUTTLE_BTRAIN: ids[0] = Integer.parseInt(order.getParameter1()); final BaggageTrainDTO scuttledTrain = service.getBaggageTrainById(getScenarioId(), ids[0]); if (scuttledTrain != null) { orderCost = CostCalculators.getScuttleBaggageTrainCost(scuttledTrain.getCondition()); } break; case ORDER_SCUTTLE_SHIP: ids[0] = Integer.parseInt(order.getParameter1()); final ShipDTO scuttledShip = service.getShipById(getScenarioId(), ids[0]); if (scuttledShip != null) { orderCost = CostCalculators.getScuttleShipCost(scuttledShip); } break; case ORDER_POLITICS: ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); ids[2] = Integer.parseInt(order.getParameter3()); break; default: // do nothing } addNewOrder(order.getType(), orderCost, regionId, name, ids, order.getPosition(), comment); } return clientOrders; } /** * Identify if sector is a home region, inside sphere of influence, or outside of the receiving nation. * * @param sector the sector to examine. * @param receiver the receiving nation. * @return 1 if home region, 2 if in sphere of influence, 3 if outside. */ protected final int getSphere(final Sector sector, final Nation receiver) { final char thisNationCodeLower = String.valueOf(receiver.getCode()).toLowerCase().charAt(0); final char thisSectorCodeLower = String.valueOf(sector.getPoliticalSphere()).toLowerCase().charAt(0); int sphere = 1; // Τα χ2 και x3 ισχύουν μόνο για τα Ευρωπαικά αν χτίζονται στο SoI ή εκτός SoI if (sector.getPosition().getRegion().getId() != RegionConstants.EUROPE) { return 1; } // Check if this is not home region if (thisNationCodeLower != thisSectorCodeLower) { sphere = 2; // Check if this is outside sphere of influence if (receiver.getSphereOfInfluence().toLowerCase().indexOf(thisSectorCodeLower) < 0) { sphere = 3; } } return sphere; } // /** // * Identify if sector is a home region, inside sphere of influence, or outside of the receiving nation. // * // * @param sector the sector to examine. // * @param receiver the receiving nation. // * @return 1 if home region, 2 if in sphere of influence, 3 if outside. // */ // protected int getSphere(final Sector sector, final Nation receiver) { // final char thisNationCodeLower = String.valueOf(receiver.getCode()).toLowerCase().charAt(0); // final char thisSectorCodeLower = String.valueOf(sector.getPoliticalSphere()).toLowerCase().charAt(0); // int sphere = 1; // // if (sector.getPosition().getRegion().getId() != RegionConstants.EUROPE) { // return sphere; // } // // // Check if this is not home region // if (thisNationCodeLower != thisSectorCodeLower) { // sphere = 2; // // final char thisNationCode = String.valueOf(receiver.getCode()).toLowerCase().charAt(0); // // // Check if this is outside sphere of influence // if (sector.getNation().getSphereOfInfluence().indexOf(thisNationCode) < 0) { // sphere = 3; // } // } // // return sphere; // } /** * Method that adds a new order to our order Map * * @param typeId The type of the order we want to add. * @param orderCost The calculated cost of the order. * @param regionId the region of the warehouse. * @param name the name of the order. * @param identifiers the id of the order. * @param position The position of the order. * @param comment the comment of the order. * @return 0 if there are no available funds 1 if there are */ private int addNewOrder(final int typeId, final OrderCostDTO orderCost, final int regionId, final String name, final int[] identifiers, final int position, final String comment) { int priority = position; if (clientOrders.get(typeId) == null) { clientOrders.put(typeId, new ArrayList<ClientOrderDTO>()); } else { priority = clientOrders.get(typeId).size(); } if (position == 0) { priority = clientOrders.get(typeId).size(); } final ClientOrderDTO order = new ClientOrderDTO(); order.setOrderTypeId(typeId); order.setPriority(priority); order.setCosts(orderCost); order.setName(name); order.setComment(comment); for (int index = 0; index < identifiers.length; index++) { order.setIdentifier(index, identifiers[index]); } order.setRegionId(regionId); clientOrders.get(typeId).add(order); return 1; } /** * Creates new brigade from the order. * * @param order the order to use. * @return the new brigade object. */ private BrigadeDTO createBrigadeFromOrder(final OrderDTO order) { final BrigadeDTO newBrigade = new BrigadeDTO(); newBrigade.setNationId(getNationId()); newBrigade.setName(order.getParameter9()); try { newBrigade.setBrigadeId(Integer.parseInt(order.getTemp1())); } catch (Exception ex) { if (clientOrders.get(ORDER_ADD_BATT) == null) { newBrigade.setBrigadeId(0); } else { newBrigade.setBrigadeId(clientOrders.get(ORDER_ADD_BATT).size()); } } newBrigade.setBattalions(new ArrayList<BattalionDTO>()); final BattalionDTO battalionDto1 = getBattalionByArmyTypeId(order.getParameter2(), 1); final BattalionDTO battalionDto2 = getBattalionByArmyTypeId(order.getParameter3(), 2); final BattalionDTO battalionDto3 = getBattalionByArmyTypeId(order.getParameter4(), 3); final BattalionDTO battalionDto4 = getBattalionByArmyTypeId(order.getParameter5(), 4); final BattalionDTO battalionDto5 = getBattalionByArmyTypeId(order.getParameter6(), 5); final BattalionDTO battalionDto6 = getBattalionByArmyTypeId(order.getParameter7(), 6); final BattalionDTO battalionDto7 = getBattalionByArmyTypeId(order.getParameter8(), 7); newBrigade.getBattalions().add(battalionDto1); newBrigade.getBattalions().add(battalionDto2); newBrigade.getBattalions().add(battalionDto3); newBrigade.getBattalions().add(battalionDto4); newBrigade.getBattalions().add(battalionDto5); newBrigade.getBattalions().add(battalionDto6); newBrigade.getBattalions().add(battalionDto7); final Sector sector = service.getSectorManager().getByID(Integer.parseInt(order.getParameter1())); newBrigade.setRegionId(sector.getPosition().getRegion().getId()); newBrigade.setX(sector.getPosition().getX()); newBrigade.setY(sector.getPosition().getY()); return newBrigade; } /** * Create new battalion. * * @param armyTypeID the battalion type. * @param order the order ID. * @return the new battalio dto. */ private BattalionDTO getBattalionByArmyTypeId(final String armyTypeID, final int order) { final ArmyTypeDTO armyTypeDto = getArmyTypeById(Integer.parseInt(armyTypeID)); final BattalionDTO newBattalion = new BattalionDTO(); newBattalion.setEmpireArmyType(armyTypeDto); int headcount = 800; if (newBattalion.getEmpireArmyType().getNationId() == NationConstants.NATION_MOROCCO || newBattalion.getEmpireArmyType().getNationId() == NationConstants.NATION_OTTOMAN || newBattalion.getEmpireArmyType().getNationId() == NationConstants.NATION_EGYPT) { headcount = 1000; } newBattalion.setExperience(1); newBattalion.setHeadcount(headcount); newBattalion.setId(-1); newBattalion.setOrder(order); return newBattalion; } /** * Creates new ship from the order. * * @param order the order describing the new ship. * @return the new ship dto. */ public ShipDTO createShipFromOrder(final OrderDTO order) { final ShipDTO newShip = new ShipDTO(); newShip.setNationId(getNationId()); newShip.setName(order.getParameter3()); newShip.setId(Integer.parseInt(order.getTemp1())); final ShipTypeDTO shipTypeDTO = getShipTypeId(Integer.parseInt(order.getParameter2())); newShip.setTypeId(shipTypeDTO.getIndPt()); newShip.setType(shipTypeDTO); final Sector sector = service.getSectorManager().getByID(Integer.parseInt(order.getParameter1())); newShip.setRegionId(sector.getPosition().getRegion().getId()); newShip.setX(sector.getPosition().getX()); newShip.setY(sector.getPosition().getY()); return newShip; } /** * @param shipTypeID the type of the ship. * @return the new ship type dto. */ private ShipTypeDTO getShipTypeId(final int shipTypeID) { final ShipTypeDTO shipTypeDto = new ShipTypeDTO(); if (shipTypes.containsKey(shipTypeID)) { return shipTypes.get(shipTypeID); } return shipTypeDto; } public ArmyTypeDTO getArmyTypeById(final int armyTypeId) { final ArmyTypeDTO armyTypeDto = new ArmyTypeDTO(); if (armyTypes.containsKey(armyTypeId)) { return armyTypes.get(armyTypeId); } return armyTypeDto; } }
EaW1805/www
src/main/java/com/eaw1805/www/controllers/remote/hotspot/OrderApplyChangesProcessor.java
7,072
// Τα χ2 και x3 ισχύουν μόνο για τα Ευρωπαικά αν χτίζονται στο SoI ή εκτός SoI
line_comment
el
package com.eaw1805.www.controllers.remote.hotspot; import com.eaw1805.data.constants.AdminCommandPoints; import com.eaw1805.data.constants.ArmyConstants; import com.eaw1805.data.constants.GoodConstants; import com.eaw1805.data.constants.NationConstants; import com.eaw1805.data.constants.OrderConstants; import com.eaw1805.data.constants.RegionConstants; import com.eaw1805.data.dto.collections.DataCollection; import com.eaw1805.data.dto.common.SectorDTO; import com.eaw1805.data.dto.converters.SectorConverter; import com.eaw1805.data.dto.web.ClientOrderDTO; import com.eaw1805.data.dto.web.OrderCostDTO; import com.eaw1805.data.dto.web.OrderDTO; import com.eaw1805.data.dto.web.army.ArmyTypeDTO; import com.eaw1805.data.dto.web.army.BattalionDTO; import com.eaw1805.data.dto.web.army.BrigadeDTO; import com.eaw1805.data.dto.web.economy.BaggageTrainDTO; import com.eaw1805.data.dto.web.fleet.ShipDTO; import com.eaw1805.data.dto.web.fleet.ShipTypeDTO; import com.eaw1805.data.model.Nation; import com.eaw1805.data.model.army.Brigade; import com.eaw1805.data.model.map.Sector; import com.eaw1805.www.controllers.remote.EmpireRpcServiceImpl; import com.eaw1805.www.shared.stores.GameStore; import com.eaw1805.www.shared.stores.util.calculators.CostCalculators; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; @SuppressWarnings("restriction") public class OrderApplyChangesProcessor extends AbstractChangesProcessor implements OrderConstants, GoodConstants { /** * The orders and the corresponding costs. */ private transient final Map<Integer, List<ClientOrderDTO>> clientOrders; private transient List<OrderDTO> orders = new ArrayList<OrderDTO>(); private transient final Map<Integer, ArmyTypeDTO> armyTypes = new HashMap<Integer, ArmyTypeDTO>(); private transient final Map<Integer, ShipTypeDTO> shipTypes = new HashMap<Integer, ShipTypeDTO>(); private transient final EmpireRpcServiceImpl service; private transient final DataCollection prodAndNatSites; /** * Default constructor. * * @param thisGame the game of the order. * @param thisNation the owner of the order. * @param thisTurn the turn of the order. */ public OrderApplyChangesProcessor(final int scenarioId, final int thisGame, final int thisNation, final int thisTurn, final EmpireRpcServiceImpl empireRpcServiceImpl) { super(scenarioId, thisGame, thisNation, thisTurn); service = empireRpcServiceImpl; for (ArmyTypeDTO armyTypeDTO : service.getArmyTypes(getScenarioId(), getNationId())) { armyTypes.put(armyTypeDTO.getIntId(), armyTypeDTO); } for (ShipTypeDTO shipTypeDTO : service.getShipTypes(getScenarioId(), getNationId())) { shipTypes.put(shipTypeDTO.getIntId(), shipTypeDTO); } prodAndNatSites = service.getNaturalResAndProdSites(getScenarioId()); clientOrders = new TreeMap<Integer, List<ClientOrderDTO>>(); } @SuppressWarnings({"unchecked"}) public void addData(final Collection<?> dbData, final Collection<?> chOrders) { orders = (List<OrderDTO>) chOrders; } public void addData(final Map<?, ?> dbData, final Map<?, ?> chData) { // do nothing } public Map<Integer, List<ClientOrderDTO>> processChanges() { for (final OrderDTO order : orders) { OrderCostDTO orderCost = new OrderCostDTO(); int regionId = 1; String name = ""; String comment = ""; final int[] ids = new int[9]; for (int i = 0; i < 9; i++) { ids[i] = 0; } switch (order.getType()) { case ORDER_B_BATT: { // Double costs custom game option final int doubleCosts = (GameStore.getInstance().isDoubleCostsArmy()) ? 2 : 1; final Sector sector = service.getSectorManager().getByID(Integer.parseInt(order.getParameter1())); final int sphere = getSphere(sector, service.nationManager.getByID(getNationId())); final int multiplier = doubleCosts * sphere; final BrigadeDTO brig = createBrigadeFromOrder(order); orderCost = CostCalculators.getBrigadeCost(brig, multiplier, sphere); name = order.getParameter9(); ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = brig.getBrigadeId(); regionId = brig.getRegionId(); break; } case ORDER_ADDTO_BRIGADE: ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); ids[2] = Integer.parseInt(order.getParameter3()); break; case ORDER_ADDTO_ARMY: case ORDER_ADDTO_CORP: case ORDER_ADDTO_FLT: ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); break; case ORDER_HIRE_COM: orderCost.setNumericCost(GOOD_AP, Integer.parseInt(order.getTemp1())); ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); break; case ORDER_ARMY_COM: name = order.getTemp1() + "-" + order.getParameter2(); ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); break; case ORDER_CORP_COM: name = order.getTemp1() + "-" + order.getParameter2(); ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); break; case ORDER_LEAVE_COM: ids[0] = Integer.parseInt(order.getParameter2()); ids[1] = 0; break; case ORDER_DISS_COM: orderCost.setNumericCost(GOOD_AP, Integer.parseInt(order.getTemp1())); ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); break; case ORDER_B_ARMY: case ORDER_B_FLT: orderCost = CostCalculators.getFormFederationCost(order.getType()); name = order.getParameter2(); ids[0] = Integer.parseInt(order.getParameter1()); break; case ORDER_B_CORP: orderCost = CostCalculators.getFormFederationCost(order.getType()); name = order.getParameter3(); ids[0] = Integer.parseInt(order.getParameter1()); break; case ORDER_ADD_BATT: { final Brigade brigade = service.getBrigadeManager().getByID(Integer.parseInt(order.getParameter1())); final Sector sector = service.getSectorManager().getByPosition(brigade.getPosition()); final int multiplier = getSphere(sector, service.getNationManager().getByID(getNationId())); orderCost = CostCalculators.getArmyTypeCost(getArmyTypeById(Integer.parseInt(order.getParameter2())), multiplier); ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); ids[2] = Integer.parseInt(order.getParameter3()); regionId = Integer.parseInt(order.getTemp1()); break; } case ORDER_B_BTRAIN: orderCost = CostCalculators.getBaggageTrainCost(); ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); regionId = Integer.parseInt(order.getTemp1()); break; case ORDER_R_BTRAIN: orderCost = CostCalculators.getBaggageTrainRepairCost(100 - Integer.parseInt(order.getParameter3())); ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); regionId = Integer.parseInt(order.getTemp1()); break; case ORDER_B_PRODS: ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); SectorDTO sectorDTO = SectorConverter.convert(service.getSectorManager().getByID(ids[0])); regionId = sectorDTO.getRegionId(); orderCost = CostCalculators.getProductionSiteCost(regionId, prodAndNatSites.getProdSite(Integer.parseInt(order.getParameter2())), false); break; case ORDER_D_PRODS: ids[0] = Integer.parseInt(order.getParameter1()); sectorDTO = SectorConverter.convert(service.getSectorManager().getByID(ids[0])); regionId = sectorDTO.getRegionId(); orderCost = CostCalculators.getProductionSiteCost(regionId, null, true); break; case ORDER_B_SHIP: ShipDTO ship = createShipFromOrder(order); orderCost = CostCalculators.getShipCost(ship); name = order.getParameter3(); ids[0] = Integer.parseInt(order.getTemp1()); ids[1] = Integer.parseInt(order.getParameter1()); ids[2] = Integer.parseInt(order.getParameter2()); regionId = ship.getRegionId(); break; case ORDER_R_FLT: final String[] costValues = order.getTemp2().split("!"); for (String costValue : costValues) { final String[] keyVal = costValue.split(":"); orderCost.setNumericCost(Integer.parseInt(keyVal[0]), Integer.parseInt(keyVal[1])); } ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); ids[2] = Integer.parseInt(order.getParameter3()); ids[3] = Integer.parseInt(order.getParameter4()); comment = order.getTemp2(); regionId = ids[2]; break; case ORDER_R_SHP: ship = service.getShipById(getScenarioId(), Integer.parseInt(order.getParameter1())); ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); ids[2] = Integer.parseInt(order.getParameter3()); ids[3] = Integer.parseInt(order.getParameter4()); orderCost = CostCalculators.getShipRepairCost(ship.getCondition(), ship); regionId = Integer.parseInt(order.getTemp1()); break; case ORDER_D_ARMY: case ORDER_D_BATT: case ORDER_D_BRIG: case ORDER_D_CORP: case ORDER_D_FLT: name = order.getTemp1(); ids[0] = Integer.parseInt(order.getParameter1()); break; case ORDER_FM_ARMY: ids[0] = Integer.parseInt(order.getParameter1()); break; case ORDER_FM_BRIG: ids[0] = Integer.parseInt(order.getParameter1()); break; case ORDER_FM_CORP: ids[0] = Integer.parseInt(order.getParameter1()); break; case ORDER_HOVER_SEC: case ORDER_HOVER_SHIP: ids[0] = Integer.parseInt(order.getParameter1()); orderCost = CostCalculators.getHandOverCost(order.getType(), Integer.parseInt(order.getTemp1())); break; case ORDER_INC_EXP: case ORDER_INC_EXP_CORPS: case ORDER_INC_EXP_ARMY: if (order.getTemp2() != null && !order.getTemp2().isEmpty()) { final String[] expCostValues = order.getTemp2().split("!"); for (String costValue : expCostValues) { final String[] keyVal = costValue.split(":"); orderCost.setNumericCost(Integer.parseInt(keyVal[0]), Integer.parseInt(keyVal[1])); } } ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); ids[2] = Integer.parseInt(order.getParameter3()); regionId = ids[2]; break; case ORDER_INC_HEADCNT: case ORDER_INC_HEADCNT_CORPS: case ORDER_INC_HEADCNT_ARMY: if (order.getTemp2() != null && !order.getTemp2().isEmpty()) { final String[] upHeadCostValues = order.getTemp2().split("!"); for (String costValue : upHeadCostValues) { final String[] keyVal = costValue.split(":"); orderCost.setNumericCost(Integer.parseInt(keyVal[0]), Integer.parseInt(keyVal[1])); } } ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); ids[2] = Integer.parseInt(order.getParameter3()); regionId = ids[2]; break; case ORDER_INC_POP: { ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); regionId = ids[1]; sectorDTO = SectorConverter.convert(service.getSectorManager().getByID(ids[0])); orderCost = CostCalculators.getIncDecPopCost(sectorDTO, true); break; } case ORDER_DEC_POP: { ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); regionId = ids[1]; final SectorDTO sector = SectorConverter.convert(service.getSectorManager().getByID(ids[0])); orderCost = CostCalculators.getIncDecPopCost(sector, false); break; } case ORDER_M_UNIT: orderCost = CostCalculators.getMovementCost(Integer.parseInt(order.getParameter5())); ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); ids[2] = Integer.parseInt(order.getParameter5()); break; case ORDER_MRG_BATT: ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); break; case ORDER_TAXATION: orderCost = CostCalculators.getTaxationCost(Integer.parseInt(order.getTemp3()), Integer.parseInt(order.getTemp4()), Integer.parseInt(order.getTemp1()), Integer.parseInt(order.getTemp2())); break; case ORDER_EXCHF: case ORDER_EXCHS: orderCost.setNumericCost(Integer.parseInt(order.getParameter5()), Integer.parseInt(order.getParameter6())); orderCost.setNumericCost(1, Integer.parseInt(order.getTemp1())); if (Integer.parseInt(order.getParameter1()) == ArmyConstants.TRADECITY || Integer.parseInt(order.getParameter3()) == ArmyConstants.TRADECITY) { orderCost.setNumericCost(GOOD_AP, AdminCommandPoints.P_ADM.get(order.getType())); } ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); ids[2] = Integer.parseInt(order.getParameter3()); ids[3] = Integer.parseInt(order.getParameter4()); ids[4] = Integer.parseInt(order.getParameter5()); ids[5] = Integer.parseInt(order.getParameter6()); regionId = Integer.parseInt(order.getParameter9()); break; case ORDER_LOAD_TROOPSF: case ORDER_LOAD_TROOPSS: if (order.getTemp3() != null && !order.getTemp3().isEmpty()) {//recover cp cost orderCost.setNumericCost(GOOD_CP, Integer.parseInt(order.getTemp3())); } ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); ids[2] = Integer.parseInt(order.getParameter3()); ids[3] = Integer.parseInt(order.getParameter4()); ids[4] = Integer.parseInt(order.getParameter5()); ids[5] = Integer.parseInt(order.getParameter6()); break; case ORDER_UNLOAD_TROOPSF: case ORDER_UNLOAD_TROOPSS: if (order.getTemp3() != null && !order.getTemp3().isEmpty()) {//recover cp cost orderCost.setNumericCost(GOOD_CP, Integer.parseInt(order.getTemp3())); } ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); ids[2] = Integer.parseInt(order.getParameter3()); ids[3] = Integer.parseInt(order.getParameter4()); ids[4] = Integer.parseInt(order.getParameter5()); ids[5] = Integer.parseInt(order.getTemp1()); ids[6] = Integer.parseInt(order.getTemp2()); break; case ORDER_REN_SHIP: case ORDER_REN_BRIG: case ORDER_REN_COMM: case ORDER_REN_ARMY: case ORDER_REN_CORP: case ORDER_REN_FLT: case ORDER_REN_BARRACK: case ORDER_REN_BTRAIN: ids[0] = Integer.parseInt(order.getParameter1()); name = order.getParameter2(); break; case ORDER_SCUTTLE_BTRAIN: ids[0] = Integer.parseInt(order.getParameter1()); final BaggageTrainDTO scuttledTrain = service.getBaggageTrainById(getScenarioId(), ids[0]); if (scuttledTrain != null) { orderCost = CostCalculators.getScuttleBaggageTrainCost(scuttledTrain.getCondition()); } break; case ORDER_SCUTTLE_SHIP: ids[0] = Integer.parseInt(order.getParameter1()); final ShipDTO scuttledShip = service.getShipById(getScenarioId(), ids[0]); if (scuttledShip != null) { orderCost = CostCalculators.getScuttleShipCost(scuttledShip); } break; case ORDER_POLITICS: ids[0] = Integer.parseInt(order.getParameter1()); ids[1] = Integer.parseInt(order.getParameter2()); ids[2] = Integer.parseInt(order.getParameter3()); break; default: // do nothing } addNewOrder(order.getType(), orderCost, regionId, name, ids, order.getPosition(), comment); } return clientOrders; } /** * Identify if sector is a home region, inside sphere of influence, or outside of the receiving nation. * * @param sector the sector to examine. * @param receiver the receiving nation. * @return 1 if home region, 2 if in sphere of influence, 3 if outside. */ protected final int getSphere(final Sector sector, final Nation receiver) { final char thisNationCodeLower = String.valueOf(receiver.getCode()).toLowerCase().charAt(0); final char thisSectorCodeLower = String.valueOf(sector.getPoliticalSphere()).toLowerCase().charAt(0); int sphere = 1; // Τα χ2<SUF> if (sector.getPosition().getRegion().getId() != RegionConstants.EUROPE) { return 1; } // Check if this is not home region if (thisNationCodeLower != thisSectorCodeLower) { sphere = 2; // Check if this is outside sphere of influence if (receiver.getSphereOfInfluence().toLowerCase().indexOf(thisSectorCodeLower) < 0) { sphere = 3; } } return sphere; } // /** // * Identify if sector is a home region, inside sphere of influence, or outside of the receiving nation. // * // * @param sector the sector to examine. // * @param receiver the receiving nation. // * @return 1 if home region, 2 if in sphere of influence, 3 if outside. // */ // protected int getSphere(final Sector sector, final Nation receiver) { // final char thisNationCodeLower = String.valueOf(receiver.getCode()).toLowerCase().charAt(0); // final char thisSectorCodeLower = String.valueOf(sector.getPoliticalSphere()).toLowerCase().charAt(0); // int sphere = 1; // // if (sector.getPosition().getRegion().getId() != RegionConstants.EUROPE) { // return sphere; // } // // // Check if this is not home region // if (thisNationCodeLower != thisSectorCodeLower) { // sphere = 2; // // final char thisNationCode = String.valueOf(receiver.getCode()).toLowerCase().charAt(0); // // // Check if this is outside sphere of influence // if (sector.getNation().getSphereOfInfluence().indexOf(thisNationCode) < 0) { // sphere = 3; // } // } // // return sphere; // } /** * Method that adds a new order to our order Map * * @param typeId The type of the order we want to add. * @param orderCost The calculated cost of the order. * @param regionId the region of the warehouse. * @param name the name of the order. * @param identifiers the id of the order. * @param position The position of the order. * @param comment the comment of the order. * @return 0 if there are no available funds 1 if there are */ private int addNewOrder(final int typeId, final OrderCostDTO orderCost, final int regionId, final String name, final int[] identifiers, final int position, final String comment) { int priority = position; if (clientOrders.get(typeId) == null) { clientOrders.put(typeId, new ArrayList<ClientOrderDTO>()); } else { priority = clientOrders.get(typeId).size(); } if (position == 0) { priority = clientOrders.get(typeId).size(); } final ClientOrderDTO order = new ClientOrderDTO(); order.setOrderTypeId(typeId); order.setPriority(priority); order.setCosts(orderCost); order.setName(name); order.setComment(comment); for (int index = 0; index < identifiers.length; index++) { order.setIdentifier(index, identifiers[index]); } order.setRegionId(regionId); clientOrders.get(typeId).add(order); return 1; } /** * Creates new brigade from the order. * * @param order the order to use. * @return the new brigade object. */ private BrigadeDTO createBrigadeFromOrder(final OrderDTO order) { final BrigadeDTO newBrigade = new BrigadeDTO(); newBrigade.setNationId(getNationId()); newBrigade.setName(order.getParameter9()); try { newBrigade.setBrigadeId(Integer.parseInt(order.getTemp1())); } catch (Exception ex) { if (clientOrders.get(ORDER_ADD_BATT) == null) { newBrigade.setBrigadeId(0); } else { newBrigade.setBrigadeId(clientOrders.get(ORDER_ADD_BATT).size()); } } newBrigade.setBattalions(new ArrayList<BattalionDTO>()); final BattalionDTO battalionDto1 = getBattalionByArmyTypeId(order.getParameter2(), 1); final BattalionDTO battalionDto2 = getBattalionByArmyTypeId(order.getParameter3(), 2); final BattalionDTO battalionDto3 = getBattalionByArmyTypeId(order.getParameter4(), 3); final BattalionDTO battalionDto4 = getBattalionByArmyTypeId(order.getParameter5(), 4); final BattalionDTO battalionDto5 = getBattalionByArmyTypeId(order.getParameter6(), 5); final BattalionDTO battalionDto6 = getBattalionByArmyTypeId(order.getParameter7(), 6); final BattalionDTO battalionDto7 = getBattalionByArmyTypeId(order.getParameter8(), 7); newBrigade.getBattalions().add(battalionDto1); newBrigade.getBattalions().add(battalionDto2); newBrigade.getBattalions().add(battalionDto3); newBrigade.getBattalions().add(battalionDto4); newBrigade.getBattalions().add(battalionDto5); newBrigade.getBattalions().add(battalionDto6); newBrigade.getBattalions().add(battalionDto7); final Sector sector = service.getSectorManager().getByID(Integer.parseInt(order.getParameter1())); newBrigade.setRegionId(sector.getPosition().getRegion().getId()); newBrigade.setX(sector.getPosition().getX()); newBrigade.setY(sector.getPosition().getY()); return newBrigade; } /** * Create new battalion. * * @param armyTypeID the battalion type. * @param order the order ID. * @return the new battalio dto. */ private BattalionDTO getBattalionByArmyTypeId(final String armyTypeID, final int order) { final ArmyTypeDTO armyTypeDto = getArmyTypeById(Integer.parseInt(armyTypeID)); final BattalionDTO newBattalion = new BattalionDTO(); newBattalion.setEmpireArmyType(armyTypeDto); int headcount = 800; if (newBattalion.getEmpireArmyType().getNationId() == NationConstants.NATION_MOROCCO || newBattalion.getEmpireArmyType().getNationId() == NationConstants.NATION_OTTOMAN || newBattalion.getEmpireArmyType().getNationId() == NationConstants.NATION_EGYPT) { headcount = 1000; } newBattalion.setExperience(1); newBattalion.setHeadcount(headcount); newBattalion.setId(-1); newBattalion.setOrder(order); return newBattalion; } /** * Creates new ship from the order. * * @param order the order describing the new ship. * @return the new ship dto. */ public ShipDTO createShipFromOrder(final OrderDTO order) { final ShipDTO newShip = new ShipDTO(); newShip.setNationId(getNationId()); newShip.setName(order.getParameter3()); newShip.setId(Integer.parseInt(order.getTemp1())); final ShipTypeDTO shipTypeDTO = getShipTypeId(Integer.parseInt(order.getParameter2())); newShip.setTypeId(shipTypeDTO.getIndPt()); newShip.setType(shipTypeDTO); final Sector sector = service.getSectorManager().getByID(Integer.parseInt(order.getParameter1())); newShip.setRegionId(sector.getPosition().getRegion().getId()); newShip.setX(sector.getPosition().getX()); newShip.setY(sector.getPosition().getY()); return newShip; } /** * @param shipTypeID the type of the ship. * @return the new ship type dto. */ private ShipTypeDTO getShipTypeId(final int shipTypeID) { final ShipTypeDTO shipTypeDto = new ShipTypeDTO(); if (shipTypes.containsKey(shipTypeID)) { return shipTypes.get(shipTypeID); } return shipTypeDto; } public ArmyTypeDTO getArmyTypeById(final int armyTypeId) { final ArmyTypeDTO armyTypeDto = new ArmyTypeDTO(); if (armyTypes.containsKey(armyTypeId)) { return armyTypes.get(armyTypeId); } return armyTypeDto; } }
865_8
package com.example.eshop3; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; //κάνω implements View.OnclickListener ένας άλλος τρόπος αντί να κάνω setOncliCkListener(new View.OnclickListner) σε εάν κουμπί public class menu_proionta extends Fragment implements View.OnClickListener{ //δημιουργώ 3 μεταβλητές τύπου Button Button B_insertPr, B_deletePr, B_editPr; public menu_proionta() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //δημιορυγώ το view κάνοντας inflate το αντίστοιχο fragment View view = inflater.inflate(R.layout.fragment_menu_proionta, container, false); //κάνω αντιστόιχηση τις μεταβλητές μου με τα ανάλογα button //χρησιμοποιόντας την findViewById //και ορίζω σε κάθε κουμπί την ιδιότητα setOnClickListener(this) ///δηλαδή τι θα γίνεται κάθε φορα που κάποιος πατάει κάποιο κουμπί B_insertPr = view.findViewById(R.id.insertButtonPr); B_insertPr.setOnClickListener(this); B_deletePr =view.findViewById(R.id.deleteButtonPr); B_deletePr.setOnClickListener(this); B_editPr =view.findViewById(R.id.editButtonPr); B_editPr.setOnClickListener(this); return view; } //η onClick παίρνει σα παράμετρο τη View που έχω δημιουργήσει και ανάλογα τα id των κουμπιών // που έχει η view πάει στο ανόλογο case. Μέσα στο case ανάλογα ποιο κουμπί έχει πατηθεί //ξεκινάει μια συναλλαγή και δημιουργεί το αντίστοιχο fragment και με addToBackStack μπορεί //κανείς να πηγαίνει πίσω και φυσικά στο τέλος commit. public void onClick(View v) { switch (v.getId()) { case R.id.insertButtonPr: MainActivity.fragmentManager.beginTransaction().replace(R.id.fragment_container, new InsertProion()).addToBackStack(null).commit(); break; case R.id.deleteButtonPr: MainActivity.fragmentManager.beginTransaction().replace(R.id.fragment_container, new DeleteProionta()).addToBackStack(null).commit(); break; case R.id.editButtonPr: MainActivity.fragmentManager.beginTransaction().replace(R.id.fragment_container, new UpdateProionta()).addToBackStack(null).commit(); break; } }}
EfthimisKele/E_Shop
app/src/main/java/com/example/eshop3/menu_proionta.java
928
//η onClick παίρνει σα παράμετρο τη View που έχω δημιουργήσει και ανάλογα τα id των κουμπιών
line_comment
el
package com.example.eshop3; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; //κάνω implements View.OnclickListener ένας άλλος τρόπος αντί να κάνω setOncliCkListener(new View.OnclickListner) σε εάν κουμπί public class menu_proionta extends Fragment implements View.OnClickListener{ //δημιουργώ 3 μεταβλητές τύπου Button Button B_insertPr, B_deletePr, B_editPr; public menu_proionta() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //δημιορυγώ το view κάνοντας inflate το αντίστοιχο fragment View view = inflater.inflate(R.layout.fragment_menu_proionta, container, false); //κάνω αντιστόιχηση τις μεταβλητές μου με τα ανάλογα button //χρησιμοποιόντας την findViewById //και ορίζω σε κάθε κουμπί την ιδιότητα setOnClickListener(this) ///δηλαδή τι θα γίνεται κάθε φορα που κάποιος πατάει κάποιο κουμπί B_insertPr = view.findViewById(R.id.insertButtonPr); B_insertPr.setOnClickListener(this); B_deletePr =view.findViewById(R.id.deleteButtonPr); B_deletePr.setOnClickListener(this); B_editPr =view.findViewById(R.id.editButtonPr); B_editPr.setOnClickListener(this); return view; } //η onClick<SUF> // που έχει η view πάει στο ανόλογο case. Μέσα στο case ανάλογα ποιο κουμπί έχει πατηθεί //ξεκινάει μια συναλλαγή και δημιουργεί το αντίστοιχο fragment και με addToBackStack μπορεί //κανείς να πηγαίνει πίσω και φυσικά στο τέλος commit. public void onClick(View v) { switch (v.getId()) { case R.id.insertButtonPr: MainActivity.fragmentManager.beginTransaction().replace(R.id.fragment_container, new InsertProion()).addToBackStack(null).commit(); break; case R.id.deleteButtonPr: MainActivity.fragmentManager.beginTransaction().replace(R.id.fragment_container, new DeleteProionta()).addToBackStack(null).commit(); break; case R.id.editButtonPr: MainActivity.fragmentManager.beginTransaction().replace(R.id.fragment_container, new UpdateProionta()).addToBackStack(null).commit(); break; } }}
16735_0
package gr.dit.hua.divorce.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.JdbcUserDetailsManager; import org.springframework.security.web.SecurityFilterChain; import javax.sql.DataSource; @Configuration @EnableWebSecurity public class SecurityConfig { @Autowired DataSource dataSource; @Bean public JdbcUserDetailsManager jdbcUserDetailsManager() throws Exception { JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager(); jdbcUserDetailsManager.setDataSource(dataSource); return jdbcUserDetailsManager; } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .cors().and().csrf().disable() .authorizeRequests() .requestMatchers("/").permitAll() .requestMatchers("/register").permitAll() .requestMatchers("/contact").permitAll() .requestMatchers("/more_information").permitAll() .requestMatchers("/help").permitAll() .requestMatchers("/member/**").hasRole("ADMIN") .requestMatchers("/my_divorces" ).hasAnyRole("LAWYER", "SPOUSE", "NOTARY") .requestMatchers("/divorce/deleteDivorce").hasRole("LAWYER") .requestMatchers("/divorce/getDivorces").hasRole("ADMIN") .requestMatchers("/divorce/saveDivorce").hasRole("LAWYER") .requestMatchers("/divorce/approveDivorce").hasRole("NOTARY") .requestMatchers("/cdp").hasRole("LAWYER") .requestMatchers("/member_names").hasRole("LAWYER") .requestMatchers("/document_details").hasRole("LAWYER") .requestMatchers("/confirmation_of_divorce").hasAnyRole("SPOUSE", "LAWYER") .requestMatchers("/divorce_cancellation").hasRole("LAWYER") .requestMatchers("/account_details").hasRole("NOTARY") .requestMatchers("/notarialActionId/**").hasRole("NOTARY") .requestMatchers("/cu").hasRole("ADMIN") //μόλις φτιαχτεί να το αλλάξω .anyRequest().authenticated() .and().formLogin().loginPage("/login").defaultSuccessUrl("/my_divorces", true).permitAll() .and().logout(); http.headers().frameOptions().sameOrigin(); return http.build(); } @Bean public WebSecurityCustomizer webSecurityCustomizer() { return (web) -> web.ignoring().requestMatchers( "/css/**", "/js/**", "/images/**"); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
EliteOneTube/divorce_app_dev_ops
src/main/java/gr/dit/hua/divorce/config/SecurityConfig.java
759
//μόλις φτιαχτεί να το αλλάξω
line_comment
el
package gr.dit.hua.divorce.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.JdbcUserDetailsManager; import org.springframework.security.web.SecurityFilterChain; import javax.sql.DataSource; @Configuration @EnableWebSecurity public class SecurityConfig { @Autowired DataSource dataSource; @Bean public JdbcUserDetailsManager jdbcUserDetailsManager() throws Exception { JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager(); jdbcUserDetailsManager.setDataSource(dataSource); return jdbcUserDetailsManager; } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .cors().and().csrf().disable() .authorizeRequests() .requestMatchers("/").permitAll() .requestMatchers("/register").permitAll() .requestMatchers("/contact").permitAll() .requestMatchers("/more_information").permitAll() .requestMatchers("/help").permitAll() .requestMatchers("/member/**").hasRole("ADMIN") .requestMatchers("/my_divorces" ).hasAnyRole("LAWYER", "SPOUSE", "NOTARY") .requestMatchers("/divorce/deleteDivorce").hasRole("LAWYER") .requestMatchers("/divorce/getDivorces").hasRole("ADMIN") .requestMatchers("/divorce/saveDivorce").hasRole("LAWYER") .requestMatchers("/divorce/approveDivorce").hasRole("NOTARY") .requestMatchers("/cdp").hasRole("LAWYER") .requestMatchers("/member_names").hasRole("LAWYER") .requestMatchers("/document_details").hasRole("LAWYER") .requestMatchers("/confirmation_of_divorce").hasAnyRole("SPOUSE", "LAWYER") .requestMatchers("/divorce_cancellation").hasRole("LAWYER") .requestMatchers("/account_details").hasRole("NOTARY") .requestMatchers("/notarialActionId/**").hasRole("NOTARY") .requestMatchers("/cu").hasRole("ADMIN") //μόλις φτιαχτεί<SUF> .anyRequest().authenticated() .and().formLogin().loginPage("/login").defaultSuccessUrl("/my_divorces", true).permitAll() .and().logout(); http.headers().frameOptions().sameOrigin(); return http.build(); } @Bean public WebSecurityCustomizer webSecurityCustomizer() { return (web) -> web.ignoring().requestMatchers( "/css/**", "/js/**", "/images/**"); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
6544_1
import java.math.BigDecimal; /** * @author EvanCoh * se: ConvertMoneyToString.getVerbal(412444.87) */ public class ConvertMoneyToString { private ConvertMoneyToString() { } private static String[] m = {"", "ΕΝΑ ", "ΔΥΟ ", "ΤΡΙΑ ", "ΤΕΣΣΕΡΑ ", "ΠΕΝΤΕ ", "ΕΞΙ ", "ΕΠΤΑ ", "ΟΚΤΩ ", "ΕΝΝΕΑ "}; private static String[] mF = {"", "ΜΙΑ ", "", "ΤΡΕΙΣ ", "ΤΕΣΣΕΡΙΣ "}; private static String[] d1 = { //Διαφοροποίησεις των 11,12 ... "ΔΕΚΑ ", "ΕΝΤΕΚΑ ", "ΔΩΔΕΚΑ "}; private static String[] d = {"", "ΔΕΚΑ", "ΕΙΚΟΣΙ ", "ΤΡΙΑΝΤΑ ", "ΣΑΡΑΝΤΑ ", "ΠΕΝΗΝΤΑ ", "ΕΞΗΝΤΑ ", "ΕΒΔΟΜΗΝΤΑ ", "ΟΓΔΟΝΤΑ ", "ΕΝΕΝΗΝΤΑ "}; private static String[] e = {"", "ΕΚΑΤΟ", "ΔΙΑΚΟΣΙ", "ΤΡΙΑΚΟΣΙ", "ΤΕΤΡΑΚΟΣΙ", "ΠΕΝΤΑΚΟΣΙ", "ΕΞΑΚΟΣΙ", "ΕΠΤΑΚΟΣΙ", "ΟΚΤΑΚΟΣΙ", "ΕΝΝΙΑΚΟΣΙ"}; private static String[] idx = {"ΛΕΠΤΑ", "ΕΥΡΩ ", "ΧΙΛΙΑΔΕΣ ", "ΕΚΑΤΟΜΜΥΡΙ", "ΔΙΣ", "ΤΡΙΣ", "ΤΕΤΡΑΚΙΣ ", "ΠΕΝΤΑΚΙΣ "}; public static Integer Round(Double value) { Double doubl = Round(value, 0); Long lng = Math.round(doubl); return lng.intValue(); } public static Double Round(Double value, Integer precision) { return new BigDecimal(String.valueOf(value)).setScale(precision, BigDecimal.ROUND_HALF_UP).doubleValue(); } public static String GetVerbal(Double money) { return GetVerbal(money, true); } public static String GetVerbal(Double money, Boolean showZero) { return GetVerbal(money, showZero, true); } public static String GetVerbal(Double money, Boolean showZero, Boolean showCurrency) { String str; Short index = 0; Boolean isZero = true; Boolean isNegative = false; str = ""; if (money < 0) { money = -money; isNegative = true; } if (money != Math.floor(money)) { Integer value = Round(100 * money - 100 * Math.floor(money)); if (value >= 100) { value -= 100; money += 1.0; } //money = (Long)money; Long moneyLong = money.longValue(); if (value > 0) { isZero = false; if (moneyLong >= 1 && value > 0) { str += "ΚΑΙ "; } str += GetValue(value, index, showCurrency); } } while (money >= 1) { isZero = false; Double kati = money % 1000; Integer value = kati.intValue(); money /= 1000; Integer indexValue = index.intValue(); indexValue += 1; index = indexValue.shortValue(); str = GetValue(value, index, showCurrency) + str; //money = (Long)money; Long moneyLong = money.longValue(); money = moneyLong.doubleValue(); } if (isZero) { if (showZero) { str = "ΜΗΔΕΝ "; if (showCurrency) { str += idx[1]; } } } else { if (isNegative) { str = "MEION " + str; } } return str; } public static String GetValue(Integer money, Short index, Boolean showCurrency) { if (index == 2 && money == 1) { return "ΧΙΛΙΑ "; } String str = ""; Integer dekmon = money % 100; Integer monades = dekmon % 10; Integer ekatontades = (Integer) (money / 100); Integer dekades = (Integer) (dekmon / 10); //EKATONTADES if (ekatontades == 1) { if (dekmon == 0) { str = e[1] + " "; } else { str = e[1] + "Ν "; } } else if (ekatontades > 1) { if (index == 2) { str = e[ekatontades] + "ΕΣ "; } else { str = e[ekatontades] + "Α "; } } //DEKADES switch (dekmon) { case 10: str += d1[monades]; //"ΔΕΚΑ " με κενό στο τέλος break; case 11: str += d1[monades]; monades = 0; break; case 12: str += d1[monades]; monades = 0; break; default: str += d[dekades]; break; } //MONADES if ((index == 2) && (monades == 1 || monades == 3 || monades == 4)) { str += mF[monades]; } else { if (dekmon < 10 || dekmon > 12) { str += m[monades]; } } if (str.length() > 0 || index == 1) { if (index == 0 && money == 1) { if (showCurrency) { str += "ΛΕΠΤΟ"; } } else { if (index > 1 || showCurrency) { str += idx[index]; if (index > 2) { if (index > 3) { str += idx[3]; } if (money > 1) { str += "Α "; } else { str += "Ο "; } } } } } return str; } }
EvanCoh/monetaryAmountToGreek
ConvertMoneyToString.java
1,860
//Διαφοροποίησεις των 11,12 ...
line_comment
el
import java.math.BigDecimal; /** * @author EvanCoh * se: ConvertMoneyToString.getVerbal(412444.87) */ public class ConvertMoneyToString { private ConvertMoneyToString() { } private static String[] m = {"", "ΕΝΑ ", "ΔΥΟ ", "ΤΡΙΑ ", "ΤΕΣΣΕΡΑ ", "ΠΕΝΤΕ ", "ΕΞΙ ", "ΕΠΤΑ ", "ΟΚΤΩ ", "ΕΝΝΕΑ "}; private static String[] mF = {"", "ΜΙΑ ", "", "ΤΡΕΙΣ ", "ΤΕΣΣΕΡΙΣ "}; private static String[] d1 = { //Διαφοροποίησεις των<SUF> "ΔΕΚΑ ", "ΕΝΤΕΚΑ ", "ΔΩΔΕΚΑ "}; private static String[] d = {"", "ΔΕΚΑ", "ΕΙΚΟΣΙ ", "ΤΡΙΑΝΤΑ ", "ΣΑΡΑΝΤΑ ", "ΠΕΝΗΝΤΑ ", "ΕΞΗΝΤΑ ", "ΕΒΔΟΜΗΝΤΑ ", "ΟΓΔΟΝΤΑ ", "ΕΝΕΝΗΝΤΑ "}; private static String[] e = {"", "ΕΚΑΤΟ", "ΔΙΑΚΟΣΙ", "ΤΡΙΑΚΟΣΙ", "ΤΕΤΡΑΚΟΣΙ", "ΠΕΝΤΑΚΟΣΙ", "ΕΞΑΚΟΣΙ", "ΕΠΤΑΚΟΣΙ", "ΟΚΤΑΚΟΣΙ", "ΕΝΝΙΑΚΟΣΙ"}; private static String[] idx = {"ΛΕΠΤΑ", "ΕΥΡΩ ", "ΧΙΛΙΑΔΕΣ ", "ΕΚΑΤΟΜΜΥΡΙ", "ΔΙΣ", "ΤΡΙΣ", "ΤΕΤΡΑΚΙΣ ", "ΠΕΝΤΑΚΙΣ "}; public static Integer Round(Double value) { Double doubl = Round(value, 0); Long lng = Math.round(doubl); return lng.intValue(); } public static Double Round(Double value, Integer precision) { return new BigDecimal(String.valueOf(value)).setScale(precision, BigDecimal.ROUND_HALF_UP).doubleValue(); } public static String GetVerbal(Double money) { return GetVerbal(money, true); } public static String GetVerbal(Double money, Boolean showZero) { return GetVerbal(money, showZero, true); } public static String GetVerbal(Double money, Boolean showZero, Boolean showCurrency) { String str; Short index = 0; Boolean isZero = true; Boolean isNegative = false; str = ""; if (money < 0) { money = -money; isNegative = true; } if (money != Math.floor(money)) { Integer value = Round(100 * money - 100 * Math.floor(money)); if (value >= 100) { value -= 100; money += 1.0; } //money = (Long)money; Long moneyLong = money.longValue(); if (value > 0) { isZero = false; if (moneyLong >= 1 && value > 0) { str += "ΚΑΙ "; } str += GetValue(value, index, showCurrency); } } while (money >= 1) { isZero = false; Double kati = money % 1000; Integer value = kati.intValue(); money /= 1000; Integer indexValue = index.intValue(); indexValue += 1; index = indexValue.shortValue(); str = GetValue(value, index, showCurrency) + str; //money = (Long)money; Long moneyLong = money.longValue(); money = moneyLong.doubleValue(); } if (isZero) { if (showZero) { str = "ΜΗΔΕΝ "; if (showCurrency) { str += idx[1]; } } } else { if (isNegative) { str = "MEION " + str; } } return str; } public static String GetValue(Integer money, Short index, Boolean showCurrency) { if (index == 2 && money == 1) { return "ΧΙΛΙΑ "; } String str = ""; Integer dekmon = money % 100; Integer monades = dekmon % 10; Integer ekatontades = (Integer) (money / 100); Integer dekades = (Integer) (dekmon / 10); //EKATONTADES if (ekatontades == 1) { if (dekmon == 0) { str = e[1] + " "; } else { str = e[1] + "Ν "; } } else if (ekatontades > 1) { if (index == 2) { str = e[ekatontades] + "ΕΣ "; } else { str = e[ekatontades] + "Α "; } } //DEKADES switch (dekmon) { case 10: str += d1[monades]; //"ΔΕΚΑ " με κενό στο τέλος break; case 11: str += d1[monades]; monades = 0; break; case 12: str += d1[monades]; monades = 0; break; default: str += d[dekades]; break; } //MONADES if ((index == 2) && (monades == 1 || monades == 3 || monades == 4)) { str += mF[monades]; } else { if (dekmon < 10 || dekmon > 12) { str += m[monades]; } } if (str.length() > 0 || index == 1) { if (index == 0 && money == 1) { if (showCurrency) { str += "ΛΕΠΤΟ"; } } else { if (index > 1 || showCurrency) { str += idx[index]; if (index > 2) { if (index > 3) { str += idx[3]; } if (money > 1) { str += "Α "; } else { str += "Ο "; } } } } } return str; } }
2063_17
package mvc.com.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import mvc.com.bean.CategoryInfo; import mvc.com.bean.EvaluationlInfo; import mvc.com.util.DBConnection; public class EvaluationDao { public boolean evaluateEmployee(int amika, HttpServletRequest request) { //retrieve parameters int total = 0; double totald = 0.0; String type = request.getParameter("typeTF"); System.out.println("Type: " + type); String evaluationDate = request.getParameter("dateTF"); System.out.println("Uformatted date: " + evaluationDate); Date date = null; if (evaluationDate!=null){ try { date = new SimpleDateFormat("yyyy-MM-dd").parse(evaluationDate); } catch (ParseException e1) { System.out.println("Cannot parse date"); e1.printStackTrace(); } } String comments = request.getParameter("commentsTF"); String nextEvaluationDate = request.getParameter("nextEvaluationDateTF"); System.out.println("Uformatted nextEvaluationDate: " + nextEvaluationDate); Date next_evaluation_date = null; if (nextEvaluationDate!=null){ try { next_evaluation_date = new SimpleDateFormat("yyyy-MM-dd").parse(nextEvaluationDate); } catch (ParseException e1) { System.out.println("Cannot parse nextEvaluationDate"); e1.printStackTrace(); } } totald = Double.parseDouble(request.getParameter("totalTF")); System.out.println("Total before: " + totald); total = roundUp(totald); System.out.println("Total after: " + total); Connection currentCon = null; PreparedStatement prepStatement = null; int rowsUpdated = 0; try { currentCon = DBConnection.getConnection(); String query = "INSERT INTO employee_evaluation (type, date, comments, next_evaluation_date, total_rating, employee_am_ika) VALUES (?, ?, ?, ?, ?, ?)"; //6 values to insert prepStatement = currentCon.prepareStatement(query); prepStatement.setString(1, type); prepStatement.setDate(2, new java.sql.Date(date.getTime())); prepStatement.setString(3, comments); prepStatement.setDate(4, new java.sql.Date(next_evaluation_date.getTime())); prepStatement.setInt(5, total); prepStatement.setInt(6, amika); rowsUpdated = prepStatement.executeUpdate(); if (rowsUpdated > 0) { System.out.println("Evaluation Inserted!"); return true; } } catch (SQLException e) { System.out.println(e.getMessage()); } finally { if (currentCon != null) { // closes the database connection try { currentCon.close(); } catch (SQLException e) { e.printStackTrace(); } } } return false; } private static int roundUp(double d) { return (d > (int) d) ? (int) d + 1 : (int) d; } public boolean ratingPerCategory(HttpServletRequest request) { //retrieve parameters String[] titles = request.getParameterValues("title"); String[] ratings = request.getParameterValues("rating"); int[] categoryIds = new int[titles.length]; int[] ratingsInt = new int[ratings.length]; for(int i=0; i<ratingsInt.length; i++){ ratingsInt[i] = Integer.parseInt(ratings[i]); } for (int i = 0; i < titles.length; i++) { categoryIds[i] = i + 1; } // for (int i = 0; i < titles.length; i++) { // if(titles[i].trim().equalsIgnoreCase("Διαθεσιμότητα")){ // categoryIds[i] = 1; // } // else if(titles[i].trim().equalsIgnoreCase("Ανεξαρτησία")){ // categoryIds[i] = 2; // } // else if(titles[i].trim().equalsIgnoreCase("Πρωτοβουλία")){ // categoryIds[i] = 3; // } // else if(titles[i].trim().equalsIgnoreCase("Γνώση Εργασίας")){ // categoryIds[i] = 4; // } // else if(titles[i].trim().equalsIgnoreCase("Κρίση")){ // categoryIds[i] = 5; // } // else if(titles[i].trim().equalsIgnoreCase("Παραγωγικότητα")){ // categoryIds[i] = 6; // } // else if(titles[i].trim().equalsIgnoreCase("Ποιότητα")){ // categoryIds[i] = 7; // } // else if(titles[i].trim().equalsIgnoreCase("Αξιοπιστία")){ // categoryIds[i] = 8; // } // else if(titles[i].trim().equalsIgnoreCase("Εργασιακές Σχέσεις")){ // categoryIds[i] = 9; // } // else if(titles[i].trim().equalsIgnoreCase("Δημιουργικότητα")){ // categoryIds[i] = 10; // } // else if(titles[i].trim().equalsIgnoreCase("Διαχείριση Στόχων")){ // categoryIds[i] = 11; // } // else if(titles[i].trim().equalsIgnoreCase("Ανάληψη πολύπλοκων στόχων")){ // categoryIds[i] = 12; // } Connection currentCon = null; PreparedStatement prepStatement = null; ResultSet resultSet = null; int[] rowsUpdated = new int[0]; int id = -1; try { currentCon = DBConnection.getConnection(); String last_insert_query = "SELECT max(id) FROM employee_evaluation "; prepStatement = currentCon.prepareStatement(last_insert_query); resultSet = prepStatement.executeQuery(last_insert_query); while (resultSet.next()) { id = resultSet.getInt(1); System.out.println("ID = " + id); } String insert_query = "INSERT INTO evaluation_has_category (evaluation_id, category_id, rating) VALUES (?, ?, ?)"; prepStatement = currentCon.prepareStatement(insert_query); //3 values to insert for (int j = 0; j < ratingsInt.length; j++) { System.out.println("id: " + categoryIds[j] + "title" + titles[j] + ": " + ratings[j]); prepStatement.setInt(1, id); prepStatement.setInt(2, categoryIds[j]); prepStatement.setInt(3, ratingsInt[j]); prepStatement.addBatch(); } System.out.println("_____________________________"); rowsUpdated = prepStatement.executeBatch(); if (rowsUpdated.length > 0) { System.out.println("Evaluation Inserted!"); return true; } } catch (SQLException e) { System.out.println(e.getMessage()); } finally { if (currentCon != null) { // closes the database connection try { currentCon.close(); } catch (SQLException e) { e.printStackTrace(); } } } return false; } public List<EvaluationlInfo> myEvaluationsList(int employee_am_ika) throws SQLException { List<EvaluationlInfo> myEvaluations = new ArrayList<EvaluationlInfo>(); Connection currentCon = null; Statement statement = null; ResultSet resultSet = null; try{ currentCon = DBConnection.getConnection(); statement = currentCon.createStatement(); resultSet = statement.executeQuery("SELECT * FROM trackingdb.employee_evaluation AS e WHERE employee_am_ika='" + employee_am_ika + "' ORDER BY e.id"); while (resultSet.next()) { EvaluationlInfo myEvaluation = new EvaluationlInfo(); myEvaluation.setId(resultSet.getInt("id")); myEvaluation.setType(resultSet.getString("type")); myEvaluation.setDate(resultSet.getDate("date")); myEvaluation.setComments(resultSet.getString("comments")); myEvaluation.setNext_evaluation_date(resultSet.getDate("next_evaluation_date")); myEvaluation.setTotal_rating(resultSet.getInt("total_rating")); myEvaluation.setEmployee_am_ika(resultSet.getInt("employee_am_ika")); myEvaluations.add(myEvaluation); } } finally { if (currentCon != null) { // closes the database connection try { currentCon.close(); } catch (SQLException e) { e.printStackTrace(); } } } return myEvaluations; //returning the list of completed goals } public List<CategoryInfo> ratingsList(int employee_am_ika, int id) throws SQLException { List<CategoryInfo> ratings = new ArrayList<CategoryInfo>(); Connection currentCon = null; Statement statement = null; ResultSet resultSet = null; try{ currentCon = DBConnection.getConnection(); statement = currentCon.createStatement(); resultSet = statement.executeQuery("SELECT title, rating FROM trackingdb.employee_evaluation AS e" + " INNER JOIN trackingdb.evaluation_has_category AS h" + " ON e.id ='"+ id +"' AND h.evaluation_id ='"+ id +"' AND employee_am_ika='" + employee_am_ika + "'" + " INNER JOIN trackingdb.category AS c ON c.id=h.category_id;"); while (resultSet.next()) { CategoryInfo categoryPerRating = new CategoryInfo(); categoryPerRating.setCategory_title(resultSet.getString(1)); categoryPerRating.setRating(resultSet.getInt(2)); ratings.add(categoryPerRating); } } finally { if (currentCon != null) { // closes the database connection try { currentCon.close(); } catch (SQLException e) { e.printStackTrace(); } } } return ratings; //returning the list of completed goals } }
Evrydiki/TrackingEvaluationBonusSystem
src/mvc/com/dao/EvaluationDao.java
2,802
// else if(titles[i].trim().equalsIgnoreCase("Ανάληψη πολύπλοκων στόχων")){
line_comment
el
package mvc.com.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import mvc.com.bean.CategoryInfo; import mvc.com.bean.EvaluationlInfo; import mvc.com.util.DBConnection; public class EvaluationDao { public boolean evaluateEmployee(int amika, HttpServletRequest request) { //retrieve parameters int total = 0; double totald = 0.0; String type = request.getParameter("typeTF"); System.out.println("Type: " + type); String evaluationDate = request.getParameter("dateTF"); System.out.println("Uformatted date: " + evaluationDate); Date date = null; if (evaluationDate!=null){ try { date = new SimpleDateFormat("yyyy-MM-dd").parse(evaluationDate); } catch (ParseException e1) { System.out.println("Cannot parse date"); e1.printStackTrace(); } } String comments = request.getParameter("commentsTF"); String nextEvaluationDate = request.getParameter("nextEvaluationDateTF"); System.out.println("Uformatted nextEvaluationDate: " + nextEvaluationDate); Date next_evaluation_date = null; if (nextEvaluationDate!=null){ try { next_evaluation_date = new SimpleDateFormat("yyyy-MM-dd").parse(nextEvaluationDate); } catch (ParseException e1) { System.out.println("Cannot parse nextEvaluationDate"); e1.printStackTrace(); } } totald = Double.parseDouble(request.getParameter("totalTF")); System.out.println("Total before: " + totald); total = roundUp(totald); System.out.println("Total after: " + total); Connection currentCon = null; PreparedStatement prepStatement = null; int rowsUpdated = 0; try { currentCon = DBConnection.getConnection(); String query = "INSERT INTO employee_evaluation (type, date, comments, next_evaluation_date, total_rating, employee_am_ika) VALUES (?, ?, ?, ?, ?, ?)"; //6 values to insert prepStatement = currentCon.prepareStatement(query); prepStatement.setString(1, type); prepStatement.setDate(2, new java.sql.Date(date.getTime())); prepStatement.setString(3, comments); prepStatement.setDate(4, new java.sql.Date(next_evaluation_date.getTime())); prepStatement.setInt(5, total); prepStatement.setInt(6, amika); rowsUpdated = prepStatement.executeUpdate(); if (rowsUpdated > 0) { System.out.println("Evaluation Inserted!"); return true; } } catch (SQLException e) { System.out.println(e.getMessage()); } finally { if (currentCon != null) { // closes the database connection try { currentCon.close(); } catch (SQLException e) { e.printStackTrace(); } } } return false; } private static int roundUp(double d) { return (d > (int) d) ? (int) d + 1 : (int) d; } public boolean ratingPerCategory(HttpServletRequest request) { //retrieve parameters String[] titles = request.getParameterValues("title"); String[] ratings = request.getParameterValues("rating"); int[] categoryIds = new int[titles.length]; int[] ratingsInt = new int[ratings.length]; for(int i=0; i<ratingsInt.length; i++){ ratingsInt[i] = Integer.parseInt(ratings[i]); } for (int i = 0; i < titles.length; i++) { categoryIds[i] = i + 1; } // for (int i = 0; i < titles.length; i++) { // if(titles[i].trim().equalsIgnoreCase("Διαθεσιμότητα")){ // categoryIds[i] = 1; // } // else if(titles[i].trim().equalsIgnoreCase("Ανεξαρτησία")){ // categoryIds[i] = 2; // } // else if(titles[i].trim().equalsIgnoreCase("Πρωτοβουλία")){ // categoryIds[i] = 3; // } // else if(titles[i].trim().equalsIgnoreCase("Γνώση Εργασίας")){ // categoryIds[i] = 4; // } // else if(titles[i].trim().equalsIgnoreCase("Κρίση")){ // categoryIds[i] = 5; // } // else if(titles[i].trim().equalsIgnoreCase("Παραγωγικότητα")){ // categoryIds[i] = 6; // } // else if(titles[i].trim().equalsIgnoreCase("Ποιότητα")){ // categoryIds[i] = 7; // } // else if(titles[i].trim().equalsIgnoreCase("Αξιοπιστία")){ // categoryIds[i] = 8; // } // else if(titles[i].trim().equalsIgnoreCase("Εργασιακές Σχέσεις")){ // categoryIds[i] = 9; // } // else if(titles[i].trim().equalsIgnoreCase("Δημιουργικότητα")){ // categoryIds[i] = 10; // } // else if(titles[i].trim().equalsIgnoreCase("Διαχείριση Στόχων")){ // categoryIds[i] = 11; // } // else if(titles[i].trim().equalsIgnoreCase("Ανάληψη<SUF> // categoryIds[i] = 12; // } Connection currentCon = null; PreparedStatement prepStatement = null; ResultSet resultSet = null; int[] rowsUpdated = new int[0]; int id = -1; try { currentCon = DBConnection.getConnection(); String last_insert_query = "SELECT max(id) FROM employee_evaluation "; prepStatement = currentCon.prepareStatement(last_insert_query); resultSet = prepStatement.executeQuery(last_insert_query); while (resultSet.next()) { id = resultSet.getInt(1); System.out.println("ID = " + id); } String insert_query = "INSERT INTO evaluation_has_category (evaluation_id, category_id, rating) VALUES (?, ?, ?)"; prepStatement = currentCon.prepareStatement(insert_query); //3 values to insert for (int j = 0; j < ratingsInt.length; j++) { System.out.println("id: " + categoryIds[j] + "title" + titles[j] + ": " + ratings[j]); prepStatement.setInt(1, id); prepStatement.setInt(2, categoryIds[j]); prepStatement.setInt(3, ratingsInt[j]); prepStatement.addBatch(); } System.out.println("_____________________________"); rowsUpdated = prepStatement.executeBatch(); if (rowsUpdated.length > 0) { System.out.println("Evaluation Inserted!"); return true; } } catch (SQLException e) { System.out.println(e.getMessage()); } finally { if (currentCon != null) { // closes the database connection try { currentCon.close(); } catch (SQLException e) { e.printStackTrace(); } } } return false; } public List<EvaluationlInfo> myEvaluationsList(int employee_am_ika) throws SQLException { List<EvaluationlInfo> myEvaluations = new ArrayList<EvaluationlInfo>(); Connection currentCon = null; Statement statement = null; ResultSet resultSet = null; try{ currentCon = DBConnection.getConnection(); statement = currentCon.createStatement(); resultSet = statement.executeQuery("SELECT * FROM trackingdb.employee_evaluation AS e WHERE employee_am_ika='" + employee_am_ika + "' ORDER BY e.id"); while (resultSet.next()) { EvaluationlInfo myEvaluation = new EvaluationlInfo(); myEvaluation.setId(resultSet.getInt("id")); myEvaluation.setType(resultSet.getString("type")); myEvaluation.setDate(resultSet.getDate("date")); myEvaluation.setComments(resultSet.getString("comments")); myEvaluation.setNext_evaluation_date(resultSet.getDate("next_evaluation_date")); myEvaluation.setTotal_rating(resultSet.getInt("total_rating")); myEvaluation.setEmployee_am_ika(resultSet.getInt("employee_am_ika")); myEvaluations.add(myEvaluation); } } finally { if (currentCon != null) { // closes the database connection try { currentCon.close(); } catch (SQLException e) { e.printStackTrace(); } } } return myEvaluations; //returning the list of completed goals } public List<CategoryInfo> ratingsList(int employee_am_ika, int id) throws SQLException { List<CategoryInfo> ratings = new ArrayList<CategoryInfo>(); Connection currentCon = null; Statement statement = null; ResultSet resultSet = null; try{ currentCon = DBConnection.getConnection(); statement = currentCon.createStatement(); resultSet = statement.executeQuery("SELECT title, rating FROM trackingdb.employee_evaluation AS e" + " INNER JOIN trackingdb.evaluation_has_category AS h" + " ON e.id ='"+ id +"' AND h.evaluation_id ='"+ id +"' AND employee_am_ika='" + employee_am_ika + "'" + " INNER JOIN trackingdb.category AS c ON c.id=h.category_id;"); while (resultSet.next()) { CategoryInfo categoryPerRating = new CategoryInfo(); categoryPerRating.setCategory_title(resultSet.getString(1)); categoryPerRating.setRating(resultSet.getInt(2)); ratings.add(categoryPerRating); } } finally { if (currentCon != null) { // closes the database connection try { currentCon.close(); } catch (SQLException e) { e.printStackTrace(); } } } return ratings; //returning the list of completed goals } }
23225_3
import java.util.Scanner; public class DNAPalindrome { public static StringDoubleEndedQueueImpl CreateQ(String DNAseq){ StringDoubleEndedQueueImpl s = new StringDoubleEndedQueueImpl(); char[] charArray = DNAseq.toCharArray(); for (int i = 0; i < charArray.length; i++) { s.addLast(String.valueOf(charArray[i])); } return s; } public static boolean isValidDNASequence(String sequence) { // Ελέγχουμε αν το String είναι null. if (sequence == null) { return false; } // Ελέγχουμε αν το String είναι κενό. if (sequence.isEmpty()) { return true; } // Ελέγχουμε κάθε χαρακτήρα του String για εγκυρότητα. for (char nucleotide : sequence.toCharArray()) { if (!isValidNucleotide(nucleotide)) { return false; } } return true; } private static boolean isValidNucleotide(char nucleotide) { // Ελέγχουμε αν ο χαρακτήρας είναι ένα από τα έγκυρα A, T, C, G (πεζά γράμματα). return (nucleotide == 'A' || nucleotide == 'T' || nucleotide == 'C' || nucleotide == 'G'); } public static boolean isWatson( StringDoubleEndedQueueImpl q1){ while(!q1.isEmpty()){ if((q1.getFirst().equals("A") && q1.getLast().equals("T")) || (q1.getFirst().equals("T") && q1.getLast().equals("A")) || (q1.getFirst().equals("C") && q1.getLast().equals("G")) || (q1.getFirst().equals("G") &&q1.getLast().equals("C"))){ q1.removeFirst(); q1.removeLast(); q1.printQueue(System.out); System.out.println("this is queue"); }else{ return false; } } return true; } public static void main(String[] args) { try (Scanner in = new Scanner(System.in)) { System.out.println("Give me a Dna sequence"); String DNAseq=in.nextLine(); while(!isValidDNASequence(DNAseq)){ System.out.println("Give me a Dna sequence"); DNAseq=in.nextLine(); } StringDoubleEndedQueueImpl q1=CreateQ(DNAseq); if (isWatson(q1)) { System.out.println(DNAseq+" is watson"); }else{ System.out.println(DNAseq+" is not watson"); } } } }
FANISPAP123/Data-Structure
DS23-project1/DNAPalindrome.java
715
// Ελέγχουμε αν ο χαρακτήρας είναι ένα από τα έγκυρα A, T, C, G (πεζά γράμματα).
line_comment
el
import java.util.Scanner; public class DNAPalindrome { public static StringDoubleEndedQueueImpl CreateQ(String DNAseq){ StringDoubleEndedQueueImpl s = new StringDoubleEndedQueueImpl(); char[] charArray = DNAseq.toCharArray(); for (int i = 0; i < charArray.length; i++) { s.addLast(String.valueOf(charArray[i])); } return s; } public static boolean isValidDNASequence(String sequence) { // Ελέγχουμε αν το String είναι null. if (sequence == null) { return false; } // Ελέγχουμε αν το String είναι κενό. if (sequence.isEmpty()) { return true; } // Ελέγχουμε κάθε χαρακτήρα του String για εγκυρότητα. for (char nucleotide : sequence.toCharArray()) { if (!isValidNucleotide(nucleotide)) { return false; } } return true; } private static boolean isValidNucleotide(char nucleotide) { // Ελέγχουμε αν<SUF> return (nucleotide == 'A' || nucleotide == 'T' || nucleotide == 'C' || nucleotide == 'G'); } public static boolean isWatson( StringDoubleEndedQueueImpl q1){ while(!q1.isEmpty()){ if((q1.getFirst().equals("A") && q1.getLast().equals("T")) || (q1.getFirst().equals("T") && q1.getLast().equals("A")) || (q1.getFirst().equals("C") && q1.getLast().equals("G")) || (q1.getFirst().equals("G") &&q1.getLast().equals("C"))){ q1.removeFirst(); q1.removeLast(); q1.printQueue(System.out); System.out.println("this is queue"); }else{ return false; } } return true; } public static void main(String[] args) { try (Scanner in = new Scanner(System.in)) { System.out.println("Give me a Dna sequence"); String DNAseq=in.nextLine(); while(!isValidDNASequence(DNAseq)){ System.out.println("Give me a Dna sequence"); DNAseq=in.nextLine(); } StringDoubleEndedQueueImpl q1=CreateQ(DNAseq); if (isWatson(q1)) { System.out.println(DNAseq+" is watson"); }else{ System.out.println(DNAseq+" is not watson"); } } } }
11705_2
// Στο αρχείο Main.java package bankapp; import bankapp.model.OverdraftAccount; import bankapp.model.JointAccount; /** * Κύρια κλάση για τον έλεγχο της λειτουργίας των λογαριασμών. */ public class Main { public static void main(String[] args) { // Δημιουργία λογαριασμών OverdraftAccount overdraftAccount = new OverdraftAccount(1, 1000.0, 500.0); JointAccount jointAccount = new JointAccount(2, 2000.0, "John", "Mike"); // Εκτύπωση ιδιοτήτων λογαριασμών System.out.println("Overdraft Account Balance: " + overdraftAccount.getBalance()); System.out.println("Joint Account Holders: " + String.join(", ", jointAccount.getHolders())); } }
Filippostsak/java-oo-projects
src/bankapp/Main.java
284
// Εκτύπωση ιδιοτήτων λογαριασμών
line_comment
el
// Στο αρχείο Main.java package bankapp; import bankapp.model.OverdraftAccount; import bankapp.model.JointAccount; /** * Κύρια κλάση για τον έλεγχο της λειτουργίας των λογαριασμών. */ public class Main { public static void main(String[] args) { // Δημιουργία λογαριασμών OverdraftAccount overdraftAccount = new OverdraftAccount(1, 1000.0, 500.0); JointAccount jointAccount = new JointAccount(2, 2000.0, "John", "Mike"); // Εκτύπωση ιδιοτήτων<SUF> System.out.println("Overdraft Account Balance: " + overdraftAccount.getBalance()); System.out.println("Joint Account Holders: " + String.join(", ", jointAccount.getHolders())); } }
18213_0
package JavaClasses.class1; public class papi { public static void main(String[] args) { X a = new X(2,3); //using copy X a1 = new X(a); // έχουμε 2 αντικείμενα με τις ίδιες τιμές // vs X a2 = a; // 2 μεταβλητές για το ίδιο αντικείμενο System.out.println(a.getI()); a.setI(10); System.out.println(a.getI()); Surface s1 = new Surface("A", 3,5); System.out.println(s1.getSurface()); } }
Firewolf05/JavaClasses
src/JavaClasses/class1/papi.java
199
// έχουμε 2 αντικείμενα με τις ίδιες τιμές
line_comment
el
package JavaClasses.class1; public class papi { public static void main(String[] args) { X a = new X(2,3); //using copy X a1 = new X(a); // έχουμε 2<SUF> // vs X a2 = a; // 2 μεταβλητές για το ίδιο αντικείμενο System.out.println(a.getI()); a.setI(10); System.out.println(a.getI()); Surface s1 = new Surface("A", 3,5); System.out.println(s1.getSurface()); } }
19290_16
package org.example; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Main { public static void main(String[] args) { //Create arraylist of doctors ArrayList<Doctor> doctors = new ArrayList<>(); Doctor doc1 = new Doctor("maria", "k", "8754"); Doctor doc2 = new Doctor("kwstas", "k", "8753"); Doctor doc3 = new Doctor("dimitra", "k", "98674"); Doctor doc4 = new Doctor("giwrgos", "k", "8764"); //create arraylist of timeslots for VacCenter1 ArrayList<Timeslot> timeslots1 = new ArrayList<>(); timeslots1.add(new Timeslot(10, 4, 2024, 9, 0, 9, 30, doc1)); timeslots1.add(new Timeslot(10, 4, 2024, 10, 0, 10, 30, doc2)); timeslots1.add(new Timeslot(10, 4, 2024, 11, 0, 9, 30, doc1)); timeslots1.add(new Timeslot(10, 4, 2024, 12, 0, 10, 30, doc2)); timeslots1.add(new Timeslot(10, 4, 2024, 13, 0, 9, 30, doc1)); timeslots1.add(new Timeslot(10, 4, 2024, 14, 0, 10, 30, doc2)); timeslots1.add(new Timeslot(10, 4, 2024, 15, 0, 9, 30, doc1)); timeslots1.add(new Timeslot(10, 4, 2024, 16, 0, 10, 30, doc2)); timeslots1.add(new Timeslot(10, 4, 2024, 17, 0, 9, 30, doc1)); timeslots1.add(new Timeslot(10, 4, 2024, 18, 0, 10, 30, doc2)); //create arraylist of timeslots for VacCenter2 ArrayList<Timeslot> timeslots2 = new ArrayList<>(); timeslots2.add(new Timeslot(10, 4, 2024, 9, 0, 9, 30, doc3)); timeslots2.add(new Timeslot(10, 4, 2024, 10, 0, 10, 30, doc4)); timeslots2.add(new Timeslot(10, 4, 2024, 11, 0, 9, 30, doc3)); timeslots2.add(new Timeslot(10, 4, 2024, 12, 0, 10, 30, doc4)); timeslots2.add(new Timeslot(10, 4, 2024, 13, 0, 9, 30, doc3)); timeslots2.add(new Timeslot(10, 4, 2024, 14, 0, 10, 30, doc4)); timeslots2.add(new Timeslot(10, 4, 2024, 15, 0, 9, 30, doc3)); timeslots2.add(new Timeslot(10, 4, 2024, 16, 0, 10, 30, doc4)); timeslots2.add(new Timeslot(10, 4, 2024, 17, 0, 9, 30, doc3)); timeslots2.add(new Timeslot(10, 4, 2024, 18, 0, 10, 30, doc4)); //create arraylist of VacCenters ArrayList<VaccinationCenter> vaccinationCenters = new ArrayList<>(); vaccinationCenters.add(new VaccinationCenter("123", "casterly rock", timeslots1)); vaccinationCenters.add(new VaccinationCenter("456", "storm's end", timeslots2)); //Set vaccination center to doctors doc1.setVaccinationCenter(vaccinationCenters.get(0)); doc2.setVaccinationCenter(vaccinationCenters.get(0)); doc3.setVaccinationCenter(vaccinationCenters.get(1)); doc4.setVaccinationCenter(vaccinationCenters.get(1)); //add timeslots to doctors for(int i=0;i<10;i++){ if(i<5){ doc1.addTimeslot(timeslots1.get(i)); doc3.addTimeslot(timeslots2.get(i)); } else{ doc2.addTimeslot(timeslots2.get(i)); doc4.addTimeslot(timeslots2.get(i)); } } //create arraylist of insures people ArrayList<Insured> insuredpeople = new ArrayList<>(); insuredpeople.add(new Insured("Petyr", "Baelish", "128975439", "[email protected]", "673537", "11/03/1935")); insuredpeople.add(new Insured("Lord", "Varys", "373598", "[email protected]", "846338", "17/03/1972")); insuredpeople.add(new Insured("Theon", "Greyjoy", "83635", "[email protected]", "83625", "7/08/1945")); insuredpeople.add(new Insured("Sandor", "Clegane", "823627", "[email protected]", "927156", "5/12/1988")); insuredpeople.add(new Insured("Brienne", "of Tarth", "987534", "[email protected]", "82615", "15/12/1999")); insuredpeople.add(new Insured("Arya", "Stark", "765439", "[email protected]", "76754", "10/1/2010")); insuredpeople.add(new Insured("Sansa", "Stark", "6535978", "[email protected]", "787530", "8/11/2011")); insuredpeople.add(new Insured("Jon", "Snow", "898674", "[email protected]", "876430", "18/4/1980")); insuredpeople.add(new Insured("Daenerys", "Targaryen", "875643", "[email protected]", "998764", "1/5/1989")); insuredpeople.add(new Insured("Tyrion", "Lannister", "7635234", "[email protected]", "926254", "10/7/1970")); insuredpeople.add(new Insured("Cersei", "Lannister", "87632", "[email protected]", "9864309", "1/4/1943")); insuredpeople.add(new Insured("Ned", "Stark", "875318", "[email protected]", "986752", "19/9/1969")); // Shuffle the list to get random ordering Collections.shuffle(insuredpeople); //make reservation for 8 insured people //prepei na ftiaxtei o elegxos gia to an apo randoms select vaccCenter na min dialegete panta 1. for (int i = 0; i < 8; i++){ Reservation reservation = insuredpeople.get(i).makeReservation(vaccinationCenters); VaccinationCenter VacCenter = reservation.getVaccinationCenter(); VacCenter.addReservation(reservation); Doctor doctor = reservation.findDoctor(doctors); doctor.addReservation(reservation); } int count = 0; //Make vaccination //Na min 3exaso avrio na valo oti emvoliazontai oi 6 apo tous 8 for (Doctor doctor:doctors){ for (Reservation res:doctor.getReservations()){ //den xreiazetai mallon na epistrefei Vaccination VaccObj =res.getInsured().getVaccinated(res,doctor); doctor.addVaccination(VaccObj); count=count+1; if (count >=6) { break; // Breaks out of the inner loop } } if (count >= 6) { break; // Breaks out of the outer loop } } //Επικείμενα ραντεβου για κάθε εμβολιαστικό for(VaccinationCenter vacCenter:vaccinationCenters){ vacCenter.printUpcomingReservations(); } //Ελέυθερες χρονικές θυρίδες κάθε εμβολιαστικού vaccinationCenters.get(0).printFreeTimeslot(timeslots1); vaccinationCenters.get(1).printFreeTimeslot(timeslots2); //Εμβολιασμούς κάθε γιατρός για όλους τους γιατρούς for (Doctor doctor:doctors){ doctor.printVaccinations(); } /*//Ασφαλισμένοι >60 που δεν έχουν κλείσει ραντεβού for(VaccinationCenter vaccCenter:vaccinationCenters){ vaccCenter.printInsuredWithoutReservation(insuredpeople); }*/ /*//create second Arraylist of appointments na to sizitisoume ArrayList<Reservation> reservations = new ArrayList<>(); reservations.add(new Reservation(insuredpeople.get(0), timeslots1.get(1))); reservations.add(new Reservation(insuredpeople.get(3), timeslots2.get(4))); reservations.add(new Reservation(insuredpeople.get(4), timeslots1.get(7))); reservations.add(new Reservation(insuredpeople.get(6), timeslots2.get(8))); reservations.add(new Reservation(insuredpeople.get(7), timeslots1.get(2))); reservations.add(new Reservation(insuredpeople.get(10), timeslots2.get(3))); reservations.add(new Reservation(insuredpeople.get(11), timeslots1.get(9))); reservations.add(new Reservation(insuredpeople.get(9), timeslots2.get(1))); printToFile(reservations);*/ } private static void printToFile(List<Reservation> reservations) { File file = new File("vaccination-results.txt"); try (PrintWriter pw = new PrintWriter(file)) { pw.println("The first center has the appointments: "); for (var elem : reservations) { if (elem.getVaccinationCenter().getCode().equals("123")) { pw.println(elem.getTimeslot()); } } pw.println("The second center has the appointments: "); for (var elem : reservations) { if (elem.getVaccinationCenter().getCode().equals("456")) { pw.println(elem.getTimeslot()); } } } catch (IOException e) { System.out.println(e); } } }
GTGH-accenture-uom-2/Team4-part1
src/main/java/org/example/Main.java
3,081
//Εμβολιασμούς κάθε γιατρός για όλους τους γιατρούς
line_comment
el
package org.example; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Main { public static void main(String[] args) { //Create arraylist of doctors ArrayList<Doctor> doctors = new ArrayList<>(); Doctor doc1 = new Doctor("maria", "k", "8754"); Doctor doc2 = new Doctor("kwstas", "k", "8753"); Doctor doc3 = new Doctor("dimitra", "k", "98674"); Doctor doc4 = new Doctor("giwrgos", "k", "8764"); //create arraylist of timeslots for VacCenter1 ArrayList<Timeslot> timeslots1 = new ArrayList<>(); timeslots1.add(new Timeslot(10, 4, 2024, 9, 0, 9, 30, doc1)); timeslots1.add(new Timeslot(10, 4, 2024, 10, 0, 10, 30, doc2)); timeslots1.add(new Timeslot(10, 4, 2024, 11, 0, 9, 30, doc1)); timeslots1.add(new Timeslot(10, 4, 2024, 12, 0, 10, 30, doc2)); timeslots1.add(new Timeslot(10, 4, 2024, 13, 0, 9, 30, doc1)); timeslots1.add(new Timeslot(10, 4, 2024, 14, 0, 10, 30, doc2)); timeslots1.add(new Timeslot(10, 4, 2024, 15, 0, 9, 30, doc1)); timeslots1.add(new Timeslot(10, 4, 2024, 16, 0, 10, 30, doc2)); timeslots1.add(new Timeslot(10, 4, 2024, 17, 0, 9, 30, doc1)); timeslots1.add(new Timeslot(10, 4, 2024, 18, 0, 10, 30, doc2)); //create arraylist of timeslots for VacCenter2 ArrayList<Timeslot> timeslots2 = new ArrayList<>(); timeslots2.add(new Timeslot(10, 4, 2024, 9, 0, 9, 30, doc3)); timeslots2.add(new Timeslot(10, 4, 2024, 10, 0, 10, 30, doc4)); timeslots2.add(new Timeslot(10, 4, 2024, 11, 0, 9, 30, doc3)); timeslots2.add(new Timeslot(10, 4, 2024, 12, 0, 10, 30, doc4)); timeslots2.add(new Timeslot(10, 4, 2024, 13, 0, 9, 30, doc3)); timeslots2.add(new Timeslot(10, 4, 2024, 14, 0, 10, 30, doc4)); timeslots2.add(new Timeslot(10, 4, 2024, 15, 0, 9, 30, doc3)); timeslots2.add(new Timeslot(10, 4, 2024, 16, 0, 10, 30, doc4)); timeslots2.add(new Timeslot(10, 4, 2024, 17, 0, 9, 30, doc3)); timeslots2.add(new Timeslot(10, 4, 2024, 18, 0, 10, 30, doc4)); //create arraylist of VacCenters ArrayList<VaccinationCenter> vaccinationCenters = new ArrayList<>(); vaccinationCenters.add(new VaccinationCenter("123", "casterly rock", timeslots1)); vaccinationCenters.add(new VaccinationCenter("456", "storm's end", timeslots2)); //Set vaccination center to doctors doc1.setVaccinationCenter(vaccinationCenters.get(0)); doc2.setVaccinationCenter(vaccinationCenters.get(0)); doc3.setVaccinationCenter(vaccinationCenters.get(1)); doc4.setVaccinationCenter(vaccinationCenters.get(1)); //add timeslots to doctors for(int i=0;i<10;i++){ if(i<5){ doc1.addTimeslot(timeslots1.get(i)); doc3.addTimeslot(timeslots2.get(i)); } else{ doc2.addTimeslot(timeslots2.get(i)); doc4.addTimeslot(timeslots2.get(i)); } } //create arraylist of insures people ArrayList<Insured> insuredpeople = new ArrayList<>(); insuredpeople.add(new Insured("Petyr", "Baelish", "128975439", "[email protected]", "673537", "11/03/1935")); insuredpeople.add(new Insured("Lord", "Varys", "373598", "[email protected]", "846338", "17/03/1972")); insuredpeople.add(new Insured("Theon", "Greyjoy", "83635", "[email protected]", "83625", "7/08/1945")); insuredpeople.add(new Insured("Sandor", "Clegane", "823627", "[email protected]", "927156", "5/12/1988")); insuredpeople.add(new Insured("Brienne", "of Tarth", "987534", "[email protected]", "82615", "15/12/1999")); insuredpeople.add(new Insured("Arya", "Stark", "765439", "[email protected]", "76754", "10/1/2010")); insuredpeople.add(new Insured("Sansa", "Stark", "6535978", "[email protected]", "787530", "8/11/2011")); insuredpeople.add(new Insured("Jon", "Snow", "898674", "[email protected]", "876430", "18/4/1980")); insuredpeople.add(new Insured("Daenerys", "Targaryen", "875643", "[email protected]", "998764", "1/5/1989")); insuredpeople.add(new Insured("Tyrion", "Lannister", "7635234", "[email protected]", "926254", "10/7/1970")); insuredpeople.add(new Insured("Cersei", "Lannister", "87632", "[email protected]", "9864309", "1/4/1943")); insuredpeople.add(new Insured("Ned", "Stark", "875318", "[email protected]", "986752", "19/9/1969")); // Shuffle the list to get random ordering Collections.shuffle(insuredpeople); //make reservation for 8 insured people //prepei na ftiaxtei o elegxos gia to an apo randoms select vaccCenter na min dialegete panta 1. for (int i = 0; i < 8; i++){ Reservation reservation = insuredpeople.get(i).makeReservation(vaccinationCenters); VaccinationCenter VacCenter = reservation.getVaccinationCenter(); VacCenter.addReservation(reservation); Doctor doctor = reservation.findDoctor(doctors); doctor.addReservation(reservation); } int count = 0; //Make vaccination //Na min 3exaso avrio na valo oti emvoliazontai oi 6 apo tous 8 for (Doctor doctor:doctors){ for (Reservation res:doctor.getReservations()){ //den xreiazetai mallon na epistrefei Vaccination VaccObj =res.getInsured().getVaccinated(res,doctor); doctor.addVaccination(VaccObj); count=count+1; if (count >=6) { break; // Breaks out of the inner loop } } if (count >= 6) { break; // Breaks out of the outer loop } } //Επικείμενα ραντεβου για κάθε εμβολιαστικό for(VaccinationCenter vacCenter:vaccinationCenters){ vacCenter.printUpcomingReservations(); } //Ελέυθερες χρονικές θυρίδες κάθε εμβολιαστικού vaccinationCenters.get(0).printFreeTimeslot(timeslots1); vaccinationCenters.get(1).printFreeTimeslot(timeslots2); //Εμβολιασμούς κάθε<SUF> for (Doctor doctor:doctors){ doctor.printVaccinations(); } /*//Ασφαλισμένοι >60 που δεν έχουν κλείσει ραντεβού for(VaccinationCenter vaccCenter:vaccinationCenters){ vaccCenter.printInsuredWithoutReservation(insuredpeople); }*/ /*//create second Arraylist of appointments na to sizitisoume ArrayList<Reservation> reservations = new ArrayList<>(); reservations.add(new Reservation(insuredpeople.get(0), timeslots1.get(1))); reservations.add(new Reservation(insuredpeople.get(3), timeslots2.get(4))); reservations.add(new Reservation(insuredpeople.get(4), timeslots1.get(7))); reservations.add(new Reservation(insuredpeople.get(6), timeslots2.get(8))); reservations.add(new Reservation(insuredpeople.get(7), timeslots1.get(2))); reservations.add(new Reservation(insuredpeople.get(10), timeslots2.get(3))); reservations.add(new Reservation(insuredpeople.get(11), timeslots1.get(9))); reservations.add(new Reservation(insuredpeople.get(9), timeslots2.get(1))); printToFile(reservations);*/ } private static void printToFile(List<Reservation> reservations) { File file = new File("vaccination-results.txt"); try (PrintWriter pw = new PrintWriter(file)) { pw.println("The first center has the appointments: "); for (var elem : reservations) { if (elem.getVaccinationCenter().getCode().equals("123")) { pw.println(elem.getTimeslot()); } } pw.println("The second center has the appointments: "); for (var elem : reservations) { if (elem.getVaccinationCenter().getCode().equals("456")) { pw.println(elem.getTimeslot()); } } } catch (IOException e) { System.out.println(e); } } }
17_3
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; public class XlsReader { private ArrayList<Course> courses=new ArrayList<Course>(); private ArrayList<Course> coursesSelected=new ArrayList<Course>(); private HashSet<String> courseDistinct = new HashSet<String>(); private HashSet<String> courseDistinctSelected = new HashSet<String>(); private ArrayList<CourseStats> courseStats = new ArrayList<CourseStats>(); private ArrayList<CourseStats> courseStatsSelected = new ArrayList<CourseStats>(); private ArrayList<String> courseStr = new ArrayList<String>(); private String dirstr; public void read() { int i; int j; int k; int day; int counter; int hour; String cellstring; boolean merged; String cellinfo; String course; String classs; String classr; String sheetName; String sheetName2; int numOfSheets; int cindex; int cindex2; int index2; int prev=0; boolean added; Workbook workbook = null; JOptionPane.showMessageDialog(null, "Επιλέξτε το πρόγραμμα αφου το έχετε αποθηκεύσει ως .xls αρχείο."); JButton open = new JButton(); JFileChooser chooser= new JFileChooser(); chooser.setDialogTitle("Επιλογή προγραμματος"); if(chooser.showOpenDialog(open) == JFileChooser.CANCEL_OPTION) { System.exit(0); } Path xlPath = Paths.get(chooser.getSelectedFile().getAbsolutePath()); String path = xlPath.toString(); try { workbook = Workbook.getWorkbook(new File(path)); // Ανοιγουμε το εξελ σε μεταβλητη τυπου workbook και παιρνουμε στην μεταβλητη numOfSheets τα φυλλα του numOfSheets = workbook.getNumberOfSheets(); for(k=0;k<numOfSheets;k++) // για καθε φυλλο { Sheet sheet = workbook.getSheet(k); sheetName = sheet.getName(); // το ονομα του φυλλου περιεχει κατευθυνση και εξαμηνο οποτε κανουμε substring και τα αποκταμε cindex2 = sheetName.indexOf("'"); sheetName2 = sheetName.substring(0, cindex2); cindex = sheetName.indexOf('-'); sheetName = sheetName.substring(cindex+1); day = 0; j=2; counter = 0; merged = false; do { if(sheet.getCell(j,3).getCellFormat().getAlignment().getDescription().equals("centre")) // ελεγχοι για να δουμε αν καποιο cell ειναι merged { day++; } if(sheet.getCell(j,3).getCellFormat().getWrap()==false) { merged = true; } else { merged = false; } // σε περιπτωση που ειναι merged πρεπει να καταλαβουμε μεχρι που ειναι merged για να κανουμε copy paste την πληροφορια του original cell i=4; do{ Cell cell = sheet.getCell(j, i); cellstring = cell.toString(); if(cellstring.contains("Label") || cellstring.contains("Mul") || cellstring.contains("Blank")) { //ελεγχος για το αν το cell ειναι original (περιεχει πληροφοριες και δεν ειναι merged) hour = i+4; //ωρα course = ""; // μαθημα classs = "κοινό"; // κατευθυνση classr = ""; // αιθουσα if(cellstring.contains("Label")) { cellinfo = cell.getContents().trim().replaceAll(" +", " "); cindex = cellinfo.indexOf('('); course = cellinfo.substring(0, cindex); if(course.contains(" / "))// αποθηκευουμε τα ονοματα των μαθηματων πριν την παρενθεση που ξεκιναει ο κωδικος. Σασ συνιστω να εχετε και το excel διπλα να καταλαβαινετε τι λεω { course = course.replace("/", "-"); } if(cellinfo.contains("Τμήμα ")) { index2 = cellinfo.indexOf("Τμήμα "); classs = cellinfo.substring(index2 + 6,index2 + 7); } else if(cellinfo.contains("Τμήμα: ")) { index2 = cellinfo.indexOf("Τμήμα: "); classs = cellinfo.substring(index2 + 6,index2 + 7); } else if(cellinfo.contains("Τμήμα")) { index2 = cellinfo.indexOf("Τμήμα"); classs = cellinfo.substring(index2 + 6,index2 + 7); } else if(cellinfo.contains("Τμήμα:")) { index2 = cellinfo.indexOf("Τμήμα:"); classs = cellinfo.substring(index2 + 6,index2 + 7); // το τμημα το γραφουν με τους εξης διαφορετικους τροπους οποτε επρεπε να γινει σωστα το subsrting } if(cellinfo.contains("Αίθουσα ")) { index2 = cellinfo.indexOf("Αίθουσα "); classr = cellinfo.substring(index2); } if(cellinfo.contains("Αμφιθέατρο") && cellinfo.contains("ΚΕΥΠ")) { index2 = cellinfo.indexOf("Αμφιθέατρο"); classr = cellinfo.substring(index2); } else if(cellinfo.contains("ΚΕΥΠ")) { index2 = cellinfo.indexOf("ΚΕΥΠ"); classr = cellinfo.substring(index2); } else if(cellinfo.contains("Αμφιθέατρο ")) { index2 = cellinfo.indexOf("Αμφιθέατρο "); classr = cellinfo.substring(index2); } if(cellinfo.contains("Εργαστήριο ")) { index2 = cellinfo.indexOf("Εργαστήριο "); classr = cellinfo.substring(index2); } //το ιδιο και η αιθουσα if(classr.contains("\n")) { index2 = classr.indexOf("\n"); classr = classr.substring(0,index2); } if(cellinfo.contains("Φροντιστήριο")==false) { //δεν μας ενδιαφερουν τα φροντιστηριακα counter = 0; if(hour!=22) { courses.add(new Course(course,day,hour,classr,classs,sheetName2,sheetName)); //αποκτησαμε ολες τις πληροφοριες και δημιουργουμε το course } added = false; if(sheetName.equals("ΚΕΠ") || sheetName.equals("ΚΟΙΝΟ") ) { added = courseDistinct.add(course); } else if(sheetName.equals("ΚΔΤ") || sheetName.equals("ΚΟΙΝΟ")) { added = courseDistinctSelected.add(course); } if (added == true) { courseStats.add(new CourseStats(course,sheetName2,sheetName)); } prev=j; //εδω περα χρησιμοποιω ενα hashset για να δω αν μπορει να εισαχθει το στοιχειο τυπου CourseStat που //θα ειναι distinct και με την added την προσθετω σε ταξινομημενο arrayList } } if (cell.getCellFormat().getWrap() == false && cell.getCellFormat().getAlignment().getDescription().equals("general") && counter <2 && prev ==j) //ελεγχω αν ειναι merged αν εχει αλλαξει η μερα //και εαν τυχαινει να ειναι merged αλλα να ξεπερασει το τριωρο το μαθημα. σε μερικες μερες εχουμε merge στηλων και ηταν δυσκολο να γινει ο διαχωρισμος { counter++; course = courses.get(courses.size()-1).getName(); classs = courses.get(courses.size()-1).getClasss(); classr = courses.get(courses.size()-1).getClassr(); if(classs.equals("4") && (classr.contains("Εργαστήριο") || classr.contains("ΚΕΥΠ"))) { break; } if(hour!=22) { courses.add(new Course(course,day,hour,classr,classs,sheetName2,sheetName)); } added = false; if(sheetName.equals("ΚΕΠ") || sheetName.equals("ΚΟΙΝΟ")) { added = courseDistinct.add(course); } else if(sheetName.equals("ΚΔΤ") || sheetName.equals("ΚΟΙΝΟ")) { added = courseDistinctSelected.add(course); } if (added == true) { courseStats.add(new CourseStats(course,sheetName2,sheetName)); } } //παρομοιοι ελεγχοι για τα original cells } if(sheet.getCell(1,i).getCellFormat().getWrap() == true && sheet.getCell(1,i).getContents().equals("")) { break; } i++; //γραμμες if(i>17) { break; } }while(true); if(sheet.getCell(j,3).getContents().equals("")==true && merged == false) { break; } j++; //στηλες }while(true); } Collections.sort(courseStats); //sort } catch (IOException e) { e.printStackTrace(); } catch (BiffException e) { JOptionPane.showMessageDialog(null, "Λάθος αρχείο.","ERROR",JOptionPane.ERROR_MESSAGE); System.exit(1); e.printStackTrace(); } finally { if (workbook != null) { workbook.close(); } } } public ArrayList<Course> getCourses() { return courses; } public ArrayList<CourseStats> getCoursesStats() { return courseStats; } public void printCourses() { if(courses.size()>1) { for(int k=0;k<courses.size();k++) { System.out.println(courses.get(k).toString()); } } } public void printCoursesStats() { if(courseStats.size()>1) { for(int k=0;k<courseStats.size();k++) { System.out.println(courseStats.get(k).toString()); } } } public void setArrayString(ArrayList<String> anArray) { this.courseStr.addAll(anArray); } public void setSelectedDirection(String str) { dirstr = str; } public void writeSelectedCourses() { //serialize των επιλεγμενων μαθηματων απο την CheckboxGui for(int i=0;i<courseStr.size();i++) { String temp = courseStr.get(i).replace("\n",""); courseStr.remove(i); courseStr.add(i,temp); for(int j=0;j<courses.size();j++) { if(courseStr.get(i).equals(courses.get(j).getName()) && dirstr.equals(courses.get(j).getDirection())) { coursesSelected.add(courses.get(j)); } if(courseStr.get(i).equals(courses.get(j).getName()) && courses.get(j).getDirection().equals("ΚΟΙΝΟ")) { coursesSelected.add(courses.get(j)); } } for(int k=0;k<courseStats.size();k++) { if(courseStr.get(i).equals(courseStats.get(k).getName())) { courseStatsSelected.add(courseStats.get(k));; } } } try { FileOutputStream fileOut = new FileOutputStream("Course.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(coursesSelected); out.close(); fileOut.close(); } catch(IOException i) { i.printStackTrace(); } finally { System.out.println("Serialization Attempted..."); } try { FileOutputStream fileOut = new FileOutputStream("CourseStats.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(courseStatsSelected); out.close(); fileOut.close(); } catch(IOException i) { i.printStackTrace(); } finally { System.out.println("Serialization Attempted..."); } } }
GeorgeMichos13/MyUom
src/XlsReader.java
4,446
// ελεγχοι για να δουμε αν καποιο cell ειναι merged
line_comment
el
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; public class XlsReader { private ArrayList<Course> courses=new ArrayList<Course>(); private ArrayList<Course> coursesSelected=new ArrayList<Course>(); private HashSet<String> courseDistinct = new HashSet<String>(); private HashSet<String> courseDistinctSelected = new HashSet<String>(); private ArrayList<CourseStats> courseStats = new ArrayList<CourseStats>(); private ArrayList<CourseStats> courseStatsSelected = new ArrayList<CourseStats>(); private ArrayList<String> courseStr = new ArrayList<String>(); private String dirstr; public void read() { int i; int j; int k; int day; int counter; int hour; String cellstring; boolean merged; String cellinfo; String course; String classs; String classr; String sheetName; String sheetName2; int numOfSheets; int cindex; int cindex2; int index2; int prev=0; boolean added; Workbook workbook = null; JOptionPane.showMessageDialog(null, "Επιλέξτε το πρόγραμμα αφου το έχετε αποθηκεύσει ως .xls αρχείο."); JButton open = new JButton(); JFileChooser chooser= new JFileChooser(); chooser.setDialogTitle("Επιλογή προγραμματος"); if(chooser.showOpenDialog(open) == JFileChooser.CANCEL_OPTION) { System.exit(0); } Path xlPath = Paths.get(chooser.getSelectedFile().getAbsolutePath()); String path = xlPath.toString(); try { workbook = Workbook.getWorkbook(new File(path)); // Ανοιγουμε το εξελ σε μεταβλητη τυπου workbook και παιρνουμε στην μεταβλητη numOfSheets τα φυλλα του numOfSheets = workbook.getNumberOfSheets(); for(k=0;k<numOfSheets;k++) // για καθε φυλλο { Sheet sheet = workbook.getSheet(k); sheetName = sheet.getName(); // το ονομα του φυλλου περιεχει κατευθυνση και εξαμηνο οποτε κανουμε substring και τα αποκταμε cindex2 = sheetName.indexOf("'"); sheetName2 = sheetName.substring(0, cindex2); cindex = sheetName.indexOf('-'); sheetName = sheetName.substring(cindex+1); day = 0; j=2; counter = 0; merged = false; do { if(sheet.getCell(j,3).getCellFormat().getAlignment().getDescription().equals("centre")) // ελεγχοι για<SUF> { day++; } if(sheet.getCell(j,3).getCellFormat().getWrap()==false) { merged = true; } else { merged = false; } // σε περιπτωση που ειναι merged πρεπει να καταλαβουμε μεχρι που ειναι merged για να κανουμε copy paste την πληροφορια του original cell i=4; do{ Cell cell = sheet.getCell(j, i); cellstring = cell.toString(); if(cellstring.contains("Label") || cellstring.contains("Mul") || cellstring.contains("Blank")) { //ελεγχος για το αν το cell ειναι original (περιεχει πληροφοριες και δεν ειναι merged) hour = i+4; //ωρα course = ""; // μαθημα classs = "κοινό"; // κατευθυνση classr = ""; // αιθουσα if(cellstring.contains("Label")) { cellinfo = cell.getContents().trim().replaceAll(" +", " "); cindex = cellinfo.indexOf('('); course = cellinfo.substring(0, cindex); if(course.contains(" / "))// αποθηκευουμε τα ονοματα των μαθηματων πριν την παρενθεση που ξεκιναει ο κωδικος. Σασ συνιστω να εχετε και το excel διπλα να καταλαβαινετε τι λεω { course = course.replace("/", "-"); } if(cellinfo.contains("Τμήμα ")) { index2 = cellinfo.indexOf("Τμήμα "); classs = cellinfo.substring(index2 + 6,index2 + 7); } else if(cellinfo.contains("Τμήμα: ")) { index2 = cellinfo.indexOf("Τμήμα: "); classs = cellinfo.substring(index2 + 6,index2 + 7); } else if(cellinfo.contains("Τμήμα")) { index2 = cellinfo.indexOf("Τμήμα"); classs = cellinfo.substring(index2 + 6,index2 + 7); } else if(cellinfo.contains("Τμήμα:")) { index2 = cellinfo.indexOf("Τμήμα:"); classs = cellinfo.substring(index2 + 6,index2 + 7); // το τμημα το γραφουν με τους εξης διαφορετικους τροπους οποτε επρεπε να γινει σωστα το subsrting } if(cellinfo.contains("Αίθουσα ")) { index2 = cellinfo.indexOf("Αίθουσα "); classr = cellinfo.substring(index2); } if(cellinfo.contains("Αμφιθέατρο") && cellinfo.contains("ΚΕΥΠ")) { index2 = cellinfo.indexOf("Αμφιθέατρο"); classr = cellinfo.substring(index2); } else if(cellinfo.contains("ΚΕΥΠ")) { index2 = cellinfo.indexOf("ΚΕΥΠ"); classr = cellinfo.substring(index2); } else if(cellinfo.contains("Αμφιθέατρο ")) { index2 = cellinfo.indexOf("Αμφιθέατρο "); classr = cellinfo.substring(index2); } if(cellinfo.contains("Εργαστήριο ")) { index2 = cellinfo.indexOf("Εργαστήριο "); classr = cellinfo.substring(index2); } //το ιδιο και η αιθουσα if(classr.contains("\n")) { index2 = classr.indexOf("\n"); classr = classr.substring(0,index2); } if(cellinfo.contains("Φροντιστήριο")==false) { //δεν μας ενδιαφερουν τα φροντιστηριακα counter = 0; if(hour!=22) { courses.add(new Course(course,day,hour,classr,classs,sheetName2,sheetName)); //αποκτησαμε ολες τις πληροφοριες και δημιουργουμε το course } added = false; if(sheetName.equals("ΚΕΠ") || sheetName.equals("ΚΟΙΝΟ") ) { added = courseDistinct.add(course); } else if(sheetName.equals("ΚΔΤ") || sheetName.equals("ΚΟΙΝΟ")) { added = courseDistinctSelected.add(course); } if (added == true) { courseStats.add(new CourseStats(course,sheetName2,sheetName)); } prev=j; //εδω περα χρησιμοποιω ενα hashset για να δω αν μπορει να εισαχθει το στοιχειο τυπου CourseStat που //θα ειναι distinct και με την added την προσθετω σε ταξινομημενο arrayList } } if (cell.getCellFormat().getWrap() == false && cell.getCellFormat().getAlignment().getDescription().equals("general") && counter <2 && prev ==j) //ελεγχω αν ειναι merged αν εχει αλλαξει η μερα //και εαν τυχαινει να ειναι merged αλλα να ξεπερασει το τριωρο το μαθημα. σε μερικες μερες εχουμε merge στηλων και ηταν δυσκολο να γινει ο διαχωρισμος { counter++; course = courses.get(courses.size()-1).getName(); classs = courses.get(courses.size()-1).getClasss(); classr = courses.get(courses.size()-1).getClassr(); if(classs.equals("4") && (classr.contains("Εργαστήριο") || classr.contains("ΚΕΥΠ"))) { break; } if(hour!=22) { courses.add(new Course(course,day,hour,classr,classs,sheetName2,sheetName)); } added = false; if(sheetName.equals("ΚΕΠ") || sheetName.equals("ΚΟΙΝΟ")) { added = courseDistinct.add(course); } else if(sheetName.equals("ΚΔΤ") || sheetName.equals("ΚΟΙΝΟ")) { added = courseDistinctSelected.add(course); } if (added == true) { courseStats.add(new CourseStats(course,sheetName2,sheetName)); } } //παρομοιοι ελεγχοι για τα original cells } if(sheet.getCell(1,i).getCellFormat().getWrap() == true && sheet.getCell(1,i).getContents().equals("")) { break; } i++; //γραμμες if(i>17) { break; } }while(true); if(sheet.getCell(j,3).getContents().equals("")==true && merged == false) { break; } j++; //στηλες }while(true); } Collections.sort(courseStats); //sort } catch (IOException e) { e.printStackTrace(); } catch (BiffException e) { JOptionPane.showMessageDialog(null, "Λάθος αρχείο.","ERROR",JOptionPane.ERROR_MESSAGE); System.exit(1); e.printStackTrace(); } finally { if (workbook != null) { workbook.close(); } } } public ArrayList<Course> getCourses() { return courses; } public ArrayList<CourseStats> getCoursesStats() { return courseStats; } public void printCourses() { if(courses.size()>1) { for(int k=0;k<courses.size();k++) { System.out.println(courses.get(k).toString()); } } } public void printCoursesStats() { if(courseStats.size()>1) { for(int k=0;k<courseStats.size();k++) { System.out.println(courseStats.get(k).toString()); } } } public void setArrayString(ArrayList<String> anArray) { this.courseStr.addAll(anArray); } public void setSelectedDirection(String str) { dirstr = str; } public void writeSelectedCourses() { //serialize των επιλεγμενων μαθηματων απο την CheckboxGui for(int i=0;i<courseStr.size();i++) { String temp = courseStr.get(i).replace("\n",""); courseStr.remove(i); courseStr.add(i,temp); for(int j=0;j<courses.size();j++) { if(courseStr.get(i).equals(courses.get(j).getName()) && dirstr.equals(courses.get(j).getDirection())) { coursesSelected.add(courses.get(j)); } if(courseStr.get(i).equals(courses.get(j).getName()) && courses.get(j).getDirection().equals("ΚΟΙΝΟ")) { coursesSelected.add(courses.get(j)); } } for(int k=0;k<courseStats.size();k++) { if(courseStr.get(i).equals(courseStats.get(k).getName())) { courseStatsSelected.add(courseStats.get(k));; } } } try { FileOutputStream fileOut = new FileOutputStream("Course.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(coursesSelected); out.close(); fileOut.close(); } catch(IOException i) { i.printStackTrace(); } finally { System.out.println("Serialization Attempted..."); } try { FileOutputStream fileOut = new FileOutputStream("CourseStats.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(courseStatsSelected); out.close(); fileOut.close(); } catch(IOException i) { i.printStackTrace(); } finally { System.out.println("Serialization Attempted..."); } } }
6291_0
package gr.conference.menus; import java.util.Scanner; public class StartingScreen { public String user; public StartingScreen() { loadMenu(); } private void loadMenu() { Scanner scanner = new Scanner(System.in); int flag = 0; LoginPage lp = new LoginPage(); System.out.println("------------------------------------------"); System.out.println("WELCOME TO THE CONFERENCE SYSTEM USER PAGE"); while(flag == 0) { System.out.println("1. LOGIN"); System.out.println("2. REGISTER"); System.out.println("3. CONTINUE AS GUEST"); System.out.println("4. ADMIN LOGIN"); System.out.println("5. EXIT"); System.out.print("Your input >"); int input = scanner.nextInt(); switch(input) { case 1: flag = 1; lp.loadPageUser(); break; case 2: flag = 1; RegisterPage rp = new RegisterPage(); break; case 3: flag = 1; //TODO Φτιάξε τι θα γίνεται σε περίπτωση visitor. break; case 4: flag =1; lp.loadPageAdmin(); break; case 5: flag = 1; System.exit(0); break; default: flag = 0; break; } } } public String getUser() { return user; } }
Georgezach24/Project-soft
OneDrive/Desktop/5th Semester/Soft. Eng/final/sys/src/main/java/gr/conference/menus/StartingScreen.java
424
//TODO Φτιάξε τι θα γίνεται σε περίπτωση visitor.
line_comment
el
package gr.conference.menus; import java.util.Scanner; public class StartingScreen { public String user; public StartingScreen() { loadMenu(); } private void loadMenu() { Scanner scanner = new Scanner(System.in); int flag = 0; LoginPage lp = new LoginPage(); System.out.println("------------------------------------------"); System.out.println("WELCOME TO THE CONFERENCE SYSTEM USER PAGE"); while(flag == 0) { System.out.println("1. LOGIN"); System.out.println("2. REGISTER"); System.out.println("3. CONTINUE AS GUEST"); System.out.println("4. ADMIN LOGIN"); System.out.println("5. EXIT"); System.out.print("Your input >"); int input = scanner.nextInt(); switch(input) { case 1: flag = 1; lp.loadPageUser(); break; case 2: flag = 1; RegisterPage rp = new RegisterPage(); break; case 3: flag = 1; //TODO Φτιάξε<SUF> break; case 4: flag =1; lp.loadPageAdmin(); break; case 5: flag = 1; System.exit(0); break; default: flag = 0; break; } } } public String getUser() { return user; } }
8394_14
package com.example.brick_breaker_game; import javafx.animation.Animation; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.geometry.Bounds; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Label; import javafx.scene.layout.AnchorPane; import javafx.scene.paint.Color; import javafx.scene.paint.PhongMaterial; import javafx.scene.shape.Rectangle; import javafx.scene.shape.Sphere; import javafx.scene.text.Font; import javafx.util.Duration; import java.net.URL; import java.util.ArrayList; import java.util.Random; import java.util.ResourceBundle; public class Controller implements Initializable { @FXML private Rectangle rod; @FXML private Sphere ball; @FXML protected int deltaX = 10, deltaY = -5, scoreCounter = 0, rodSpeed = 65, minX = 10, maxX = 12, minY = 8, maxY = 10, maxA = 360, minA = 180; @FXML private final ArrayList<Rectangle> bricks = new ArrayList<>(); @FXML private AnchorPane scene; @FXML private Label score; @FXML Random rand = new Random(); @FXML private Canvas canvas; @FXML PhongMaterial material = new PhongMaterial(); Timeline timeline = new Timeline(new KeyFrame(Duration.millis(50), new EventHandler<>() { @Override public void handle(ActionEvent event) { Bounds bounds = scene.getBoundsInLocal(); //Δίνει κίνηση στην μπάλα ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA); ball.setTranslateX(ball.getTranslateX() + deltaX ); ball.setTranslateY(ball.getTranslateY() + deltaY ); //Όταν πάει να βγει από τα όρια της οθόνης η μπάλα αναπηδάει if(ball.getTranslateX() >= (bounds.getMaxX()/2) - ball.getRadius()) { ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA); deltaX = -1 * (rand.nextInt(maxX + 1 - minX) + minX); ball.setTranslateX(ball.getTranslateX() + deltaX); scoreCounter += 2; score.setText("Score: " + scoreCounter); }else if( ball.getTranslateX() <= (-bounds.getMaxX()/2) + ball.getRadius()){ ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA); deltaX = (rand.nextInt(maxX + 1 - minX) + minX); ball.setTranslateX(ball.getTranslateX() + deltaX); scoreCounter += 2; score.setText("Score: " + scoreCounter); } if (ball.getTranslateY() <= (-bounds.getMaxY()/2) + ball.getRadius()){ ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA); deltaY = (rand.nextInt(maxY + 1 - minY) + minY); ball.setTranslateY(ball.getTranslateY() + deltaY); scoreCounter += 2; score.setText("Score: " + scoreCounter); } //Αναγνωρίζει αν η μπάλα ακούμπησε την μπάρα αναπηδάει if(ball.getBoundsInParent().intersects(rod.getBoundsInParent())){ ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA); deltaY = -1 * (rand.nextInt(maxY + 1 - minY) + minY); ball.setRotate(rand.nextInt(360)); ball.setTranslateY(ball.getTranslateY() + deltaY); //Ανεβάζει το σκορ scoreCounter += 5; score.setText("Score: " + scoreCounter); } //Αν η μπάλα πάει στο κάτω μέρος της οθόνης ο παίκτης χάνει και τελειώνει το παιχνίδι if (ball.getTranslateY() >= (bounds.getMaxY()/2) - ball.getRadius()) { timeline.stop(); //Εμφανίζει το μήνυμα στην οθόνη GraphicsContext gc = canvas.getGraphicsContext2D(); gc.setFill(Color.BLACK); gc.setFont(new Font("", 40)); gc.fillText("GAME OVER!! Your score is: " + scoreCounter, 50, 300); } //Αν υπάρχουν ακόμη τουβλάκια στη λίστα το παιχνίδι συνεχίζεται αφαιρώντας το τουβλάκι που ακούμπησε η μπάλα if(!bricks.isEmpty()){ bricks.removeIf(brick -> checkCollisionBricks(brick)); //Διαφορετικά ο παίκτης κερδίζει το παιχνίδι } else { timeline.stop(); GraphicsContext gc = canvas.getGraphicsContext2D(); gc.setFill(Color.BLACK); gc.setFont(new Font("", 40)); gc.fillText("YOU WON!! Your score is: " + scoreCounter, 50, 300); } } })); //Ρυθμίζει την πορεία της μπάλας όταν χτυπάει στα τουβλάκια. Αν αφαιρεθεί τουβλάκι η συνάρτηση επιστρέφει true public boolean checkCollisionBricks(Rectangle brick){ if(ball.getBoundsInParent().intersects(brick.getBoundsInParent())){ boolean rightBorder = ball.getLayoutX() >= ((brick.getX() + brick.getWidth()) - ball.getRadius()); boolean leftBorder = ball.getLayoutX() <= (brick.getX() + ball.getRadius()); boolean bottomBorder = ball.getLayoutY() >= ((brick.getY() + brick.getHeight()) - ball.getRadius()); boolean topBorder = ball.getLayoutY() <= (brick.getY() + ball.getRadius()); if (rightBorder || leftBorder) { ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA); deltaX *= -1; } if (bottomBorder || topBorder) { ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA); deltaY *= -1; } scene.getChildren().remove(brick);//Αφαιρεί το τουβλάκι από την οθόνη όταν το ακουμπήσει η μπάλα scoreCounter += 10; score.setText("Score: " + scoreCounter); return true; } return false; } //Για να κινείται η μπάρα προς τα δεξιά public void moveRight(){ Bounds bounds = scene.getBoundsInLocal(); //Ρυθμίζει την ταχύτητα κίνησης //Αλλάζει τη θέση του rod.setTranslateX(rod.getTranslateX() + rodSpeed); //Άμα φτάσει στο όριο της οθόνης εμφανίζεται από την άλλη μεριά if(rod.getTranslateX() >= (bounds.getMaxX()/2)){ rod.setTranslateX(rod.getTranslateX() - rodSpeed); } } public void moveLeft() { Bounds bounds = scene.getBoundsInLocal(); rod.setTranslateX(rod.getTranslateX() - rodSpeed); if(rod.getTranslateX() <= (-(bounds.getMaxX()/2))){ rod.setTranslateX(rod.getTranslateX() + rodSpeed); } } @FXML //Εμφανίζει τα τουβλάκια στην οθόνη private void createBricks(){ double width = 640; double height = 200; int spaceCheck = 1; for (double i = height; i > 0 ; i = i - 40) { for (double j = width; j > 0 ; j = j - 15) { if(spaceCheck % 3 == 0){ Rectangle brick = new Rectangle(j,i,40,15); brick.setFill(Color.FIREBRICK); scene.getChildren().add(brick); bricks.add(brick); } spaceCheck++; } } } @Override public void initialize(URL url, ResourceBundle resourceBundle) { material.setDiffuseColor(Color.YELLOW); material.setSpecularColor(Color.BLACK); ball.setMaterial(material); score.setText("Score: " + scoreCounter); createBricks(); timeline.setCycleCount(Animation.INDEFINITE); timeline.play(); } }
Giannis1273646/Brick-Breaker-Game
src/main/java/com/example/brick_breaker_game/Controller.java
2,486
//Εμφανίζει τα τουβλάκια στην οθόνη
line_comment
el
package com.example.brick_breaker_game; import javafx.animation.Animation; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.geometry.Bounds; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Label; import javafx.scene.layout.AnchorPane; import javafx.scene.paint.Color; import javafx.scene.paint.PhongMaterial; import javafx.scene.shape.Rectangle; import javafx.scene.shape.Sphere; import javafx.scene.text.Font; import javafx.util.Duration; import java.net.URL; import java.util.ArrayList; import java.util.Random; import java.util.ResourceBundle; public class Controller implements Initializable { @FXML private Rectangle rod; @FXML private Sphere ball; @FXML protected int deltaX = 10, deltaY = -5, scoreCounter = 0, rodSpeed = 65, minX = 10, maxX = 12, minY = 8, maxY = 10, maxA = 360, minA = 180; @FXML private final ArrayList<Rectangle> bricks = new ArrayList<>(); @FXML private AnchorPane scene; @FXML private Label score; @FXML Random rand = new Random(); @FXML private Canvas canvas; @FXML PhongMaterial material = new PhongMaterial(); Timeline timeline = new Timeline(new KeyFrame(Duration.millis(50), new EventHandler<>() { @Override public void handle(ActionEvent event) { Bounds bounds = scene.getBoundsInLocal(); //Δίνει κίνηση στην μπάλα ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA); ball.setTranslateX(ball.getTranslateX() + deltaX ); ball.setTranslateY(ball.getTranslateY() + deltaY ); //Όταν πάει να βγει από τα όρια της οθόνης η μπάλα αναπηδάει if(ball.getTranslateX() >= (bounds.getMaxX()/2) - ball.getRadius()) { ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA); deltaX = -1 * (rand.nextInt(maxX + 1 - minX) + minX); ball.setTranslateX(ball.getTranslateX() + deltaX); scoreCounter += 2; score.setText("Score: " + scoreCounter); }else if( ball.getTranslateX() <= (-bounds.getMaxX()/2) + ball.getRadius()){ ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA); deltaX = (rand.nextInt(maxX + 1 - minX) + minX); ball.setTranslateX(ball.getTranslateX() + deltaX); scoreCounter += 2; score.setText("Score: " + scoreCounter); } if (ball.getTranslateY() <= (-bounds.getMaxY()/2) + ball.getRadius()){ ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA); deltaY = (rand.nextInt(maxY + 1 - minY) + minY); ball.setTranslateY(ball.getTranslateY() + deltaY); scoreCounter += 2; score.setText("Score: " + scoreCounter); } //Αναγνωρίζει αν η μπάλα ακούμπησε την μπάρα αναπηδάει if(ball.getBoundsInParent().intersects(rod.getBoundsInParent())){ ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA); deltaY = -1 * (rand.nextInt(maxY + 1 - minY) + minY); ball.setRotate(rand.nextInt(360)); ball.setTranslateY(ball.getTranslateY() + deltaY); //Ανεβάζει το σκορ scoreCounter += 5; score.setText("Score: " + scoreCounter); } //Αν η μπάλα πάει στο κάτω μέρος της οθόνης ο παίκτης χάνει και τελειώνει το παιχνίδι if (ball.getTranslateY() >= (bounds.getMaxY()/2) - ball.getRadius()) { timeline.stop(); //Εμφανίζει το μήνυμα στην οθόνη GraphicsContext gc = canvas.getGraphicsContext2D(); gc.setFill(Color.BLACK); gc.setFont(new Font("", 40)); gc.fillText("GAME OVER!! Your score is: " + scoreCounter, 50, 300); } //Αν υπάρχουν ακόμη τουβλάκια στη λίστα το παιχνίδι συνεχίζεται αφαιρώντας το τουβλάκι που ακούμπησε η μπάλα if(!bricks.isEmpty()){ bricks.removeIf(brick -> checkCollisionBricks(brick)); //Διαφορετικά ο παίκτης κερδίζει το παιχνίδι } else { timeline.stop(); GraphicsContext gc = canvas.getGraphicsContext2D(); gc.setFill(Color.BLACK); gc.setFont(new Font("", 40)); gc.fillText("YOU WON!! Your score is: " + scoreCounter, 50, 300); } } })); //Ρυθμίζει την πορεία της μπάλας όταν χτυπάει στα τουβλάκια. Αν αφαιρεθεί τουβλάκι η συνάρτηση επιστρέφει true public boolean checkCollisionBricks(Rectangle brick){ if(ball.getBoundsInParent().intersects(brick.getBoundsInParent())){ boolean rightBorder = ball.getLayoutX() >= ((brick.getX() + brick.getWidth()) - ball.getRadius()); boolean leftBorder = ball.getLayoutX() <= (brick.getX() + ball.getRadius()); boolean bottomBorder = ball.getLayoutY() >= ((brick.getY() + brick.getHeight()) - ball.getRadius()); boolean topBorder = ball.getLayoutY() <= (brick.getY() + ball.getRadius()); if (rightBorder || leftBorder) { ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA); deltaX *= -1; } if (bottomBorder || topBorder) { ball.setRotate(rand.nextInt(maxA + 1 - minA) + minA); deltaY *= -1; } scene.getChildren().remove(brick);//Αφαιρεί το τουβλάκι από την οθόνη όταν το ακουμπήσει η μπάλα scoreCounter += 10; score.setText("Score: " + scoreCounter); return true; } return false; } //Για να κινείται η μπάρα προς τα δεξιά public void moveRight(){ Bounds bounds = scene.getBoundsInLocal(); //Ρυθμίζει την ταχύτητα κίνησης //Αλλάζει τη θέση του rod.setTranslateX(rod.getTranslateX() + rodSpeed); //Άμα φτάσει στο όριο της οθόνης εμφανίζεται από την άλλη μεριά if(rod.getTranslateX() >= (bounds.getMaxX()/2)){ rod.setTranslateX(rod.getTranslateX() - rodSpeed); } } public void moveLeft() { Bounds bounds = scene.getBoundsInLocal(); rod.setTranslateX(rod.getTranslateX() - rodSpeed); if(rod.getTranslateX() <= (-(bounds.getMaxX()/2))){ rod.setTranslateX(rod.getTranslateX() + rodSpeed); } } @FXML //Εμφανίζει τα<SUF> private void createBricks(){ double width = 640; double height = 200; int spaceCheck = 1; for (double i = height; i > 0 ; i = i - 40) { for (double j = width; j > 0 ; j = j - 15) { if(spaceCheck % 3 == 0){ Rectangle brick = new Rectangle(j,i,40,15); brick.setFill(Color.FIREBRICK); scene.getChildren().add(brick); bricks.add(brick); } spaceCheck++; } } } @Override public void initialize(URL url, ResourceBundle resourceBundle) { material.setDiffuseColor(Color.YELLOW); material.setSpecularColor(Color.BLACK); ball.setMaterial(material); score.setText("Score: " + scoreCounter); createBricks(); timeline.setCycleCount(Animation.INDEFINITE); timeline.play(); } }
3410_34
package sample; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.stage.Stage; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.ResourceBundle; public class SinglePlayerController implements Initializable { @FXML private ComboBox<String> menu; @FXML String s = "."; @FXML private Label label, label1, label2; @FXML private TextField textField; @FXML private char[] wordsLetters; @FXML ArrayList<String> word = new ArrayList<>(); @FXML public int counter, tries = 7; @FXML private ImageView img; @FXML private Button button, playAgainB, menuB; @FXML private void menu(ActionEvent event) throws IOException { //Παίρνει την επιλογή του χρήστη String choice = menu.getValue(); //Επιστρέφει στο αρχικό μενού if(choice.equals("Επιστροφή στο κύριο μενού")){ Parent singlePlayerParent = FXMLLoader.load(getClass().getResource("sample.fxml")); Scene singlePlayerScene = new Scene(singlePlayerParent); //This line gets the stage information Stage window = (Stage)((Node)event.getSource()).getScene().getWindow(); window.setScene(singlePlayerScene); window.setTitle("Menu"); window.show(); }else{ Platform.exit(); } } @FXML private void getLetters(ActionEvent event){ boolean found = false; //Παίρνει από το textField το γράμμα που δίνει ο χρήστης String letter = textField.getText(); textField.clear(); switch (letter){ case "α": for(int i = 0; i< wordsLetters.length; i++) { if (letter.equals(String.valueOf(wordsLetters[i])) || "ά".equals(String.valueOf(wordsLetters[i]))){ //Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης word.set(i,String.valueOf(wordsLetters[i])); //‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση wordsLetters[i] ='.'; counter--; found = true; } } break; case "ε": for(int i = 0; i< wordsLetters.length; i++) { if (letter.equals(String.valueOf(wordsLetters[i])) || "έ".equals(String.valueOf(wordsLetters[i]))){ //Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης word.set(i,String.valueOf(wordsLetters[i])); //‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση wordsLetters[i] ='.'; counter--; found = true; } } break; case "ι": for(int i = 0; i< wordsLetters.length; i++) { if (letter.equals(String.valueOf(wordsLetters[i])) || "ί".equals(String.valueOf(wordsLetters[i]))){ //Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης word.set(i,String.valueOf(wordsLetters[i])); //‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση wordsLetters[i] ='.'; counter--; found = true; } } break; case "η": for(int i = 0; i< wordsLetters.length; i++) { if (letter.equals(String.valueOf(wordsLetters[i])) || "ή".equals(String.valueOf(wordsLetters[i]))){ //Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης word.set(i,String.valueOf(wordsLetters[i])); //‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση wordsLetters[i] ='.'; counter--; found = true; } } break; case "υ": for(int i = 0; i< wordsLetters.length; i++) { if (letter.equals(String.valueOf(wordsLetters[i])) || "ύ".equals(String.valueOf(wordsLetters[i]))){ //Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης word.set(i,String.valueOf(wordsLetters[i])); //‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση wordsLetters[i] ='.'; counter--; found = true; } } break; case "ο": for(int i = 0; i< wordsLetters.length; i++) { if (letter.equals(String.valueOf(wordsLetters[i])) || "ό".equals(String.valueOf(wordsLetters[i]))){ //Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης word.set(i,String.valueOf(wordsLetters[i])); //‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση wordsLetters[i] ='.'; counter--; found = true; } } break; case "ω": for(int i = 0; i< wordsLetters.length; i++) { if (letter.equals(String.valueOf(wordsLetters[i])) || "ώ".equals(String.valueOf(wordsLetters[i]))){ //Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης word.set(i,String.valueOf(wordsLetters[i])); //‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση wordsLetters[i] ='.'; counter--; found = true; } } break; default: for(int i = 0; i< wordsLetters.length; i++) { if (letter.equals(String.valueOf(wordsLetters[i]))) { //Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης word.set(i,letter); //‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση wordsLetters[i] ='.'; counter--; found = true; } } } //Άμα δεν έχει βρεθεί το γράμμα το εμφανίζει στα γράμματα που έχουν χρησιμοποιηθεί και αφαιρεί μία ζωή if (!found){ label1.setText(label1.getText() + letter +" ,"); tries--; } //Εμφανίζει τα γράμματα στο label από το ArrayList word label.setText(""); for (int i = 0; i< wordsLetters.length; i++){ label.setText(label.getText() + word.get(i)); } //Εμφανίζει το ανθρωπάκι μέσω εικόνων switch (tries){ case 6: img.setImage(new Image("resources/try2.png")); break; case 5: img.setImage(new Image("resources/try3.png")); break; case 4: img.setImage(new Image("resources/try4.png")); break; case 3: img.setImage(new Image("resources/try5.png")); break; case 2: img.setImage(new Image("resources/try6.png")); break; case 1: img.setImage(new Image("resources/try7.png")); break; case 0: //Αν τελειώσουν οι προσπάθειες το πρόγραμμα τερματίζει label.setText(""); //Για να εμφανίζεται η λέξη όταν χάσει ο παίκτης for (int i=0; i<wordsLetters.length; i++){ if(s.equals(String.valueOf(wordsLetters[i]))){ label.setText(label.getText() + word.get(i)); }else { label.setText(label.getText() + wordsLetters[i]); } } //Εμφανίζονται κάποιες επιπλέον επιλογές αφού έχει τελειώσει το πρόγραμμα label2.setVisible(true); textField.setEditable(false); button.setVisible(false); playAgainB.setVisible(true); menuB.setVisible(true); break; } //Αφορά την στιγμή που ο χρήστης βρίσκει την λέξη if (counter==1){ label2.setText("You Won"); label2.setVisible(true); textField.setEditable(false); button.setVisible(false); playAgainB.setVisible(true); menuB.setVisible(true); } } @FXML //Ξεκινάει το πρόγραμμα από την αρχή private void playAgain(ActionEvent event) throws IOException { Parent singlePlayerParent = FXMLLoader.load(getClass().getResource("SinglePlayer.fxml")); Scene singlePlayerScene = new Scene(singlePlayerParent,683, 373.6); //This line gets the stage information Stage window = (Stage)((Node)event.getSource()).getScene().getWindow(); window.setScene(singlePlayerScene); window.setTitle("Single Player"); window.show(); } @FXML //Επιστρέφει στο μενού private void returnMenu(ActionEvent event) throws IOException { Parent singlePlayerParent = FXMLLoader.load(getClass().getResource("sample.fxml")); Scene singlePlayerScene = new Scene(singlePlayerParent); //This line gets the stage information Stage window = (Stage)((Node)event.getSource()).getScene().getWindow(); window.setScene(singlePlayerScene); window.setTitle("Menu"); window.show(); } @Override public void initialize(URL url, ResourceBundle resourceBundle) { menu.getItems().addAll("Επιστροφή στο κύριο μενού", "Έξοδος"); label2.setVisible(false); playAgainB.setVisible(false); menuB.setVisible(false); //Για να δέχεται γράμματα Ελληνικά με τόνους και Αγγλικά textField.textProperty().addListener((observable, oldValue, newValue) -> { if (!newValue.matches("\\sα-ωΑ-Ωά-ώ*")) { textField.setText(newValue.replaceAll("[^\\sA-Zά-ώ]", "")); } }); //Για να δέχεται μόνο ένα γράμμα textField.setTextFormatter(new TextFormatter<String>((TextFormatter.Change change) -> { String newText = change.getControlNewText(); if (newText.length() > 1) { return null; } else { return change; } })); //Ορισμός του πίνακα με τις λέξεις του παιχνιδιού και αντιγραφή σε ένα ArrayList , για την εύκολη ανακάτεψή τους String[] EnglishWords = {"αγαλλίαση", "Αλόννησος", "αναστήλωση", "ανέγγιχτος", "ανδρεία", "αστοιχείωτος", "βδελυρός","βερίκοκο", "βυσσοδομώ","γάγγραινα", "γιατρειά", "γλαφυρός", "γλιτώνω ", "δεισιδαιμονία", "διαπρύσιοι ", "διευκρίνιση", "δοκησίσοφος", "δωσίλογος", "εγκάθειρκτος", "εκεχειρία", "έκπαγλος", "ελλιπής", "εμπεριστατωμένος","εξαπίνης", "καταμεσής", "κλαυθμυρίζω", "κνώδαλο", "κομπορρημοσύνη", "κρησφύγετο", "κωδίκελος", "λέκιθος", "λήκυθος", "λογύδριο", "λυθρίνι", "μεγαλεπήβολος", "μυδράλιο", "μυκτηρίζω", "νηπενθής", "ξένοιαστος", "φερέγγυος", "χρεοκοπία", "τετριμμένος", "συνονθύλευμα"}; ArrayList<String> Words = new ArrayList<>(); Collections.addAll(Words, EnglishWords); //Ανακατεύει το ArrayList Collections.shuffle(Words); //Αποθήκευση της πρώτης λέξης του σε μία μεταβλητή τύπου String και αφαίρεση από την λίστα String magicWord = Words.get(0); Words.remove(0); // Copy character by character into array wordsLetters = magicWord.toCharArray(); //Αρχικοποίηση της μεταβλητής για να ξέρουμε πότε ο χρήστης θα βρει την λέξη counter = wordsLetters.length; //Για να εμφανίζεται το πρώτο γράμμα της λέξης word.add(0, String.valueOf(wordsLetters[0])); wordsLetters[0] = '.'; //Για να εμφανίζονται οι παύλες των γραμμάτων που δεν έχει βρει ο χρήστης for (int i = 1; i <= wordsLetters.length; i++) { word.add(" _"); label.setText(label.getText() + word.get(i - 1)); } } }
Giannis1273646/Hangman-Game
src/sample/SinglePlayerController.java
4,870
//Ανακατεύει το ArrayList
line_comment
el
package sample; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.stage.Stage; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.ResourceBundle; public class SinglePlayerController implements Initializable { @FXML private ComboBox<String> menu; @FXML String s = "."; @FXML private Label label, label1, label2; @FXML private TextField textField; @FXML private char[] wordsLetters; @FXML ArrayList<String> word = new ArrayList<>(); @FXML public int counter, tries = 7; @FXML private ImageView img; @FXML private Button button, playAgainB, menuB; @FXML private void menu(ActionEvent event) throws IOException { //Παίρνει την επιλογή του χρήστη String choice = menu.getValue(); //Επιστρέφει στο αρχικό μενού if(choice.equals("Επιστροφή στο κύριο μενού")){ Parent singlePlayerParent = FXMLLoader.load(getClass().getResource("sample.fxml")); Scene singlePlayerScene = new Scene(singlePlayerParent); //This line gets the stage information Stage window = (Stage)((Node)event.getSource()).getScene().getWindow(); window.setScene(singlePlayerScene); window.setTitle("Menu"); window.show(); }else{ Platform.exit(); } } @FXML private void getLetters(ActionEvent event){ boolean found = false; //Παίρνει από το textField το γράμμα που δίνει ο χρήστης String letter = textField.getText(); textField.clear(); switch (letter){ case "α": for(int i = 0; i< wordsLetters.length; i++) { if (letter.equals(String.valueOf(wordsLetters[i])) || "ά".equals(String.valueOf(wordsLetters[i]))){ //Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης word.set(i,String.valueOf(wordsLetters[i])); //‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση wordsLetters[i] ='.'; counter--; found = true; } } break; case "ε": for(int i = 0; i< wordsLetters.length; i++) { if (letter.equals(String.valueOf(wordsLetters[i])) || "έ".equals(String.valueOf(wordsLetters[i]))){ //Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης word.set(i,String.valueOf(wordsLetters[i])); //‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση wordsLetters[i] ='.'; counter--; found = true; } } break; case "ι": for(int i = 0; i< wordsLetters.length; i++) { if (letter.equals(String.valueOf(wordsLetters[i])) || "ί".equals(String.valueOf(wordsLetters[i]))){ //Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης word.set(i,String.valueOf(wordsLetters[i])); //‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση wordsLetters[i] ='.'; counter--; found = true; } } break; case "η": for(int i = 0; i< wordsLetters.length; i++) { if (letter.equals(String.valueOf(wordsLetters[i])) || "ή".equals(String.valueOf(wordsLetters[i]))){ //Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης word.set(i,String.valueOf(wordsLetters[i])); //‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση wordsLetters[i] ='.'; counter--; found = true; } } break; case "υ": for(int i = 0; i< wordsLetters.length; i++) { if (letter.equals(String.valueOf(wordsLetters[i])) || "ύ".equals(String.valueOf(wordsLetters[i]))){ //Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης word.set(i,String.valueOf(wordsLetters[i])); //‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση wordsLetters[i] ='.'; counter--; found = true; } } break; case "ο": for(int i = 0; i< wordsLetters.length; i++) { if (letter.equals(String.valueOf(wordsLetters[i])) || "ό".equals(String.valueOf(wordsLetters[i]))){ //Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης word.set(i,String.valueOf(wordsLetters[i])); //‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση wordsLetters[i] ='.'; counter--; found = true; } } break; case "ω": for(int i = 0; i< wordsLetters.length; i++) { if (letter.equals(String.valueOf(wordsLetters[i])) || "ώ".equals(String.valueOf(wordsLetters[i]))){ //Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης word.set(i,String.valueOf(wordsLetters[i])); //‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση wordsLetters[i] ='.'; counter--; found = true; } } break; default: for(int i = 0; i< wordsLetters.length; i++) { if (letter.equals(String.valueOf(wordsLetters[i]))) { //Προσθέτει το γράμμα σε ένα νέο ArrayList που περιέχει τα γράμματα που έχει βρει ο χρήστης word.set(i,letter); //‘’Αφαιρεί’’ το γράμμα από τον πίνακα για να μην το ξαναβρίσκει στην επόμενη αναζήτηση wordsLetters[i] ='.'; counter--; found = true; } } } //Άμα δεν έχει βρεθεί το γράμμα το εμφανίζει στα γράμματα που έχουν χρησιμοποιηθεί και αφαιρεί μία ζωή if (!found){ label1.setText(label1.getText() + letter +" ,"); tries--; } //Εμφανίζει τα γράμματα στο label από το ArrayList word label.setText(""); for (int i = 0; i< wordsLetters.length; i++){ label.setText(label.getText() + word.get(i)); } //Εμφανίζει το ανθρωπάκι μέσω εικόνων switch (tries){ case 6: img.setImage(new Image("resources/try2.png")); break; case 5: img.setImage(new Image("resources/try3.png")); break; case 4: img.setImage(new Image("resources/try4.png")); break; case 3: img.setImage(new Image("resources/try5.png")); break; case 2: img.setImage(new Image("resources/try6.png")); break; case 1: img.setImage(new Image("resources/try7.png")); break; case 0: //Αν τελειώσουν οι προσπάθειες το πρόγραμμα τερματίζει label.setText(""); //Για να εμφανίζεται η λέξη όταν χάσει ο παίκτης for (int i=0; i<wordsLetters.length; i++){ if(s.equals(String.valueOf(wordsLetters[i]))){ label.setText(label.getText() + word.get(i)); }else { label.setText(label.getText() + wordsLetters[i]); } } //Εμφανίζονται κάποιες επιπλέον επιλογές αφού έχει τελειώσει το πρόγραμμα label2.setVisible(true); textField.setEditable(false); button.setVisible(false); playAgainB.setVisible(true); menuB.setVisible(true); break; } //Αφορά την στιγμή που ο χρήστης βρίσκει την λέξη if (counter==1){ label2.setText("You Won"); label2.setVisible(true); textField.setEditable(false); button.setVisible(false); playAgainB.setVisible(true); menuB.setVisible(true); } } @FXML //Ξεκινάει το πρόγραμμα από την αρχή private void playAgain(ActionEvent event) throws IOException { Parent singlePlayerParent = FXMLLoader.load(getClass().getResource("SinglePlayer.fxml")); Scene singlePlayerScene = new Scene(singlePlayerParent,683, 373.6); //This line gets the stage information Stage window = (Stage)((Node)event.getSource()).getScene().getWindow(); window.setScene(singlePlayerScene); window.setTitle("Single Player"); window.show(); } @FXML //Επιστρέφει στο μενού private void returnMenu(ActionEvent event) throws IOException { Parent singlePlayerParent = FXMLLoader.load(getClass().getResource("sample.fxml")); Scene singlePlayerScene = new Scene(singlePlayerParent); //This line gets the stage information Stage window = (Stage)((Node)event.getSource()).getScene().getWindow(); window.setScene(singlePlayerScene); window.setTitle("Menu"); window.show(); } @Override public void initialize(URL url, ResourceBundle resourceBundle) { menu.getItems().addAll("Επιστροφή στο κύριο μενού", "Έξοδος"); label2.setVisible(false); playAgainB.setVisible(false); menuB.setVisible(false); //Για να δέχεται γράμματα Ελληνικά με τόνους και Αγγλικά textField.textProperty().addListener((observable, oldValue, newValue) -> { if (!newValue.matches("\\sα-ωΑ-Ωά-ώ*")) { textField.setText(newValue.replaceAll("[^\\sA-Zά-ώ]", "")); } }); //Για να δέχεται μόνο ένα γράμμα textField.setTextFormatter(new TextFormatter<String>((TextFormatter.Change change) -> { String newText = change.getControlNewText(); if (newText.length() > 1) { return null; } else { return change; } })); //Ορισμός του πίνακα με τις λέξεις του παιχνιδιού και αντιγραφή σε ένα ArrayList , για την εύκολη ανακάτεψή τους String[] EnglishWords = {"αγαλλίαση", "Αλόννησος", "αναστήλωση", "ανέγγιχτος", "ανδρεία", "αστοιχείωτος", "βδελυρός","βερίκοκο", "βυσσοδομώ","γάγγραινα", "γιατρειά", "γλαφυρός", "γλιτώνω ", "δεισιδαιμονία", "διαπρύσιοι ", "διευκρίνιση", "δοκησίσοφος", "δωσίλογος", "εγκάθειρκτος", "εκεχειρία", "έκπαγλος", "ελλιπής", "εμπεριστατωμένος","εξαπίνης", "καταμεσής", "κλαυθμυρίζω", "κνώδαλο", "κομπορρημοσύνη", "κρησφύγετο", "κωδίκελος", "λέκιθος", "λήκυθος", "λογύδριο", "λυθρίνι", "μεγαλεπήβολος", "μυδράλιο", "μυκτηρίζω", "νηπενθής", "ξένοιαστος", "φερέγγυος", "χρεοκοπία", "τετριμμένος", "συνονθύλευμα"}; ArrayList<String> Words = new ArrayList<>(); Collections.addAll(Words, EnglishWords); //Ανακατεύει το<SUF> Collections.shuffle(Words); //Αποθήκευση της πρώτης λέξης του σε μία μεταβλητή τύπου String και αφαίρεση από την λίστα String magicWord = Words.get(0); Words.remove(0); // Copy character by character into array wordsLetters = magicWord.toCharArray(); //Αρχικοποίηση της μεταβλητής για να ξέρουμε πότε ο χρήστης θα βρει την λέξη counter = wordsLetters.length; //Για να εμφανίζεται το πρώτο γράμμα της λέξης word.add(0, String.valueOf(wordsLetters[0])); wordsLetters[0] = '.'; //Για να εμφανίζονται οι παύλες των γραμμάτων που δεν έχει βρει ο χρήστης for (int i = 1; i <= wordsLetters.length; i++) { word.add(" _"); label.setText(label.getText() + word.get(i - 1)); } } }
2923_0
package sample; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.stage.Stage; import java.io.IOException; import java.util.Optional; public class Controller{ @FXML private Button button1, button2, button3, button4, button5, button6, button7, button8, button9; @FXML int playerTurn = 0, counter = 0; @FXML//Καθορίζει πότε θα τυπώνετε το χ και πότε ο private void setText(Button button){ if(playerTurn % 2 == 0){ //Ορίζει το χρώμα από το χ button.setStyle("-fx-text-fill: #2229EE"); //τυπώνει το χ πάνω στο κουμπί button.setText("X"); playerTurn = 1; }else { button.setStyle("-fx-text-fill: #EA1B1B"); button.setText("O"); playerTurn = 0; } } @FXML private void game(ActionEvent event) throws IOException{ //Αναγνωρίζει πιο κουμπί πατήθηκε και ορίζει το κατάλληλο γράμμα if(event.getSource() == button1){ setText(button1); button1.setDisable(true); }else if(event.getSource() == button2){ setText(button2); button2.setDisable(true); }else if(event.getSource()== button3){ setText(button3); button3.setDisable(true); }else if(event.getSource()== button4){ setText(button4); button4.setDisable(true); }else if(event.getSource()== button5){ setText(button5); button5.setDisable(true); }else if(event.getSource()== button6){ setText(button6); button6.setDisable(true); }else if(event.getSource()== button7){ setText(button7); button7.setDisable(true); }else if(event.getSource()== button8){ setText(button8); button8.setDisable(true); }else if(event.getSource()== button9) { setText(button9); button9.setDisable(true); } //Κάνει ελέγχους για το αν έχει δημιουργηθεί τρίλιζα. Εαν ναι εμφανίζει τον νικητή με ανάλογο μήνυμα if((button1.getText() + button2.getText() + button3.getText()).equals("XXX") || (button1.getText() + button2.getText() + button3.getText()).equals("OOO")){ showMessage(event, button1); }else if ((button4.getText() + button5.getText() + button6.getText()).equals("XXX") || (button4.getText() + button5.getText() + button6.getText()).equals("OOO")){ showMessage(event, button4); }else if ((button7.getText() + button8.getText() + button9.getText()).equals("XXX") || (button7.getText() + button8.getText() + button9.getText()).equals("OOO")){ showMessage(event, button7); }else if ((button1.getText() + button4.getText() + button7.getText()).equals("XXX") || (button1.getText() + button4.getText() + button7.getText()).equals("OOO")){ showMessage(event, button1); }else if ((button2.getText() + button5.getText() + button8.getText()).equals("XXX") || (button2.getText() + button5.getText() + button8.getText()).equals("OOO")){ showMessage(event, button2); }else if ((button3.getText() + button6.getText() + button9.getText()).equals("XXX") || (button3.getText() + button6.getText() + button9.getText()).equals("OOO")){ showMessage(event, button3); }else if ((button1.getText() + button5.getText() + button9.getText()).equals("XXX") || (button1.getText() + button5.getText() + button9.getText()).equals("OOO")){ showMessage(event, button1); }else if ((button3.getText() + button5.getText() + button7.getText()).equals("XXX") || (button3.getText() + button5.getText() + button7.getText()).equals("OOO")){ showMessage(event, button3); } //Για να ξέρουμε πότε το παιχνίδι βγαίνει ισοπαλία counter++; if(counter == 9){ Button draw = new Button(); draw.setText("draw"); showMessage(event, draw); } } @FXML private void showMessage(ActionEvent event, Button button) throws IOException{ //Δημιουργεί τα κουμπιά στο Alert ButtonType playAgain = new ButtonType("Play again"); ButtonType exit = new ButtonType("Exit"); //Δημιουργεί το Alert Alert a = new Alert(Alert.AlertType.INFORMATION, "", playAgain, exit); a.setTitle("Game over!"); //Για να εμφανίζει το κατάλληλο μήνυμα if (button.getText().equals("draw")){ a.setHeaderText("Draw!!!"); }else { a.setHeaderText(button.getText() + " wins!!!"); } //Δίνει λειτουργικότητα στα κουμπιά του Alert Optional<ButtonType> result = a.showAndWait(); if(!result.isPresent()) { Platform.exit(); }else if(result.get() == playAgain) { Parent root = FXMLLoader.load(getClass().getResource("sample.fxml")); Stage primaryStage = (Stage)((Node)event.getSource()).getScene().getWindow(); primaryStage.setTitle("Τρίλιζα"); primaryStage.setScene(new Scene(root, 500, 500)); primaryStage.show(); }else if(result.get() == exit) { Platform.exit(); } } }
Giannis1273646/tic-tac-toe
src/sample/Controller.java
1,709
//Καθορίζει πότε θα τυπώνετε το χ και πότε ο
line_comment
el
package sample; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.stage.Stage; import java.io.IOException; import java.util.Optional; public class Controller{ @FXML private Button button1, button2, button3, button4, button5, button6, button7, button8, button9; @FXML int playerTurn = 0, counter = 0; @FXML//Καθορίζει πότε<SUF> private void setText(Button button){ if(playerTurn % 2 == 0){ //Ορίζει το χρώμα από το χ button.setStyle("-fx-text-fill: #2229EE"); //τυπώνει το χ πάνω στο κουμπί button.setText("X"); playerTurn = 1; }else { button.setStyle("-fx-text-fill: #EA1B1B"); button.setText("O"); playerTurn = 0; } } @FXML private void game(ActionEvent event) throws IOException{ //Αναγνωρίζει πιο κουμπί πατήθηκε και ορίζει το κατάλληλο γράμμα if(event.getSource() == button1){ setText(button1); button1.setDisable(true); }else if(event.getSource() == button2){ setText(button2); button2.setDisable(true); }else if(event.getSource()== button3){ setText(button3); button3.setDisable(true); }else if(event.getSource()== button4){ setText(button4); button4.setDisable(true); }else if(event.getSource()== button5){ setText(button5); button5.setDisable(true); }else if(event.getSource()== button6){ setText(button6); button6.setDisable(true); }else if(event.getSource()== button7){ setText(button7); button7.setDisable(true); }else if(event.getSource()== button8){ setText(button8); button8.setDisable(true); }else if(event.getSource()== button9) { setText(button9); button9.setDisable(true); } //Κάνει ελέγχους για το αν έχει δημιουργηθεί τρίλιζα. Εαν ναι εμφανίζει τον νικητή με ανάλογο μήνυμα if((button1.getText() + button2.getText() + button3.getText()).equals("XXX") || (button1.getText() + button2.getText() + button3.getText()).equals("OOO")){ showMessage(event, button1); }else if ((button4.getText() + button5.getText() + button6.getText()).equals("XXX") || (button4.getText() + button5.getText() + button6.getText()).equals("OOO")){ showMessage(event, button4); }else if ((button7.getText() + button8.getText() + button9.getText()).equals("XXX") || (button7.getText() + button8.getText() + button9.getText()).equals("OOO")){ showMessage(event, button7); }else if ((button1.getText() + button4.getText() + button7.getText()).equals("XXX") || (button1.getText() + button4.getText() + button7.getText()).equals("OOO")){ showMessage(event, button1); }else if ((button2.getText() + button5.getText() + button8.getText()).equals("XXX") || (button2.getText() + button5.getText() + button8.getText()).equals("OOO")){ showMessage(event, button2); }else if ((button3.getText() + button6.getText() + button9.getText()).equals("XXX") || (button3.getText() + button6.getText() + button9.getText()).equals("OOO")){ showMessage(event, button3); }else if ((button1.getText() + button5.getText() + button9.getText()).equals("XXX") || (button1.getText() + button5.getText() + button9.getText()).equals("OOO")){ showMessage(event, button1); }else if ((button3.getText() + button5.getText() + button7.getText()).equals("XXX") || (button3.getText() + button5.getText() + button7.getText()).equals("OOO")){ showMessage(event, button3); } //Για να ξέρουμε πότε το παιχνίδι βγαίνει ισοπαλία counter++; if(counter == 9){ Button draw = new Button(); draw.setText("draw"); showMessage(event, draw); } } @FXML private void showMessage(ActionEvent event, Button button) throws IOException{ //Δημιουργεί τα κουμπιά στο Alert ButtonType playAgain = new ButtonType("Play again"); ButtonType exit = new ButtonType("Exit"); //Δημιουργεί το Alert Alert a = new Alert(Alert.AlertType.INFORMATION, "", playAgain, exit); a.setTitle("Game over!"); //Για να εμφανίζει το κατάλληλο μήνυμα if (button.getText().equals("draw")){ a.setHeaderText("Draw!!!"); }else { a.setHeaderText(button.getText() + " wins!!!"); } //Δίνει λειτουργικότητα στα κουμπιά του Alert Optional<ButtonType> result = a.showAndWait(); if(!result.isPresent()) { Platform.exit(); }else if(result.get() == playAgain) { Parent root = FXMLLoader.load(getClass().getResource("sample.fxml")); Stage primaryStage = (Stage)((Node)event.getSource()).getScene().getWindow(); primaryStage.setTitle("Τρίλιζα"); primaryStage.setScene(new Scene(root, 500, 500)); primaryStage.show(); }else if(result.get() == exit) { Platform.exit(); } } }
10080_0
package com.example.demo.controller; import com.example.demo.exception.ResourceNotFoundException; import com.example.demo.model.User; import com.example.demo.model.User.Role; import com.example.demo.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import org.springframework.security.crypto.password.PasswordEncoder; import java.util.List; @RestController @RequestMapping("/api/users") public class UserController { @Autowired private UserRepository userRepository; @GetMapping public List<User> getAllUsers() { return userRepository.findAll(); } @Autowired private PasswordEncoder passwordEncoder; @GetMapping("/{id}") public User getUserById(@PathVariable(value = "id") Long userId) { return userRepository.findById(userId) .orElseThrow(() -> new ResourceNotFoundException("User", "id", userId)); } @PostMapping public User createUser(@RequestBody User user) { return userRepository.save(user); } @PutMapping("/{id}") public User updateUser(@PathVariable(value = "id") Long userId, @RequestBody User userDetails) { User user = userRepository.findById(userId) .orElseThrow(() -> new ResourceNotFoundException("User", "id", userId)); user.setUsername(userDetails.getUsername()); user.setPassword(userDetails.getPassword()); user.setRole(userDetails.getRole()); return userRepository.save(user); } @DeleteMapping("/{id}") public void deleteUser(@PathVariable(value = "id") Long userId) { User user = userRepository.findById(userId) .orElseThrow(() -> new ResourceNotFoundException("User", "id", userId)); userRepository.delete(user); } @PostMapping("/register") public ResponseEntity<?> registerUser(@Valid @RequestBody User user) { // Έλεγχος αν το όνομα χρήστη υπάρχει ήδη if (userRepository.findByUsername(user.getUsername()) != null) { return ResponseEntity.badRequest().body("Username already exists"); } // Κωδικοποίηση του κωδικού πρόσβασης και αποθήκευση του χρήστη user.setPassword(passwordEncoder.encode(user.getPassword())); // Ανάθεση προεπιλεγμένου ρόλου (π.χ. USER) στο νέο χρήστη user.setRole(Role.USER); // Αποθήκευση του νέου χρήστη στη βάση δεδομένων User newUser = userRepository.save(user); // Επιστροφή απάντησης ότι ο χρήστης δημιουργήθηκε επιτυχώς return ResponseEntity.ok().body(newUser); } } // ΠΕΡΙΜΕΝΕ, ΜΗΝ ΞΕΚΙΝΗΣΕΙΣ ΤΗΝ ΑΝΑΠΤΥΞΗ ΑΚΟΜΑ. ΕΧΕΙ ΚΙΑΛΛΑ ΚΟΜΜΑΤΙΑ ΚΩΔΙΚΑ.
GiannisNtz01/farmers
demo/src/main/java/com/example/demo/controller/UserController.java
909
// Έλεγχος αν το όνομα χρήστη υπάρχει ήδη
line_comment
el
package com.example.demo.controller; import com.example.demo.exception.ResourceNotFoundException; import com.example.demo.model.User; import com.example.demo.model.User.Role; import com.example.demo.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import org.springframework.security.crypto.password.PasswordEncoder; import java.util.List; @RestController @RequestMapping("/api/users") public class UserController { @Autowired private UserRepository userRepository; @GetMapping public List<User> getAllUsers() { return userRepository.findAll(); } @Autowired private PasswordEncoder passwordEncoder; @GetMapping("/{id}") public User getUserById(@PathVariable(value = "id") Long userId) { return userRepository.findById(userId) .orElseThrow(() -> new ResourceNotFoundException("User", "id", userId)); } @PostMapping public User createUser(@RequestBody User user) { return userRepository.save(user); } @PutMapping("/{id}") public User updateUser(@PathVariable(value = "id") Long userId, @RequestBody User userDetails) { User user = userRepository.findById(userId) .orElseThrow(() -> new ResourceNotFoundException("User", "id", userId)); user.setUsername(userDetails.getUsername()); user.setPassword(userDetails.getPassword()); user.setRole(userDetails.getRole()); return userRepository.save(user); } @DeleteMapping("/{id}") public void deleteUser(@PathVariable(value = "id") Long userId) { User user = userRepository.findById(userId) .orElseThrow(() -> new ResourceNotFoundException("User", "id", userId)); userRepository.delete(user); } @PostMapping("/register") public ResponseEntity<?> registerUser(@Valid @RequestBody User user) { // Έλεγχος αν<SUF> if (userRepository.findByUsername(user.getUsername()) != null) { return ResponseEntity.badRequest().body("Username already exists"); } // Κωδικοποίηση του κωδικού πρόσβασης και αποθήκευση του χρήστη user.setPassword(passwordEncoder.encode(user.getPassword())); // Ανάθεση προεπιλεγμένου ρόλου (π.χ. USER) στο νέο χρήστη user.setRole(Role.USER); // Αποθήκευση του νέου χρήστη στη βάση δεδομένων User newUser = userRepository.save(user); // Επιστροφή απάντησης ότι ο χρήστης δημιουργήθηκε επιτυχώς return ResponseEntity.ok().body(newUser); } } // ΠΕΡΙΜΕΝΕ, ΜΗΝ ΞΕΚΙΝΗΣΕΙΣ ΤΗΝ ΑΝΑΠΤΥΞΗ ΑΚΟΜΑ. ΕΧΕΙ ΚΙΑΛΛΑ ΚΟΜΜΑΤΙΑ ΚΩΔΙΚΑ.
20353_5
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package SoftwareEngineering; import java.time.LocalDateTime; import java.util.ArrayList; /** * * @author DeRed */ public class Schedule { private ArrayList<Appointment> appointment_list; public Schedule(){ this.appointment_list = new ArrayList<Appointment>(); } public boolean AddAppointment(int doctorID, Patient p, LocalDateTime d){ // ΔΗΜΙΟΥΡΓΙΑ ΕΝΟΣ TMP APPOINTMENT Appointment tmp = new Appointment(p,d,doctorID); // ΕΛΕΓΧΟΣ ΕΑΝ ΜΠΟΡΕΙ ΝΑ ΜΠΕΙ ΣΤΟ ΠΡΟΓΡΑΜΜΑ for ( Appointment booking : this.appointment_list ){ if (booking.getDate() == tmp.getDate()) return false; //ΥΠΑΡΧΕΙ ΗΔΗ ΚΑΠΟΙΟ ΡΑΝΤΕΒΟΥ } // ΕΙΣΑΓΩΓΗ ΤΟΥ ΡΑΝΤΕΒΟΥ ΕΦΟΣΟΝ ΓΙΝΕΤΕ this.appointment_list.add(tmp); return true; } }
GiannisP97/Medical_office_2018
Medical_office/src/SoftwareEngineering/Schedule.java
411
// ΕΙΣΑΓΩΓΗ ΤΟΥ ΡΑΝΤΕΒΟΥ ΕΦΟΣΟΝ ΓΙΝΕΤΕ
line_comment
el
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package SoftwareEngineering; import java.time.LocalDateTime; import java.util.ArrayList; /** * * @author DeRed */ public class Schedule { private ArrayList<Appointment> appointment_list; public Schedule(){ this.appointment_list = new ArrayList<Appointment>(); } public boolean AddAppointment(int doctorID, Patient p, LocalDateTime d){ // ΔΗΜΙΟΥΡΓΙΑ ΕΝΟΣ TMP APPOINTMENT Appointment tmp = new Appointment(p,d,doctorID); // ΕΛΕΓΧΟΣ ΕΑΝ ΜΠΟΡΕΙ ΝΑ ΜΠΕΙ ΣΤΟ ΠΡΟΓΡΑΜΜΑ for ( Appointment booking : this.appointment_list ){ if (booking.getDate() == tmp.getDate()) return false; //ΥΠΑΡΧΕΙ ΗΔΗ ΚΑΠΟΙΟ ΡΑΝΤΕΒΟΥ } // ΕΙΣΑΓΩΓΗ ΤΟΥ<SUF> this.appointment_list.add(tmp); return true; } }
16379_0
/* *Copyright..... */ package gr.aueb.elearn.ch1; /** * υπολογιζει και εμφανιζει το αθροισμα 2 αριθμων του 12 και του 5 */ public class DataDemo { public static void main(String[] args) { //Δηλωση αρχικοποιηση μεταβλητων int num1 = 12; int num2 = 5; int sum; //Εντολες sum = num1 + num2; //Εκτυπωση αποτελεσματων System.out.println("Το αθροισμα ειναι" + sum); } }
GioNik7/java-jr-to-mid-level
chapter1/DataDemo.java
227
/** * υπολογιζει και εμφανιζει το αθροισμα 2 αριθμων του 12 και του 5 */
block_comment
el
/* *Copyright..... */ package gr.aueb.elearn.ch1; /** * υπολογιζει και εμφανιζει<SUF>*/ public class DataDemo { public static void main(String[] args) { //Δηλωση αρχικοποιηση μεταβλητων int num1 = 12; int num2 = 5; int sum; //Εντολες sum = num1 + num2; //Εκτυπωση αποτελεσματων System.out.println("Το αθροισμα ειναι" + sum); } }
7697_8
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package project_test; import java.util.List; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Scanner; import java.util.ArrayList; import java.util.Arrays; import java.io.Serializable; /** * * @author Giorgos Giannopoulos * @author Ioannis Giannopoulos */ public class Game { // private Refugee _player; private List<Refugee> players; // private GiverEntity ngo_bank = new GiverEntity("NGO Bank", 10000); private GiverEntity ngo_bank; // private MoneyReceiver ngo_bank; private ReceiverEntity mafia_bank; private ReceiverEntity nobody; private Board gameBoard; private Square square; List<Integer> paySquares = Arrays.asList(1, 3, 6, 9, 13, 16, 21, 26, 37); List<Integer> rollSquares = Arrays.asList(2, 9, 12, 16, 17, 22, 28, 31, 33); List<Integer> staySquares = Arrays.asList(8, 11, 14, 19, 24, 27, 32, 34); List<Integer> goToSquares = Arrays.asList(4, 5, 15, 18, 23, 25, 29, 30, 33, 35, 38); List<Integer> receiveSquares = Arrays.asList(20); List<Integer> winSquares = Arrays.asList(36,39); List<Integer> deadSquares = Arrays.asList(10); public void setNgoBank() { ngo_bank = new GiverEntity("NGO Bank", 10000); } public String getNgoBank() { return (ngo_bank.toString()); } public void setMafiaBank() { mafia_bank = new ReceiverEntity("Mafia Bank", 0); } public String getMafiaBank() { return (mafia_bank.toString()); } public void setNobodyReceives(){ nobody = new ReceiverEntity("Nobody", 0); } public void setBoard() { gameBoard = new Board(); try { File file = new File("src\\project_test\\refugeoly-squares.txt"); Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { int number = Integer.parseInt(scanner.nextLine().trim()); String text = scanner.nextLine().trim(); String description = scanner.nextLine().trim(); // Προσθέστε το τετράγωνο στο ταμπλό square = new Square(number, text, description, gameBoard); // switch based on square number add the actions to be performed by the player gameBoard.addSquare(square); /* if (square.getNumber() == 7) { System.out.println("DEBUG: Square number is 7"); ExtraLiveAction extraLiveAction = new ExtraLiveAction(); square.addAction(extraLiveAction); //IsDeadAction dead = new IsDeadAction(); //square.addAction(dead); } */ // Διαβάστε την κενή γραμμή μεταξύ των τετραγώνων if (scanner.hasNextLine()) { scanner.nextLine(); } } } catch (FileNotFoundException e) { e.printStackTrace(); } } public void setPlayers(int numberOfPlayers) { if (numberOfPlayers < 1 || numberOfPlayers > 4) { System.out.println("Invalid number of players. Please choose a number between 1 and 4."); return; } players = new ArrayList<>(); Scanner scanner = new Scanner(System.in); for (int i = 0; i < numberOfPlayers; i++) { System.out.print("Enter name for player " + (i + 1) + ": "); String playerName = scanner.nextLine(); Refugee player = new Refugee(playerName, 10000, 0, 0, false, false, false, false); players.add(player); } } public void playGame() { setNgoBank(); System.out.println(getNgoBank()); setMafiaBank(); System.out.println(getMafiaBank()); setNobodyReceives(); setBoard(); int numberOfPlayers; Scanner scanner = new Scanner(System.in); do { System.out.print("Enter the number of players (1 - 4): "); numberOfPlayers = scanner.nextInt(); if (numberOfPlayers < 1 || numberOfPlayers > 4) { System.out.println("Invalid number of players. Please choose a number between 1 and 4."); } } while (numberOfPlayers < 1 || numberOfPlayers > 4); scanner.nextLine(); //read the next line // Set up players setPlayers(numberOfPlayers); ExtraLiveAction extraLiveAction = new ExtraLiveAction(); StayAction stay = new StayAction(); int current_square = 0; int i = 0; int round; boolean play_again = true; // for square 26 where the user choose option B and stays in the same square for two rounds instead of 1 round that's the normal int doubleStay = 0; String userInput; while (!isGameOver(numberOfPlayers)) { round = i + 1; System.out.println("\t\tRound " + round); for (Refugee player : players) { if (!player.isDead() && !player.getHasWon()) { System.out.println("\n" + player.getName() + "'s turn: "); if (!player.isStayed()) { System.out.println("Press r to roll the dice"); System.out.println("Press s to save the game"); System.out.println("Press l to load a game"); System.out.println("Enter your input: "); //Scanner scanner = new Scanner(System.in); userInput = scanner.nextLine(); //System.out.println(userInput); if (userInput.equalsIgnoreCase("s")) { saveGame(); // Call the saveGame method System.out.println("Game saved successfully!"); userInput = "r"; //continue; // Skip the rest of the player's turn } if (userInput.equalsIgnoreCase("l")) { loadGame(); // Call the loadGame method // Continue the game from the loaded state continue; } if(userInput.equalsIgnoreCase("r")){ // standard dice for the player turn RollDiceAction diceAction = new RollDiceAction(); // go to square // valid move, player is moving to the new square diceAction.act(player); if(!diceAction.isLegal()){ // the move is not legal, player exceed's square 39 so stay on the same square and break so he doesn't perform any other actions break; } else{ //player move is legal GoToAction goToAction = new GoToAction(diceAction.diceval); goToAction.act(player); play_again = true; while(play_again){ gameBoard.getSquare(player.getCurrentSquare()); // get text of the square and number square.clearActions(); play_again = false; //set play_again false and set it true if player get's to roll the dice again current_square = player.getCurrentSquare(); if (paySquares.contains(current_square)) { //handle the square 26 actions that have two options after paying the amount if(current_square == 26){ PayMoneyAction payMoney = new PayMoneyAction(player, mafia_bank, 1000); square.addAction(payMoney); System.out.println("Choose between\nOption A: Pay $1500 to Mafia Bank and roll dice"); System.out.println("Option B: Don’t pay and stay 2 turns"); System.out.println("Enter A or B: "); //userInput = scanner.nextLine(); boolean validInput = false; do { userInput = scanner.nextLine(); if (userInput.equalsIgnoreCase("A")) { // User chose option A PayMoneyAction payMoney2 = new PayMoneyAction(player, mafia_bank, 1500); square.addAction(payMoney2); square.addAction(diceAction); square.addAction(goToAction); play_again = true; // So the player gets the new actions of the box validInput = true; // Valid input, exit the loop } else if (userInput.equalsIgnoreCase("B")) { // User chose option B square.addAction(stay); doubleStay = 1; //stay for 2 rounds validInput = true; // Valid input, exit the loop } else { // User entered something other than A or B System.out.println("Invalid input. Please enter either A or B.\n"); } } while (!validInput); } // handle square 21 where you have lost 1500$ due to theft else if (current_square == 21) { PayMoneyAction payMoney = new PayMoneyAction(player, nobody, 1500); square.addAction(payMoney); } else if(current_square == 1){ //the money goes to nobody, not in the Mafia Bank PayMoneyAction payMoney = new PayMoneyAction(player, nobody, 100); square.addAction(payMoney); } else{ String textForPay = gameBoard.getText(current_square); // Finding the positions of "Pay" and "$" in the message int payIndex = textForPay.indexOf("Pay"); int dollarIndex = textForPay.indexOf("$"); //System.out.println("Pay index = " + payIndex); //System.out.println("Dollar index = " + dollarIndex); if (payIndex != -1 && dollarIndex != -1) { String amountStr = "0"; // Check if the dollar sign appears after amount if (dollarIndex - payIndex > 4) { // Extracting the amount substring amountStr = textForPay.substring(payIndex + "Pay".length(), dollarIndex).trim(); } else { int endIndex = dollarIndex + 4; // Assuming the maximum amount length is 4 digits endIndex = Math.min(endIndex, textForPay.length()); // Ensure not to go beyond the // string length // Extracting the amount substring when the dollar sign comes before amount amountStr = textForPay.substring(dollarIndex + 1, endIndex).trim(); } // Parsing the amount to an integer try { int amount = Integer.parseInt(amountStr); // Creating PayMoneyAction with the extracted amount //System.out.println("Text for pay is " + textForPay); PayMoneyAction payMoney = new PayMoneyAction(player, mafia_bank, amount); square.addAction(payMoney); } catch (NumberFormatException e) { // Handle the case where the amount is not a valid integer System.out.println("Error: Unable to parse amount from the text"); } } else { // Handle the case where "Pay" or "$" is not found in the expected positions System.out.println("Error: Amount not found in the text"); } } } if (rollSquares.contains(current_square)) { square.addAction(diceAction); square.addAction(goToAction); play_again = true; //so the player get's the new actions of the box } if (staySquares.contains(current_square)) { square.addAction(stay); } if (goToSquares.contains(current_square)) { //manual go to square 5 if player is on square 15 //Text in the refugeoly-squares.txt is : Border Control 2. Back to Border Control 1 //It's missing the square number if (current_square == 15){ player.setCurrentSquare(5); square.addAction(goToAction); } else{ //other squares with Go to square have in the text the destination square String textForGoTo = gameBoard.getText(current_square); // Finding the positions of the opening and closing parentheses int openParenthesisIndex = textForGoTo.indexOf("("); int closeParenthesisIndex = textForGoTo.indexOf(")"); // System.out.println("Text for go to is: " + textForGoTo); if (openParenthesisIndex != -1 && closeParenthesisIndex != -1) { //System.out.println("openParenthesisIndex: " + openParenthesisIndex); //System.out.println("closeParenthesisIndex: " + closeParenthesisIndex); // Parsing the content to check if it's a number or a box number try { if(closeParenthesisIndex - openParenthesisIndex < 4){ // Extracting the content inside the parentheses String contentInsideParentheses = textForGoTo .substring(openParenthesisIndex + 1, closeParenthesisIndex).trim(); //System.out.println("Content inside parentheses: " + // contentInsideParentheses); int destination = Integer.parseInt(contentInsideParentheses); // Setting the new position for the player player.setCurrentSquare(destination); square.addAction(goToAction); } else{ // the text inside the parenthesis is (box number) // so we get rid off box string (3) + 1 for the space int startIndex = openParenthesisIndex + 4; // Extracting the content inside the parentheses String contentInsideParentheses = textForGoTo .substring(startIndex, closeParenthesisIndex).trim(); //System.out.println("Content inside parentheses: " + // contentInsideParentheses); int destination = Integer.parseInt(contentInsideParentheses); player.setCurrentSquare(destination); square.addAction(goToAction); } } catch (NumberFormatException e) { // If parsing as an integer fails, treat it as a box number System.out.println("Error parsing the integer in the parenthesis"); } } else { // Handle the case where "(" or ")" is not found in the expected positions System.out.println("Error: Destination number not found in the text"); } } } if (receiveSquares.contains(current_square)) { ReceiveMoneyAction receiveMoney = new ReceiveMoneyAction(ngo_bank, player, 1000); square.addAction(receiveMoney); } if (current_square == 7) { square.addAction(extraLiveAction); } if (winSquares.contains(current_square)){ System.out.println("You did it!!!\nYou won the game!!!"); player.setHasWon(true); } if (deadSquares.contains(current_square)){ if(player.hasExtraLife()){ System.out.println(player.getName()+ " is saved because he has an extra life"); player.setExtraLife(false); } else{ IsDeadAction dead = new IsDeadAction(); square.addAction(dead); } } square.act(player); } } } System.out.println(player.getCurrentSquare()); System.out.println(player.toString()); System.out.println(getNgoBank()); System.out.println(getMafiaBank()); System.out.println("---------------------------------------------------------------"); } else if (player.isStayed()) { System.out.println("Player " + player.getName() + " has lost his turn in the previous round and so he is not playing right now"); // handle the square 26 option B when user stays for 2 turns in the same square if(doubleStay <= 0){ player.setStayed(false); // set the player to play next round doubleStay = 0; } else{ doubleStay -= 1; } } } } ++i; } System.out.println("\n\n---------------------Game Finished---------------------"); // Print the player status if he won or not for(Refugee player : players){ if(player.getHasWon()){ System.out.println("Player: " + player.getName() + " managed to survive and found a new home and spend " + player.getExpenses() + "$ in his journey"); } else{ System.out.println("Player: " + player.getName() + " didn't managed to survive"); } } System.out.println("\nThank you for playing Refugeoly!!!"); scanner.close(); } public boolean isGameOver(int numberOfPlayers) { int i = 0; for(Refugee player : players){ if(player.isDead() || player.getHasWon()){ ++i; } } if(i == numberOfPlayers){ return true; } else{ return false; } } public void saveGame() { try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("savedGame.ser"))) { // Serialize the game state GameData gameData = new GameData(players, ngo_bank.getMoney(), mafia_bank.getMoney(), gameBoard); outputStream.writeObject(gameData); } catch (IOException e) { e.printStackTrace(); } } public void loadGame() { try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("savedGame.ser"))) { // Deserialize the game state GameData loadedGameData = (GameData) inputStream.readObject(); // Update the game state based on the loaded data players = loadedGameData.getPlayers(); ngo_bank.setMoney(loadedGameData.getNgoBank()); mafia_bank.setMoney(loadedGameData.getMafiaBank()); System.out.println("Game loaded successfully!"); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } }
GiorgosG1an/Refugeoly
src/project_test/Game.java
4,385
// Διαβάστε την κενή γραμμή μεταξύ των τετραγώνων
line_comment
el
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package project_test; import java.util.List; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Scanner; import java.util.ArrayList; import java.util.Arrays; import java.io.Serializable; /** * * @author Giorgos Giannopoulos * @author Ioannis Giannopoulos */ public class Game { // private Refugee _player; private List<Refugee> players; // private GiverEntity ngo_bank = new GiverEntity("NGO Bank", 10000); private GiverEntity ngo_bank; // private MoneyReceiver ngo_bank; private ReceiverEntity mafia_bank; private ReceiverEntity nobody; private Board gameBoard; private Square square; List<Integer> paySquares = Arrays.asList(1, 3, 6, 9, 13, 16, 21, 26, 37); List<Integer> rollSquares = Arrays.asList(2, 9, 12, 16, 17, 22, 28, 31, 33); List<Integer> staySquares = Arrays.asList(8, 11, 14, 19, 24, 27, 32, 34); List<Integer> goToSquares = Arrays.asList(4, 5, 15, 18, 23, 25, 29, 30, 33, 35, 38); List<Integer> receiveSquares = Arrays.asList(20); List<Integer> winSquares = Arrays.asList(36,39); List<Integer> deadSquares = Arrays.asList(10); public void setNgoBank() { ngo_bank = new GiverEntity("NGO Bank", 10000); } public String getNgoBank() { return (ngo_bank.toString()); } public void setMafiaBank() { mafia_bank = new ReceiverEntity("Mafia Bank", 0); } public String getMafiaBank() { return (mafia_bank.toString()); } public void setNobodyReceives(){ nobody = new ReceiverEntity("Nobody", 0); } public void setBoard() { gameBoard = new Board(); try { File file = new File("src\\project_test\\refugeoly-squares.txt"); Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { int number = Integer.parseInt(scanner.nextLine().trim()); String text = scanner.nextLine().trim(); String description = scanner.nextLine().trim(); // Προσθέστε το τετράγωνο στο ταμπλό square = new Square(number, text, description, gameBoard); // switch based on square number add the actions to be performed by the player gameBoard.addSquare(square); /* if (square.getNumber() == 7) { System.out.println("DEBUG: Square number is 7"); ExtraLiveAction extraLiveAction = new ExtraLiveAction(); square.addAction(extraLiveAction); //IsDeadAction dead = new IsDeadAction(); //square.addAction(dead); } */ // Διαβάστε την<SUF> if (scanner.hasNextLine()) { scanner.nextLine(); } } } catch (FileNotFoundException e) { e.printStackTrace(); } } public void setPlayers(int numberOfPlayers) { if (numberOfPlayers < 1 || numberOfPlayers > 4) { System.out.println("Invalid number of players. Please choose a number between 1 and 4."); return; } players = new ArrayList<>(); Scanner scanner = new Scanner(System.in); for (int i = 0; i < numberOfPlayers; i++) { System.out.print("Enter name for player " + (i + 1) + ": "); String playerName = scanner.nextLine(); Refugee player = new Refugee(playerName, 10000, 0, 0, false, false, false, false); players.add(player); } } public void playGame() { setNgoBank(); System.out.println(getNgoBank()); setMafiaBank(); System.out.println(getMafiaBank()); setNobodyReceives(); setBoard(); int numberOfPlayers; Scanner scanner = new Scanner(System.in); do { System.out.print("Enter the number of players (1 - 4): "); numberOfPlayers = scanner.nextInt(); if (numberOfPlayers < 1 || numberOfPlayers > 4) { System.out.println("Invalid number of players. Please choose a number between 1 and 4."); } } while (numberOfPlayers < 1 || numberOfPlayers > 4); scanner.nextLine(); //read the next line // Set up players setPlayers(numberOfPlayers); ExtraLiveAction extraLiveAction = new ExtraLiveAction(); StayAction stay = new StayAction(); int current_square = 0; int i = 0; int round; boolean play_again = true; // for square 26 where the user choose option B and stays in the same square for two rounds instead of 1 round that's the normal int doubleStay = 0; String userInput; while (!isGameOver(numberOfPlayers)) { round = i + 1; System.out.println("\t\tRound " + round); for (Refugee player : players) { if (!player.isDead() && !player.getHasWon()) { System.out.println("\n" + player.getName() + "'s turn: "); if (!player.isStayed()) { System.out.println("Press r to roll the dice"); System.out.println("Press s to save the game"); System.out.println("Press l to load a game"); System.out.println("Enter your input: "); //Scanner scanner = new Scanner(System.in); userInput = scanner.nextLine(); //System.out.println(userInput); if (userInput.equalsIgnoreCase("s")) { saveGame(); // Call the saveGame method System.out.println("Game saved successfully!"); userInput = "r"; //continue; // Skip the rest of the player's turn } if (userInput.equalsIgnoreCase("l")) { loadGame(); // Call the loadGame method // Continue the game from the loaded state continue; } if(userInput.equalsIgnoreCase("r")){ // standard dice for the player turn RollDiceAction diceAction = new RollDiceAction(); // go to square // valid move, player is moving to the new square diceAction.act(player); if(!diceAction.isLegal()){ // the move is not legal, player exceed's square 39 so stay on the same square and break so he doesn't perform any other actions break; } else{ //player move is legal GoToAction goToAction = new GoToAction(diceAction.diceval); goToAction.act(player); play_again = true; while(play_again){ gameBoard.getSquare(player.getCurrentSquare()); // get text of the square and number square.clearActions(); play_again = false; //set play_again false and set it true if player get's to roll the dice again current_square = player.getCurrentSquare(); if (paySquares.contains(current_square)) { //handle the square 26 actions that have two options after paying the amount if(current_square == 26){ PayMoneyAction payMoney = new PayMoneyAction(player, mafia_bank, 1000); square.addAction(payMoney); System.out.println("Choose between\nOption A: Pay $1500 to Mafia Bank and roll dice"); System.out.println("Option B: Don’t pay and stay 2 turns"); System.out.println("Enter A or B: "); //userInput = scanner.nextLine(); boolean validInput = false; do { userInput = scanner.nextLine(); if (userInput.equalsIgnoreCase("A")) { // User chose option A PayMoneyAction payMoney2 = new PayMoneyAction(player, mafia_bank, 1500); square.addAction(payMoney2); square.addAction(diceAction); square.addAction(goToAction); play_again = true; // So the player gets the new actions of the box validInput = true; // Valid input, exit the loop } else if (userInput.equalsIgnoreCase("B")) { // User chose option B square.addAction(stay); doubleStay = 1; //stay for 2 rounds validInput = true; // Valid input, exit the loop } else { // User entered something other than A or B System.out.println("Invalid input. Please enter either A or B.\n"); } } while (!validInput); } // handle square 21 where you have lost 1500$ due to theft else if (current_square == 21) { PayMoneyAction payMoney = new PayMoneyAction(player, nobody, 1500); square.addAction(payMoney); } else if(current_square == 1){ //the money goes to nobody, not in the Mafia Bank PayMoneyAction payMoney = new PayMoneyAction(player, nobody, 100); square.addAction(payMoney); } else{ String textForPay = gameBoard.getText(current_square); // Finding the positions of "Pay" and "$" in the message int payIndex = textForPay.indexOf("Pay"); int dollarIndex = textForPay.indexOf("$"); //System.out.println("Pay index = " + payIndex); //System.out.println("Dollar index = " + dollarIndex); if (payIndex != -1 && dollarIndex != -1) { String amountStr = "0"; // Check if the dollar sign appears after amount if (dollarIndex - payIndex > 4) { // Extracting the amount substring amountStr = textForPay.substring(payIndex + "Pay".length(), dollarIndex).trim(); } else { int endIndex = dollarIndex + 4; // Assuming the maximum amount length is 4 digits endIndex = Math.min(endIndex, textForPay.length()); // Ensure not to go beyond the // string length // Extracting the amount substring when the dollar sign comes before amount amountStr = textForPay.substring(dollarIndex + 1, endIndex).trim(); } // Parsing the amount to an integer try { int amount = Integer.parseInt(amountStr); // Creating PayMoneyAction with the extracted amount //System.out.println("Text for pay is " + textForPay); PayMoneyAction payMoney = new PayMoneyAction(player, mafia_bank, amount); square.addAction(payMoney); } catch (NumberFormatException e) { // Handle the case where the amount is not a valid integer System.out.println("Error: Unable to parse amount from the text"); } } else { // Handle the case where "Pay" or "$" is not found in the expected positions System.out.println("Error: Amount not found in the text"); } } } if (rollSquares.contains(current_square)) { square.addAction(diceAction); square.addAction(goToAction); play_again = true; //so the player get's the new actions of the box } if (staySquares.contains(current_square)) { square.addAction(stay); } if (goToSquares.contains(current_square)) { //manual go to square 5 if player is on square 15 //Text in the refugeoly-squares.txt is : Border Control 2. Back to Border Control 1 //It's missing the square number if (current_square == 15){ player.setCurrentSquare(5); square.addAction(goToAction); } else{ //other squares with Go to square have in the text the destination square String textForGoTo = gameBoard.getText(current_square); // Finding the positions of the opening and closing parentheses int openParenthesisIndex = textForGoTo.indexOf("("); int closeParenthesisIndex = textForGoTo.indexOf(")"); // System.out.println("Text for go to is: " + textForGoTo); if (openParenthesisIndex != -1 && closeParenthesisIndex != -1) { //System.out.println("openParenthesisIndex: " + openParenthesisIndex); //System.out.println("closeParenthesisIndex: " + closeParenthesisIndex); // Parsing the content to check if it's a number or a box number try { if(closeParenthesisIndex - openParenthesisIndex < 4){ // Extracting the content inside the parentheses String contentInsideParentheses = textForGoTo .substring(openParenthesisIndex + 1, closeParenthesisIndex).trim(); //System.out.println("Content inside parentheses: " + // contentInsideParentheses); int destination = Integer.parseInt(contentInsideParentheses); // Setting the new position for the player player.setCurrentSquare(destination); square.addAction(goToAction); } else{ // the text inside the parenthesis is (box number) // so we get rid off box string (3) + 1 for the space int startIndex = openParenthesisIndex + 4; // Extracting the content inside the parentheses String contentInsideParentheses = textForGoTo .substring(startIndex, closeParenthesisIndex).trim(); //System.out.println("Content inside parentheses: " + // contentInsideParentheses); int destination = Integer.parseInt(contentInsideParentheses); player.setCurrentSquare(destination); square.addAction(goToAction); } } catch (NumberFormatException e) { // If parsing as an integer fails, treat it as a box number System.out.println("Error parsing the integer in the parenthesis"); } } else { // Handle the case where "(" or ")" is not found in the expected positions System.out.println("Error: Destination number not found in the text"); } } } if (receiveSquares.contains(current_square)) { ReceiveMoneyAction receiveMoney = new ReceiveMoneyAction(ngo_bank, player, 1000); square.addAction(receiveMoney); } if (current_square == 7) { square.addAction(extraLiveAction); } if (winSquares.contains(current_square)){ System.out.println("You did it!!!\nYou won the game!!!"); player.setHasWon(true); } if (deadSquares.contains(current_square)){ if(player.hasExtraLife()){ System.out.println(player.getName()+ " is saved because he has an extra life"); player.setExtraLife(false); } else{ IsDeadAction dead = new IsDeadAction(); square.addAction(dead); } } square.act(player); } } } System.out.println(player.getCurrentSquare()); System.out.println(player.toString()); System.out.println(getNgoBank()); System.out.println(getMafiaBank()); System.out.println("---------------------------------------------------------------"); } else if (player.isStayed()) { System.out.println("Player " + player.getName() + " has lost his turn in the previous round and so he is not playing right now"); // handle the square 26 option B when user stays for 2 turns in the same square if(doubleStay <= 0){ player.setStayed(false); // set the player to play next round doubleStay = 0; } else{ doubleStay -= 1; } } } } ++i; } System.out.println("\n\n---------------------Game Finished---------------------"); // Print the player status if he won or not for(Refugee player : players){ if(player.getHasWon()){ System.out.println("Player: " + player.getName() + " managed to survive and found a new home and spend " + player.getExpenses() + "$ in his journey"); } else{ System.out.println("Player: " + player.getName() + " didn't managed to survive"); } } System.out.println("\nThank you for playing Refugeoly!!!"); scanner.close(); } public boolean isGameOver(int numberOfPlayers) { int i = 0; for(Refugee player : players){ if(player.isDead() || player.getHasWon()){ ++i; } } if(i == numberOfPlayers){ return true; } else{ return false; } } public void saveGame() { try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("savedGame.ser"))) { // Serialize the game state GameData gameData = new GameData(players, ngo_bank.getMoney(), mafia_bank.getMoney(), gameBoard); outputStream.writeObject(gameData); } catch (IOException e) { e.printStackTrace(); } } public void loadGame() { try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("savedGame.ser"))) { // Deserialize the game state GameData loadedGameData = (GameData) inputStream.readObject(); // Update the game state based on the loaded data players = loadedGameData.getPlayers(); ngo_bank.setMoney(loadedGameData.getNgoBank()); mafia_bank.setMoney(loadedGameData.getMafiaBank()); System.out.println("Game loaded successfully!"); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } }
13392_12
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package medlars_collection; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.store.LockObtainFailedException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopScoreDocCollector; import org.apache.lucene.store.Directory; import org.apache.lucene.util.Version; import java.io.*; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.lucene.store.FSDirectory; /** * * @author Giorgos */ public class KnowledgeBase { public static void main(String args[]) throws CorruptIndexException, IOException, ParseException, LockObtainFailedException, Exception { try { System.out.println(parseTerms("Knowledge_Base.xml")); } catch (Exception ex) { Logger.getLogger(KnowledgeBase.class.getName()).log(Level.SEVERE, null, ex); } } public static void indexing() throws Exception { // 0. Specify the analyzer for tokenizing text. // The same analyzer should be used for indexing and searching StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_35); String indexLocation = "knowledge"; // 1. create the index Directory index = FSDirectory.open(new File(indexLocation)); IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_35, analyzer); IndexWriter writer = new IndexWriter(index, config); List<Term> terms = parseTerms("Knowledge_Base.xml"); for (Term term : terms) { addDoc(writer, term.getDef(), term.getIs_a(), term.getSynonym()); } writer.close(); } public static ArrayList<String> findSynonyms(String query, int k) throws Exception { // 0. create the index //indexing(); // The same analyzer should be used for indexing and searching StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_35); String indexLocation = "knowledge"; // 1. open the index Directory index = FSDirectory.open(new File(indexLocation)); // 2. query Query q = new QueryParser(Version.LUCENE_35, "name", analyzer).parse(query); // 3. search IndexReader reader = IndexReader.open(index); IndexSearcher searcher = new IndexSearcher(reader); TopScoreDocCollector collector = TopScoreDocCollector.create(k, true); searcher.search(q, collector); ScoreDoc[] hits = collector.topDocs().scoreDocs; // 4. display results //System.out.println("Found: "+ hits.length + "hits"); ArrayList<String> synonyms = new ArrayList<String>(); for (int j = 0; j < hits.length; ++j) { int docId = hits[j].doc; org.apache.lucene.document.Document d = searcher.doc(docId); String syn = d.get("synonym").replace("(", "").replace(")", "").replace(":", ""); synonyms.add(syn.split("#")[0]); } searcher.close(); reader.close(); return synonyms; } private static void addDoc(IndexWriter writer, String name, String is_a, ArrayList<String> synonyms) throws IOException { org.apache.lucene.document.Document doc = new org.apache.lucene.document.Document(); Field namefield = new Field("name", name, Field.Store.YES, Field.Index.ANALYZED); Field is_afield = new Field("is_a", is_a, Field.Store.YES, Field.Index.ANALYZED); String syn = ""; for (String synonym : synonyms) { syn += synonym + "#"; } //remove last # if (syn.length() > 0) { syn = syn.substring(0, syn.length() - 1); } Field synonymfield = new Field("synonym", syn, Field.Store.YES, Field.Index.ANALYZED); doc.add(namefield); doc.add(is_afield); doc.add(synonymfield); writer.addDocument(doc); } private static List<Term> parseTerms(String fl) throws Exception { List<Term> terms = new ArrayList<Term>(); //Δημιουργία του DOM XML parser DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); //Parse fil to DOM Tree Document doc = dBuilder.parse(fl); //Διαβάσμα του root κόμβου Element rootElement = doc.getDocumentElement(); System.out.println("Root element :" + rootElement.getNodeName()); //Παίρνουμε όλα τα elements <user> NodeList nList = doc.getElementsByTagName("term"); for (int n = 0; n < nList.getLength(); n++) { Node nNode = nList.item(n); Element eElement = (Element) nNode; //Διαβάζουμε τα στοιχεία που βρίσκονται στα tags κάτω από κάθε user //element ArrayList<String> namelist = getTagValue("name", eElement); ArrayList<String> deflist = getTagValue("def", eElement); ArrayList<String> is_alist = getTagValue("is_a", eElement); ArrayList<String> synonyms = getTagValue("synonym", eElement); String name = listToString(namelist); String def = listToString(deflist); name += def; String is_a = listToString(is_alist); //Δημιουργούμε ένα object Temr με τα στοιχεία που διαβάσαμε Term term = new Term(name, synonyms, is_a); terms.add(term); } return terms; } /*** * Επιστρέφει το κείμενο που βρίσκεται ανάμεσα στo <stag></stag> * * @param sTag * @param eElement το parent node (tag element) * @return */ private static ArrayList<String> getTagValue(String sTag, Element eElement) { ArrayList<String> output = new ArrayList<String>(); if (eElement.getElementsByTagName(sTag).item(0) != null) { NodeList nlList; if (eElement.getElementsByTagName(sTag).getLength() > 1) { for (int j = 0; j < eElement.getElementsByTagName(sTag).getLength(); j++) { nlList = eElement.getElementsByTagName(sTag).item(j).getChildNodes(); Node nValue = nlList.item(0); if (nValue != null) { output.add(nValue.getNodeValue()); } } return output; } else { nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes(); Node nValue = nlList.item(0); output.add(nValue.getNodeValue()); return output; } } else { return output; } } private static String listToString(List<String> list) { String output = ""; for (String item : list) { output = output + " " + item; } return output; } }
GiorgosPa/Medlars
java code/KnowledgeBase.java
2,005
//Δημιουργία του DOM XML parser
line_comment
el
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package medlars_collection; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.store.LockObtainFailedException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopScoreDocCollector; import org.apache.lucene.store.Directory; import org.apache.lucene.util.Version; import java.io.*; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.lucene.store.FSDirectory; /** * * @author Giorgos */ public class KnowledgeBase { public static void main(String args[]) throws CorruptIndexException, IOException, ParseException, LockObtainFailedException, Exception { try { System.out.println(parseTerms("Knowledge_Base.xml")); } catch (Exception ex) { Logger.getLogger(KnowledgeBase.class.getName()).log(Level.SEVERE, null, ex); } } public static void indexing() throws Exception { // 0. Specify the analyzer for tokenizing text. // The same analyzer should be used for indexing and searching StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_35); String indexLocation = "knowledge"; // 1. create the index Directory index = FSDirectory.open(new File(indexLocation)); IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_35, analyzer); IndexWriter writer = new IndexWriter(index, config); List<Term> terms = parseTerms("Knowledge_Base.xml"); for (Term term : terms) { addDoc(writer, term.getDef(), term.getIs_a(), term.getSynonym()); } writer.close(); } public static ArrayList<String> findSynonyms(String query, int k) throws Exception { // 0. create the index //indexing(); // The same analyzer should be used for indexing and searching StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_35); String indexLocation = "knowledge"; // 1. open the index Directory index = FSDirectory.open(new File(indexLocation)); // 2. query Query q = new QueryParser(Version.LUCENE_35, "name", analyzer).parse(query); // 3. search IndexReader reader = IndexReader.open(index); IndexSearcher searcher = new IndexSearcher(reader); TopScoreDocCollector collector = TopScoreDocCollector.create(k, true); searcher.search(q, collector); ScoreDoc[] hits = collector.topDocs().scoreDocs; // 4. display results //System.out.println("Found: "+ hits.length + "hits"); ArrayList<String> synonyms = new ArrayList<String>(); for (int j = 0; j < hits.length; ++j) { int docId = hits[j].doc; org.apache.lucene.document.Document d = searcher.doc(docId); String syn = d.get("synonym").replace("(", "").replace(")", "").replace(":", ""); synonyms.add(syn.split("#")[0]); } searcher.close(); reader.close(); return synonyms; } private static void addDoc(IndexWriter writer, String name, String is_a, ArrayList<String> synonyms) throws IOException { org.apache.lucene.document.Document doc = new org.apache.lucene.document.Document(); Field namefield = new Field("name", name, Field.Store.YES, Field.Index.ANALYZED); Field is_afield = new Field("is_a", is_a, Field.Store.YES, Field.Index.ANALYZED); String syn = ""; for (String synonym : synonyms) { syn += synonym + "#"; } //remove last # if (syn.length() > 0) { syn = syn.substring(0, syn.length() - 1); } Field synonymfield = new Field("synonym", syn, Field.Store.YES, Field.Index.ANALYZED); doc.add(namefield); doc.add(is_afield); doc.add(synonymfield); writer.addDocument(doc); } private static List<Term> parseTerms(String fl) throws Exception { List<Term> terms = new ArrayList<Term>(); //Δημιουργία του<SUF> DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); //Parse fil to DOM Tree Document doc = dBuilder.parse(fl); //Διαβάσμα του root κόμβου Element rootElement = doc.getDocumentElement(); System.out.println("Root element :" + rootElement.getNodeName()); //Παίρνουμε όλα τα elements <user> NodeList nList = doc.getElementsByTagName("term"); for (int n = 0; n < nList.getLength(); n++) { Node nNode = nList.item(n); Element eElement = (Element) nNode; //Διαβάζουμε τα στοιχεία που βρίσκονται στα tags κάτω από κάθε user //element ArrayList<String> namelist = getTagValue("name", eElement); ArrayList<String> deflist = getTagValue("def", eElement); ArrayList<String> is_alist = getTagValue("is_a", eElement); ArrayList<String> synonyms = getTagValue("synonym", eElement); String name = listToString(namelist); String def = listToString(deflist); name += def; String is_a = listToString(is_alist); //Δημιουργούμε ένα object Temr με τα στοιχεία που διαβάσαμε Term term = new Term(name, synonyms, is_a); terms.add(term); } return terms; } /*** * Επιστρέφει το κείμενο που βρίσκεται ανάμεσα στo <stag></stag> * * @param sTag * @param eElement το parent node (tag element) * @return */ private static ArrayList<String> getTagValue(String sTag, Element eElement) { ArrayList<String> output = new ArrayList<String>(); if (eElement.getElementsByTagName(sTag).item(0) != null) { NodeList nlList; if (eElement.getElementsByTagName(sTag).getLength() > 1) { for (int j = 0; j < eElement.getElementsByTagName(sTag).getLength(); j++) { nlList = eElement.getElementsByTagName(sTag).item(j).getChildNodes(); Node nValue = nlList.item(0); if (nValue != null) { output.add(nValue.getNodeValue()); } } return output; } else { nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes(); Node nValue = nlList.item(0); output.add(nValue.getNodeValue()); return output; } } else { return output; } } private static String listToString(List<String> list) { String output = ""; for (String item : list) { output = output + " " + item; } return output; } }
2320_1
package thesis; import java.io.File; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Scanner; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; /** * @author Nektarios Gkouvousis * @author ice18390193 * * Η κλάση Definitions είναι υπεύθυνη για την διαχείριση και την αποθήκευση πληροφοριών * που αφορούν διαδρομές (paths) αρχείων ή φακέλων του προγράμματος. Επιπλέον, περιλαμβάνει * τις ονομασίες των αρχείων και των φύλλων του excel που θα χρησιμοποιηθούν. * Τέλος, κληρονομεί από την κλάση JFrame μεθόδους ώστε να γίνει η πρώτη αρχικοποίηση * στο μονοπάτι του προγράμματος (εάν χρειάζεται). */ public class Definitions extends JFrame{ private static String folderPath = ""; private static String settingsFile = "config.txt"; private static String genericFile = "1) General.xlsx"; private static String professorsAvailabilityFile = "TEST2.xlsx"; private static String classroomsAvailabilityFile = "TEST3.xlsx"; private static String examScheduleFile = "ΠΡΟΓΡΑΜΜΑ.xlsx"; private static String sheet1 = "PROFESSORS"; private static String sheet2 = "TIMESLOTS"; private static String sheet3 = "DATES"; private static String sheet4 = "CLASSROOMS"; private static String sheet5 = "COURSES"; private static String sheet6 = "COURSES_PROFESSORS"; private static String sheet7 = "ΠΡΟΓΡΑΜΜΑ ΕΞΕΤΑΣΤΙΚΗΣ"; private static String sheet8 = "ΠΡΟΓΡΑΜΜΑ ΑΙΘΟΥΣΩΝ"; public void Definitions(){ } /** * Έναρξη της διαδικασίας εκκίνησης του προγράμματος. Ελέγχεται εάν το αρχείο * ρυθμίσεων υπάρχει και εκκινεί την εφαρμογή ανάλογα με την ύπαρξή του. Σε * περίπτωση που δεν υπάρχει, το πρόγραμμα θα καλωσορίσει τον χρήστη στην εφαρμογή * και θα τον παροτρύνει να ορίσει έναν φάκελο ως workind directory. */ public void startProcess(){ if (!configFileExists()){ if (JOptionPane.NO_OPTION == JOptionPane.showConfirmDialog(this, "Καλωσήρθατε στο βοήθημα για την παραγωγή του προγράμματος εξετάσεων!" + " Παρακαλώ επιλέξτε τον φάκελο στον οποίο θα γίνεται η επεξεργασία των αρχείων εισόδου/εξόδου.", "Μήνυμα Εφαρμογής", JOptionPane.OK_OPTION)) { System.exit(0); }else{ promptUserForFolder(); } }else{ loadWorkingDirectory(); } } public void Definitions(String x){ this.folderPath = x; } public void setSettingsFile(String tmp){ settingsFile = tmp; } public String getSettingsFile(){ return settingsFile; } public void setFolderPath(String tmp){ folderPath = tmp; } public String getFolderPath(){ return folderPath; } public void setGenericFile(String tmp){ genericFile = tmp; } public String getGenericFile(){ return genericFile; } public void setConfigFile(String tmp){ settingsFile = tmp; } public String getConfigFile(){ return settingsFile; } public String getProfessorsAvailabilityFile(){ return professorsAvailabilityFile; } public String getClassroomsAvailabilityFile(){ return classroomsAvailabilityFile; } public void setExamScheduleFile(String x){ examScheduleFile = x; } public String getExamScheduleFile(){ return examScheduleFile; } public String getSheet1() { return sheet1; } public static void setSheet1(String sheet1) { Definitions.sheet1 = sheet1; } public String getSheet2() { return sheet2; } public static void setSheet2(String sheet2) { Definitions.sheet2 = sheet2; } public String getSheet3() { return sheet3; } public static void setSheet3(String sheet3) { Definitions.sheet3 = sheet3; } public String getSheet4() { return sheet4; } public static void setSheet4(String sheet4) { Definitions.sheet4 = sheet4; } public String getSheet5() { return sheet5; } public static void setSheet5(String sheet5) { Definitions.sheet5 = sheet5; } public String getSheet6() { return sheet6; } public static void setSheet6(String sheet6) { Definitions.sheet6 = sheet6; } public String getSheet7() { return sheet7; } public static void setSheet7(String sheet7) { Definitions.sheet7 = sheet7; } public String getSheet8() { return sheet8; } public static void setSheet8(String sheet8) { Definitions.sheet8 = sheet8; } /** * Ελέγχει εάν το αρχείο ρυθμίσεων υπάρχει. * * @return true αν το αρχείο ρυθμίσεων υπάρχει, αλλιώς false (boolean) */ private static boolean configFileExists(){ return Files.exists(Paths.get(settingsFile)); } /** * Ελέγχει εάν το αρχείο προγράμματος εξετάσεων υπάρχει στον τρέχοντα φάκελο. * * @return true αν το αρχείο προγράμματος εξετάσεων υπάρχει, αλλιώς false (boolean). */ public boolean examScheduleFileExists(){ return Files.exists(Paths.get(folderPath + "\\" + examScheduleFile )); } /** * Επιστρέφει τον τρέχοντα κατάλογο της εφαρμογής. * * @return Ο τρέχοντας κατάλογος. */ public String CurrentDirectory(){ return System.getProperty("user.dir"); } /** * Ζητά από τον χρήστη να επιλέξει έναν φάκελο για αποθήκευση. */ public void promptUserForFolder() { try{ JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int result = fileChooser.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) { File selectedFolder = fileChooser.getSelectedFile(); folderPath = selectedFolder.toString(); saveConfigFile(); } }catch (Exception ex){ JOptionPane.showMessageDialog(this, "Πρόβλημα κατά την διαδικασία ενημέρωσης του workind directory.", "Μήνυμα Εφαρμογής", JOptionPane.OK_OPTION); } } /** * Αποθηκεύει τον επιλεγμένο φάκελο στο αρχείο ρυθμίσεων. */ public void saveConfigFile() { if(folderPath != null){ try (PrintWriter out = new PrintWriter(settingsFile)) { out.println(folderPath); } catch (Exception e) { return; } }else{ System.out.println("Cannot save a null folder path"); } } /** * Φορτώνει τον τρέχοντα κατάλογο από το αρχείο ρυθμίσεων διαβάζοντας το αρχείο * ρυθμίσεων. */ public void loadWorkingDirectory() { try (Scanner scanner = new Scanner(new File(settingsFile))) { if (scanner.hasNextLine()) { folderPath = Paths.get(scanner.nextLine()).toString(); } } catch (Exception e) { folderPath = null; } } }
Gouvo7/Exam-Schedule-Creator
src/thesis/Definitions.java
2,645
/** * Έναρξη της διαδικασίας εκκίνησης του προγράμματος. Ελέγχεται εάν το αρχείο * ρυθμίσεων υπάρχει και εκκινεί την εφαρμογή ανάλογα με την ύπαρξή του. Σε * περίπτωση που δεν υπάρχει, το πρόγραμμα θα καλωσορίσει τον χρήστη στην εφαρμογή * και θα τον παροτρύνει να ορίσει έναν φάκελο ως workind directory. */
block_comment
el
package thesis; import java.io.File; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Scanner; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; /** * @author Nektarios Gkouvousis * @author ice18390193 * * Η κλάση Definitions είναι υπεύθυνη για την διαχείριση και την αποθήκευση πληροφοριών * που αφορούν διαδρομές (paths) αρχείων ή φακέλων του προγράμματος. Επιπλέον, περιλαμβάνει * τις ονομασίες των αρχείων και των φύλλων του excel που θα χρησιμοποιηθούν. * Τέλος, κληρονομεί από την κλάση JFrame μεθόδους ώστε να γίνει η πρώτη αρχικοποίηση * στο μονοπάτι του προγράμματος (εάν χρειάζεται). */ public class Definitions extends JFrame{ private static String folderPath = ""; private static String settingsFile = "config.txt"; private static String genericFile = "1) General.xlsx"; private static String professorsAvailabilityFile = "TEST2.xlsx"; private static String classroomsAvailabilityFile = "TEST3.xlsx"; private static String examScheduleFile = "ΠΡΟΓΡΑΜΜΑ.xlsx"; private static String sheet1 = "PROFESSORS"; private static String sheet2 = "TIMESLOTS"; private static String sheet3 = "DATES"; private static String sheet4 = "CLASSROOMS"; private static String sheet5 = "COURSES"; private static String sheet6 = "COURSES_PROFESSORS"; private static String sheet7 = "ΠΡΟΓΡΑΜΜΑ ΕΞΕΤΑΣΤΙΚΗΣ"; private static String sheet8 = "ΠΡΟΓΡΑΜΜΑ ΑΙΘΟΥΣΩΝ"; public void Definitions(){ } /** * Έναρξη της διαδικασίας<SUF>*/ public void startProcess(){ if (!configFileExists()){ if (JOptionPane.NO_OPTION == JOptionPane.showConfirmDialog(this, "Καλωσήρθατε στο βοήθημα για την παραγωγή του προγράμματος εξετάσεων!" + " Παρακαλώ επιλέξτε τον φάκελο στον οποίο θα γίνεται η επεξεργασία των αρχείων εισόδου/εξόδου.", "Μήνυμα Εφαρμογής", JOptionPane.OK_OPTION)) { System.exit(0); }else{ promptUserForFolder(); } }else{ loadWorkingDirectory(); } } public void Definitions(String x){ this.folderPath = x; } public void setSettingsFile(String tmp){ settingsFile = tmp; } public String getSettingsFile(){ return settingsFile; } public void setFolderPath(String tmp){ folderPath = tmp; } public String getFolderPath(){ return folderPath; } public void setGenericFile(String tmp){ genericFile = tmp; } public String getGenericFile(){ return genericFile; } public void setConfigFile(String tmp){ settingsFile = tmp; } public String getConfigFile(){ return settingsFile; } public String getProfessorsAvailabilityFile(){ return professorsAvailabilityFile; } public String getClassroomsAvailabilityFile(){ return classroomsAvailabilityFile; } public void setExamScheduleFile(String x){ examScheduleFile = x; } public String getExamScheduleFile(){ return examScheduleFile; } public String getSheet1() { return sheet1; } public static void setSheet1(String sheet1) { Definitions.sheet1 = sheet1; } public String getSheet2() { return sheet2; } public static void setSheet2(String sheet2) { Definitions.sheet2 = sheet2; } public String getSheet3() { return sheet3; } public static void setSheet3(String sheet3) { Definitions.sheet3 = sheet3; } public String getSheet4() { return sheet4; } public static void setSheet4(String sheet4) { Definitions.sheet4 = sheet4; } public String getSheet5() { return sheet5; } public static void setSheet5(String sheet5) { Definitions.sheet5 = sheet5; } public String getSheet6() { return sheet6; } public static void setSheet6(String sheet6) { Definitions.sheet6 = sheet6; } public String getSheet7() { return sheet7; } public static void setSheet7(String sheet7) { Definitions.sheet7 = sheet7; } public String getSheet8() { return sheet8; } public static void setSheet8(String sheet8) { Definitions.sheet8 = sheet8; } /** * Ελέγχει εάν το αρχείο ρυθμίσεων υπάρχει. * * @return true αν το αρχείο ρυθμίσεων υπάρχει, αλλιώς false (boolean) */ private static boolean configFileExists(){ return Files.exists(Paths.get(settingsFile)); } /** * Ελέγχει εάν το αρχείο προγράμματος εξετάσεων υπάρχει στον τρέχοντα φάκελο. * * @return true αν το αρχείο προγράμματος εξετάσεων υπάρχει, αλλιώς false (boolean). */ public boolean examScheduleFileExists(){ return Files.exists(Paths.get(folderPath + "\\" + examScheduleFile )); } /** * Επιστρέφει τον τρέχοντα κατάλογο της εφαρμογής. * * @return Ο τρέχοντας κατάλογος. */ public String CurrentDirectory(){ return System.getProperty("user.dir"); } /** * Ζητά από τον χρήστη να επιλέξει έναν φάκελο για αποθήκευση. */ public void promptUserForFolder() { try{ JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int result = fileChooser.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) { File selectedFolder = fileChooser.getSelectedFile(); folderPath = selectedFolder.toString(); saveConfigFile(); } }catch (Exception ex){ JOptionPane.showMessageDialog(this, "Πρόβλημα κατά την διαδικασία ενημέρωσης του workind directory.", "Μήνυμα Εφαρμογής", JOptionPane.OK_OPTION); } } /** * Αποθηκεύει τον επιλεγμένο φάκελο στο αρχείο ρυθμίσεων. */ public void saveConfigFile() { if(folderPath != null){ try (PrintWriter out = new PrintWriter(settingsFile)) { out.println(folderPath); } catch (Exception e) { return; } }else{ System.out.println("Cannot save a null folder path"); } } /** * Φορτώνει τον τρέχοντα κατάλογο από το αρχείο ρυθμίσεων διαβάζοντας το αρχείο * ρυθμίσεων. */ public void loadWorkingDirectory() { try (Scanner scanner = new Scanner(new File(settingsFile))) { if (scanner.hasNextLine()) { folderPath = Paths.get(scanner.nextLine()).toString(); } } catch (Exception e) { folderPath = null; } } }
46538_0
package gr.aueb.cf.ch3; import java.util.Scanner; /** * οσο ο χρηστης δινει θετικους ακεραιους * τους μετραμε μεχρι ο χρηστης να δωσει αρνιτικο */ public class PositiveCoutApp { public static void main(String[] args) { int inputNum = 0; int count = 0; Scanner scanner = new Scanner(System.in); System.out.println("Please insert a num (negative for Quit"); inputNum = scanner.nextInt(); while (inputNum >= 0){ count++; System.out.println("Please insert a num (negative for Quit"); inputNum = scanner.nextInt(); } System.out.println("Count" + count); } }
GregoryPerifanos/Coding-Factory-5-Class-Projects
src/gr/aueb/cf/ch3/PositiveCoutApp.java
233
/** * οσο ο χρηστης δινει θετικους ακεραιους * τους μετραμε μεχρι ο χρηστης να δωσει αρνιτικο */
block_comment
el
package gr.aueb.cf.ch3; import java.util.Scanner; /** * οσο ο χρηστης<SUF>*/ public class PositiveCoutApp { public static void main(String[] args) { int inputNum = 0; int count = 0; Scanner scanner = new Scanner(System.in); System.out.println("Please insert a num (negative for Quit"); inputNum = scanner.nextInt(); while (inputNum >= 0){ count++; System.out.println("Please insert a num (negative for Quit"); inputNum = scanner.nextInt(); } System.out.println("Count" + count); } }
30561_2
package gr.aueb.cf.exercise.Project; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Project1 { public static int numLine = 0; public static void main(String[] args) { try { // Διαβάζουμε τους αριθμούς από το αρχείο int[] numbers = readNumbersFromFile("E:/input.txt"); // Ταξινομούμε τον πίνακα Arrays.sort(numbers); // Αναζητούμε και εκτυπώνουμε τις εξάδες findAndPrintCombinations(numbers, "E:/output.txt"); } catch (IOException e) { e.printStackTrace(); } } public static int[] readNumbersFromFile(String filename) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(filename)); String line = reader.readLine(); // Read the entire line reader.close(); if (line == null || line.trim().isEmpty()) { System.err.println("Empty or invalid input file."); System.exit(1); } // Split the line into an array of strings String[] numberStrings = line.trim().split("\\s+"); // Convert the array of strings to an array of integers int[] numbers = new int[numberStrings.length]; for (int i = 0; i < numberStrings.length; i++) { try { numbers[i] = Integer.parseInt(numberStrings[i]); } catch (NumberFormatException e) { System.err.println("Skipping invalid number: " + numberStrings[i]); } } return numbers; } public static void findAndPrintCombinations(int[] numbers, String outputFileName) throws IOException { PrintWriter writer = new PrintWriter(new FileWriter(outputFileName)); for (int i = 0; i < numbers.length - 5; i++) { for (int j = i + 1; j < numbers.length - 4; j++) { for (int k = j + 1; k < numbers.length - 3; k++) { for (int l = k + 1; l < numbers.length - 2; l++) { for (int m = l + 1; m < numbers.length - 1; m++) { for (int n = m + 1; n < numbers.length; n++) { int[] combination = {numbers[i], numbers[j], numbers[k], numbers[l], numbers[m], numbers[n]}; if (isValidCombination(combination)) { printCombination(writer, combination); } } } } } } } writer.close(); } public static boolean isValidCombination(int[] combination) { return isAtMostNEven(combination, 4) && isAtMostNOdd(combination, 4) && hasAtMostNConsecutive(combination, 2) && hasAtMostNSameEnding(combination, 3) && hasAtMostNInSameTen(combination, 3); } public static boolean isAtMostNEven(int[] combination, int n) { int count = 0; for (int num : combination) { if (num % 2 == 0) { count++; if (count > n) { return false; } } } return true; } public static boolean isAtMostNOdd(int[] combination, int n) { int count = 0; for (int num : combination) { if (num % 2 != 0) { count++; if (count > n) { return false; } } } return true; } public static boolean hasAtMostNConsecutive(int[] combination, int n) { Arrays.sort(combination); int count = 1; for (int i = 1; i < combination.length; i++) { if (combination[i] == combination[i - 1] + 1) { count++; if (count > n) { return false; } } else { count = 1; } } return true; } public static boolean hasAtMostNSameEnding(int[] combination, int n) { int count = 1; for (int i = 1; i < combination.length; i++) { if (combination[i] % 10 == combination[i - 1] % 10) { count++; if (count > n) { return false; } } else { count = 1; } } return true; } public static boolean hasAtMostNInSameTen(int[] combination, int n) { Arrays.sort(combination); int count = 1; for (int i = 1; i < combination.length; i++) { if (combination[i] / 10 == combination[i - 1] / 10) { count++; if (count > n) { return false; } } else { count = 1; } } return true; } public static void printCombination(PrintWriter writer, int[] combination) { numLine++; writer.print(numLine+": "); for (int num : combination) { writer.print(num + " "); } writer.println(); } }
GregoryPerifanos/java-oo-projects
exercise/Project/Project1.java
1,294
// Αναζητούμε και εκτυπώνουμε τις εξάδες
line_comment
el
package gr.aueb.cf.exercise.Project; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Project1 { public static int numLine = 0; public static void main(String[] args) { try { // Διαβάζουμε τους αριθμούς από το αρχείο int[] numbers = readNumbersFromFile("E:/input.txt"); // Ταξινομούμε τον πίνακα Arrays.sort(numbers); // Αναζητούμε και<SUF> findAndPrintCombinations(numbers, "E:/output.txt"); } catch (IOException e) { e.printStackTrace(); } } public static int[] readNumbersFromFile(String filename) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(filename)); String line = reader.readLine(); // Read the entire line reader.close(); if (line == null || line.trim().isEmpty()) { System.err.println("Empty or invalid input file."); System.exit(1); } // Split the line into an array of strings String[] numberStrings = line.trim().split("\\s+"); // Convert the array of strings to an array of integers int[] numbers = new int[numberStrings.length]; for (int i = 0; i < numberStrings.length; i++) { try { numbers[i] = Integer.parseInt(numberStrings[i]); } catch (NumberFormatException e) { System.err.println("Skipping invalid number: " + numberStrings[i]); } } return numbers; } public static void findAndPrintCombinations(int[] numbers, String outputFileName) throws IOException { PrintWriter writer = new PrintWriter(new FileWriter(outputFileName)); for (int i = 0; i < numbers.length - 5; i++) { for (int j = i + 1; j < numbers.length - 4; j++) { for (int k = j + 1; k < numbers.length - 3; k++) { for (int l = k + 1; l < numbers.length - 2; l++) { for (int m = l + 1; m < numbers.length - 1; m++) { for (int n = m + 1; n < numbers.length; n++) { int[] combination = {numbers[i], numbers[j], numbers[k], numbers[l], numbers[m], numbers[n]}; if (isValidCombination(combination)) { printCombination(writer, combination); } } } } } } } writer.close(); } public static boolean isValidCombination(int[] combination) { return isAtMostNEven(combination, 4) && isAtMostNOdd(combination, 4) && hasAtMostNConsecutive(combination, 2) && hasAtMostNSameEnding(combination, 3) && hasAtMostNInSameTen(combination, 3); } public static boolean isAtMostNEven(int[] combination, int n) { int count = 0; for (int num : combination) { if (num % 2 == 0) { count++; if (count > n) { return false; } } } return true; } public static boolean isAtMostNOdd(int[] combination, int n) { int count = 0; for (int num : combination) { if (num % 2 != 0) { count++; if (count > n) { return false; } } } return true; } public static boolean hasAtMostNConsecutive(int[] combination, int n) { Arrays.sort(combination); int count = 1; for (int i = 1; i < combination.length; i++) { if (combination[i] == combination[i - 1] + 1) { count++; if (count > n) { return false; } } else { count = 1; } } return true; } public static boolean hasAtMostNSameEnding(int[] combination, int n) { int count = 1; for (int i = 1; i < combination.length; i++) { if (combination[i] % 10 == combination[i - 1] % 10) { count++; if (count > n) { return false; } } else { count = 1; } } return true; } public static boolean hasAtMostNInSameTen(int[] combination, int n) { Arrays.sort(combination); int count = 1; for (int i = 1; i < combination.length; i++) { if (combination[i] / 10 == combination[i - 1] / 10) { count++; if (count > n) { return false; } } else { count = 1; } } return true; } public static void printCombination(PrintWriter writer, int[] combination) { numLine++; writer.print(numLine+": "); for (int num : combination) { writer.print(num + " "); } writer.println(); } }
5831_75
package org.oxford.comlab.perfectref.rewriter; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import edu.ntua.image.datastructures.Tree; import edu.ntua.image.datastructures.TreeNode; public class Saturator_Tree { private TermFactory m_termFactory; protected ArrayList<TreeNode<Clause>> m_nodesAddedToTree; protected ArrayList<Clause> m_unprocessedClauses; private ArrayList<TreeNode<Clause>> m_unprocessedNodes; private Map<String,TreeNode<Clause>> m_canonicalsToDAGNodes; // private Variable lostVariable; // public Variable getLostVariable() { // return lostVariable; // } private int skolemIndex = 0;; public Saturator_Tree(TermFactory termFactory) { m_termFactory = termFactory; m_unprocessedClauses = new ArrayList<Clause>(); m_nodesAddedToTree = new ArrayList<TreeNode<Clause>>(); m_canonicalsToDAGNodes = new HashMap<String,TreeNode<Clause>>(); } public Clause getNewQuery(PI pi, int atomIndex, Clause clause){ Term newAtom = null; Term g = clause.getBody()[atomIndex]; // lostVariable = null; if(g.getArity() == 1){ Variable var1 = (Variable)g.getArguments()[0]; if(pi.m_right.equals(g.getName())) switch(pi.m_type){ case 1: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var1.m_index)); break; case 4: // if ( clauseContainsVarLargerThan( clause , 500 ) ) newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500+(skolemIndex++))}); // else // newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500)}); break; case 7: // if (clauseContainsVarLargerThan( clause , 500 ) ) newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500+(skolemIndex++)), this.m_termFactory.getVariable(var1.m_index)}); // else // newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500), this.m_termFactory.getVariable(var1.m_index)}); break; default: return null; } else return null; } // Binary atom else{ Variable var1 = (Variable)g.getArguments()[0]; Variable var2 = (Variable)g.getArguments()[1]; if(pi.m_right.equals(g.getName())){ if(!clause.isBound(var2)) switch(pi.m_type){ case 2: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var1.m_index)); // lostVariable = var2; break; case 5: // if ( clauseContainsVarLargerThan( clause , 500 ) ) newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500+(skolemIndex++))}); // else // newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500)}); break; case 8: // if ( clauseContainsVarLargerThan( clause , 500 ) ) newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500+(skolemIndex++)), this.m_termFactory.getVariable(var1.m_index)}); // else // newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500), this.m_termFactory.getVariable(var1.m_index)}); break; case 10: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)}); break; case 11: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)}); break; default: return null; } else if(!clause.isBound(var1)) switch(pi.m_type){ case 3: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var2.m_index)); // lostVariable = var1; break; case 6: // if ( clauseContainsVarLargerThan( clause, 500 ) ) newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(500+(skolemIndex++))}); // else // newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(500)}); break; case 9: // if ( clauseContainsVarLargerThan( clause , 500 ) ) newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500+(skolemIndex++)), this.m_termFactory.getVariable(var2.m_index)}); // else // newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500), this.m_termFactory.getVariable(var2.m_index)}); break; case 10: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)}); break; case 11: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)}); break; default: return null; } else switch (pi.m_type) { case 10: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)}); break; case 11: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)}); break; default: return null; } } else return null; } Set<Term> newBody = new LinkedHashSet<Term>(); newBody.add(newAtom); // Copy the other atoms from the clause for (int index=0; index < clause.getBody().length; index++) if (index != atomIndex) newBody.add(clause.getBody()[index].apply(Substitution.IDENTITY, this.m_termFactory)); // New body and head Term[] body = new Term[newBody.size()]; newBody.toArray(body); Term head = clause.getHead().apply(Substitution.IDENTITY, this.m_termFactory); Clause newQuery = new Clause(body, head); // // Rename variables in resolvent // ArrayList<Variable> variablesNewQuery = newQuery.getVariables(); // // HashMap<Variable,Integer> variableMapping = new HashMap<Variable,Integer>(); // for(int i=0; i < variablesNewQuery.size(); i++) // variableMapping.put(variablesNewQuery.get(i),i); // // Clause newQueryRenamed = newQuery.renameVariables(this.m_termFactory, variableMapping); return newQuery; } public Clause getNewQueryForIncremental(PI pi, int atomIndex, Clause clause, int localSkolem){ Term newAtom = null; Term g = clause.getBody()[atomIndex]; // lostVariable = null; if(g.getArity() == 1){ Variable var1 = (Variable)g.getArguments()[0]; if(pi.m_right.equals(g.getName())) switch(pi.m_type){ case 1: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var1.m_index)); break; case 4: // if ( clauseContainsVarLargerThan( clause , 500 ) ) newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500+(localSkolem))}); // else // newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500)}); break; case 7: // if (clauseContainsVarLargerThan( clause , 500 ) ) newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500+(localSkolem)), this.m_termFactory.getVariable(var1.m_index)}); // else // newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500), this.m_termFactory.getVariable(var1.m_index)}); break; default: return null; } else return null; } // Binary atom else{ Variable var1 = (Variable)g.getArguments()[0]; Variable var2 = (Variable)g.getArguments()[1]; if(pi.m_right.equals(g.getName())){ if(!clause.isBound(var2)) switch(pi.m_type){ case 2: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var1.m_index)); // lostVariable = var2; break; case 5: // if ( clauseContainsVarLargerThan( clause , 500 ) ) newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500+(localSkolem))}); // else // newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500)}); break; case 8: // if ( clauseContainsVarLargerThan( clause , 500 ) ) newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500+(localSkolem)), this.m_termFactory.getVariable(var1.m_index)}); // else // newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500), this.m_termFactory.getVariable(var1.m_index)}); break; case 10: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)}); break; case 11: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)}); break; default: return null; } else if(!clause.isBound(var1)) switch(pi.m_type){ case 3: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var2.m_index)); // lostVariable = var1; break; case 6: // if ( clauseContainsVarLargerThan( clause, 500 ) ) newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(500+(localSkolem))}); // else // newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(500)}); break; case 9: // if ( clauseContainsVarLargerThan( clause , 500 ) ) newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500+(localSkolem)), this.m_termFactory.getVariable(var2.m_index)}); // else // newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500), this.m_termFactory.getVariable(var2.m_index)}); break; case 10: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)}); break; case 11: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)}); break; default: return null; } else switch (pi.m_type) { case 10: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)}); break; case 11: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)}); break; default: return null; } } else return null; } Set<Term> newBody = new LinkedHashSet<Term>(); newBody.add(newAtom); // Copy the other atoms from the clause for (int index=0; index < clause.getBody().length; index++) if (index != atomIndex) newBody.add(clause.getBody()[index].apply(Substitution.IDENTITY, this.m_termFactory)); // New body and head Term[] body = new Term[newBody.size()]; newBody.toArray(body); Term head = clause.getHead().apply(Substitution.IDENTITY, this.m_termFactory); Clause newQuery = new Clause(body, head); // // Rename variables in resolvent // ArrayList<Variable> variablesNewQuery = newQuery.getVariables(); // // HashMap<Variable,Integer> variableMapping = new HashMap<Variable,Integer>(); // for(int i=0; i < variablesNewQuery.size(); i++) // variableMapping.put(variablesNewQuery.get(i),i); // // Clause newQueryRenamed = newQuery.renameVariables(this.m_termFactory, variableMapping); return newQuery; } private boolean clauseContainsVarLargerThan(Clause clause , int max) { for ( Variable var : clause.getVariables() ) if ( Integer.parseInt( var.toString().substring( 1 , var.toString().length() ) ) >= max ) return true; return false; } /** * Creates a new query by applying the mgu of two atoms to a given query */ private Clause getNewQuery(Substitution mgu, Clause clause){ Set<Term> newBody = new LinkedHashSet<Term>(); //Copy the atoms from the main premise /* * CHECK HERE * * I arxiki de douleuei swsta me to paradeigma TestABC */ for (int index=0; index < clause.getBody().length; index++) // boolean exists = false; // for (Iterator<Term> iter = newBody.iterator() ; iter.hasNext() ;) // if ( iter.next().toString().equals(clause.getBody()[index].apply(mgu, this.m_termFactory).toString()) ) // exists = true; // if (!exists) newBody.add(clause.getBody()[index].apply(mgu, this.m_termFactory)); //New body and head Term[] body = new Term[newBody.size()]; newBody.toArray(body); Term head = clause.getHead().apply(mgu, this.m_termFactory); Clause newQuery = new Clause(body, head); return newQuery; // Substitution sub = new Substitution(); // //Rename variables in new query // boolean rename = true; // ArrayList<Variable> variablesNewQuery = newQuery.getVariables(); // HashMap<Variable,Integer> variableMapping = new HashMap<Variable,Integer>(); // for(int i=0; i < variablesNewQuery.size(); i++) { // variableMapping.put(variablesNewQuery.get(i), i); // if ( ( Integer.parseInt( variablesNewQuery.get( i ).toString().substring( 1 , variablesNewQuery.get( i ).toString().length() ) ) >= 500 ) ) { // rename = false; // return newQuery; // } //// if ( !( Integer.parseInt( variablesNewQuery.get( i ).toString().substring( 1 , variablesNewQuery.get( i ).toString().length() ) ) >= 500 ) ) //// sub.put(variablesNewQuery.get(i), new Variable( i ) ); // } // // Clause newQueryRenamed = newQuery.renameVariables(this.m_termFactory, variableMapping); // // if ( newQueryRenamed.m_canonicalRepresentation.contains("degreeFrom(X1,X2) ^ headOf(X0,X2)") ) // System.out.println( newQuery + "\t\t" + variableMapping ); // // //avenet //// newQueryRenamed.addUnification( sub ); // // return newQueryRenamed; } /** * Checks if a given clause is contained in m_clausesCanonicals based on its naive canonical representation */ public TreeNode<Clause> getEquivalentNodeAlreadyInDAG(TreeNode<Clause> newNode) { /** * Option 1 */ // Node<Clause> nodeInTree = m_canonicalsToDAGNodes.get(newNode.getNodeLabel().m_canonicalRepresentation); // if( nodeInTree !=null ) // return nodeInTree; /** * Option 2 */ TreeNode<Clause> nodeInTree = m_canonicalsToDAGNodes.get(newNode.getNodeLabel().m_canonicalRepresentation); if( nodeInTree !=null ) return nodeInTree; for (TreeNode<Clause> nodeInRewritingTree : m_nodesAddedToTree) if (nodeInRewritingTree.getNodeLabel().isEquivalentUpToVariableRenaming(newNode.getNodeLabel())) return nodeInRewritingTree; /** * Option 3 */ // for (Node<Clause> nodeInRewritingTree : m_nodesAddedToTree) // if (nodeInRewritingTree.getNodeLabel().isEquivalentUpToVariableRenaming(newNode.getNodeLabel())) // return nodeInRewritingTree; return null; } /** * Η συνάρτηση αυτή δεν περιέχει όλους τους κανόνες που υπάρχουν στην getNewQuery επειδή όταν μας δίνεται ένα άτομο R(x,y) σαν extraAtom τότε μας ενδιαφέρουν να υπάρχουν και οι 2 μεταβλητές. * Η συνάρτηση αυτή στην refine χρησιμοποιείται σε συνδυασμό με τον έλγχο για το εάν το clause στο οποίο πάμε να κάνουμε refine περιέχει κάποια από τις μεταβλητές που έχει το άτομο (clause) * που παράγεται από αυτή τη συνάρτηση. * @param pi * @param clause * @return */ public Clause getSubsumees(PI pi , Clause clause ){ Term newAtom = null; Term g = clause.getBody()[0]; int gArity = g.getArity(); String name = g.getName(); if(gArity == 1){ Variable var1 = (Variable)g.getArguments()[0]; if(pi.m_right.equals( name )) switch(pi.m_type){ case 1: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var1.m_index)); break; case 4: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(50000)}); break; case 7: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(50000), this.m_termFactory.getVariable(var1.m_index)}); break; default: return null; } else return null; } else{ Variable var1 = (Variable)g.getArguments()[0]; Variable var2 = (Variable)g.getArguments()[1]; if(pi.m_right.equals( name )) // if(!clause.isBound(var2)){ switch(pi.m_type){ case 2: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var1.m_index)); break; case 3: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var2.m_index)); break; case 5: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(50000)}); break; case 6: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(50000)}); break; case 8: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(50000), this.m_termFactory.getVariable(var1.m_index)}); break; case 9: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(50000), this.m_termFactory.getVariable(var2.m_index)}); break; case 10: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)}); break; case 11: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)}); break; default: return null; // } } else return null; } Term [] body = new Term[1]; body[0] = newAtom; return new Clause ( body, clause.getHead() ); } public Tree<Clause> saturate(ArrayList<PI> pis, Clause query) { m_unprocessedNodes = new ArrayList<TreeNode<Clause>>(); TreeNode<Clause> givenNode; TreeNode<Clause> rootElement = new TreeNode<Clause>( query ); Tree<Clause> rewritingDAG = new Tree<Clause>(rootElement) ; m_unprocessedNodes.add(rootElement); while (!m_unprocessedNodes.isEmpty()) { givenNode = m_unprocessedNodes.remove( 0 ); Clause givenClause = givenNode.getNodeLabel(); // System.out.println( "m_nodesAddedToTree contains " + givenNode.getNodeLabel() + " is " + m_nodesAddedToTree.contains( givenNode ) ); m_nodesAddedToTree.add(givenNode); for (int i = 0; i < givenClause.getBody().length; i++) for (PI pi: pis) { Clause newQuery = getNewQuery(pi, i, givenClause); if (newQuery!=null) { TreeNode<Clause> newNode = new TreeNode<Clause>( newQuery ); TreeNode<Clause> nodeInRewritingDAG = getEquivalentNodeAlreadyInDAG(newNode); if (nodeInRewritingDAG==null) { for ( Substitution s : givenNode.getNodeLabel().getUnifications() ) newNode.getNodeLabel().addUnification( s ); givenNode.addChild(newNode); m_unprocessedNodes.add(newNode); m_nodesAddedToTree.add(newNode); m_canonicalsToDAGNodes.put(newQuery.m_canonicalRepresentation, newNode); } //if commented on june 8th else //if (!nodeInRewritingDAG.getSubTree().contains(givenNode)) givenNode.addChild( nodeInRewritingDAG ); } } for (int i = 0; i < givenClause.getBody().length - 1; i++) for (int j = i+1; j < givenClause.getBody().length; j++) { Substitution unifier = Substitution.mostGeneralUnifier(givenClause.getBody()[i], givenClause.getBody()[j], this.m_termFactory); // System.out.println( "GivenClause = " + givenClause + "\t\tUnifier = " + unifier + "\t\t" + givenClause.getBody()[i] + "\t\t" + givenClause.getBody()[j]); if (unifier!=null) { Clause newQuery = getNewQuery(unifier, givenClause); TreeNode<Clause> newNode = new TreeNode<Clause>( newQuery ); TreeNode<Clause> nodeInRewritingDAG = getEquivalentNodeAlreadyInDAG(newNode); if(nodeInRewritingDAG==null) { for ( Substitution s : givenNode.getNodeLabel().getUnifications() ) newNode.getNodeLabel().addUnification( s ); for ( Entry<Variable,Term> s : unifier.entrySet() ) { // if ( ! ( Integer.parseInt( s.getKey().toString().substring( 1 , s.getKey().toString().length() ) ) >= 500 || Integer.parseInt( s.getValue().toString().substring( 1 , s.getValue().toString().length() ) ) >= 500 ) ) { Substitution ns = new Substitution(); ns.put( s.getKey(), s.getValue() ); newNode.getNodeLabel().addUnification( ns ); } givenNode.addChild( newNode ); m_unprocessedNodes.add( newNode ); m_nodesAddedToTree.add( newNode ); m_canonicalsToDAGNodes.put(newQuery.m_canonicalRepresentation, newNode); } //if commented on june 8th else //if (!nodeInRewritingDAG.getSubTree().contains(givenNode)) givenNode.addChild( nodeInRewritingDAG ); } } } return rewritingDAG; } }
HBPMedical/MIPMapRew
src/org/oxford/comlab/perfectref/rewriter/Saturator_Tree.java
7,789
/** * Η συνάρτηση αυτή δεν περιέχει όλους τους κανόνες που υπάρχουν στην getNewQuery επειδή όταν μας δίνεται ένα άτομο R(x,y) σαν extraAtom τότε μας ενδιαφέρουν να υπάρχουν και οι 2 μεταβλητές. * Η συνάρτηση αυτή στην refine χρησιμοποιείται σε συνδυασμό με τον έλγχο για το εάν το clause στο οποίο πάμε να κάνουμε refine περιέχει κάποια από τις μεταβλητές που έχει το άτομο (clause) * που παράγεται από αυτή τη συνάρτηση. * @param pi * @param clause * @return */
block_comment
el
package org.oxford.comlab.perfectref.rewriter; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import edu.ntua.image.datastructures.Tree; import edu.ntua.image.datastructures.TreeNode; public class Saturator_Tree { private TermFactory m_termFactory; protected ArrayList<TreeNode<Clause>> m_nodesAddedToTree; protected ArrayList<Clause> m_unprocessedClauses; private ArrayList<TreeNode<Clause>> m_unprocessedNodes; private Map<String,TreeNode<Clause>> m_canonicalsToDAGNodes; // private Variable lostVariable; // public Variable getLostVariable() { // return lostVariable; // } private int skolemIndex = 0;; public Saturator_Tree(TermFactory termFactory) { m_termFactory = termFactory; m_unprocessedClauses = new ArrayList<Clause>(); m_nodesAddedToTree = new ArrayList<TreeNode<Clause>>(); m_canonicalsToDAGNodes = new HashMap<String,TreeNode<Clause>>(); } public Clause getNewQuery(PI pi, int atomIndex, Clause clause){ Term newAtom = null; Term g = clause.getBody()[atomIndex]; // lostVariable = null; if(g.getArity() == 1){ Variable var1 = (Variable)g.getArguments()[0]; if(pi.m_right.equals(g.getName())) switch(pi.m_type){ case 1: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var1.m_index)); break; case 4: // if ( clauseContainsVarLargerThan( clause , 500 ) ) newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500+(skolemIndex++))}); // else // newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500)}); break; case 7: // if (clauseContainsVarLargerThan( clause , 500 ) ) newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500+(skolemIndex++)), this.m_termFactory.getVariable(var1.m_index)}); // else // newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500), this.m_termFactory.getVariable(var1.m_index)}); break; default: return null; } else return null; } // Binary atom else{ Variable var1 = (Variable)g.getArguments()[0]; Variable var2 = (Variable)g.getArguments()[1]; if(pi.m_right.equals(g.getName())){ if(!clause.isBound(var2)) switch(pi.m_type){ case 2: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var1.m_index)); // lostVariable = var2; break; case 5: // if ( clauseContainsVarLargerThan( clause , 500 ) ) newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500+(skolemIndex++))}); // else // newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500)}); break; case 8: // if ( clauseContainsVarLargerThan( clause , 500 ) ) newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500+(skolemIndex++)), this.m_termFactory.getVariable(var1.m_index)}); // else // newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500), this.m_termFactory.getVariable(var1.m_index)}); break; case 10: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)}); break; case 11: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)}); break; default: return null; } else if(!clause.isBound(var1)) switch(pi.m_type){ case 3: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var2.m_index)); // lostVariable = var1; break; case 6: // if ( clauseContainsVarLargerThan( clause, 500 ) ) newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(500+(skolemIndex++))}); // else // newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(500)}); break; case 9: // if ( clauseContainsVarLargerThan( clause , 500 ) ) newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500+(skolemIndex++)), this.m_termFactory.getVariable(var2.m_index)}); // else // newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500), this.m_termFactory.getVariable(var2.m_index)}); break; case 10: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)}); break; case 11: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)}); break; default: return null; } else switch (pi.m_type) { case 10: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)}); break; case 11: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)}); break; default: return null; } } else return null; } Set<Term> newBody = new LinkedHashSet<Term>(); newBody.add(newAtom); // Copy the other atoms from the clause for (int index=0; index < clause.getBody().length; index++) if (index != atomIndex) newBody.add(clause.getBody()[index].apply(Substitution.IDENTITY, this.m_termFactory)); // New body and head Term[] body = new Term[newBody.size()]; newBody.toArray(body); Term head = clause.getHead().apply(Substitution.IDENTITY, this.m_termFactory); Clause newQuery = new Clause(body, head); // // Rename variables in resolvent // ArrayList<Variable> variablesNewQuery = newQuery.getVariables(); // // HashMap<Variable,Integer> variableMapping = new HashMap<Variable,Integer>(); // for(int i=0; i < variablesNewQuery.size(); i++) // variableMapping.put(variablesNewQuery.get(i),i); // // Clause newQueryRenamed = newQuery.renameVariables(this.m_termFactory, variableMapping); return newQuery; } public Clause getNewQueryForIncremental(PI pi, int atomIndex, Clause clause, int localSkolem){ Term newAtom = null; Term g = clause.getBody()[atomIndex]; // lostVariable = null; if(g.getArity() == 1){ Variable var1 = (Variable)g.getArguments()[0]; if(pi.m_right.equals(g.getName())) switch(pi.m_type){ case 1: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var1.m_index)); break; case 4: // if ( clauseContainsVarLargerThan( clause , 500 ) ) newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500+(localSkolem))}); // else // newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500)}); break; case 7: // if (clauseContainsVarLargerThan( clause , 500 ) ) newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500+(localSkolem)), this.m_termFactory.getVariable(var1.m_index)}); // else // newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500), this.m_termFactory.getVariable(var1.m_index)}); break; default: return null; } else return null; } // Binary atom else{ Variable var1 = (Variable)g.getArguments()[0]; Variable var2 = (Variable)g.getArguments()[1]; if(pi.m_right.equals(g.getName())){ if(!clause.isBound(var2)) switch(pi.m_type){ case 2: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var1.m_index)); // lostVariable = var2; break; case 5: // if ( clauseContainsVarLargerThan( clause , 500 ) ) newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500+(localSkolem))}); // else // newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(500)}); break; case 8: // if ( clauseContainsVarLargerThan( clause , 500 ) ) newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500+(localSkolem)), this.m_termFactory.getVariable(var1.m_index)}); // else // newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500), this.m_termFactory.getVariable(var1.m_index)}); break; case 10: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)}); break; case 11: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)}); break; default: return null; } else if(!clause.isBound(var1)) switch(pi.m_type){ case 3: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var2.m_index)); // lostVariable = var1; break; case 6: // if ( clauseContainsVarLargerThan( clause, 500 ) ) newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(500+(localSkolem))}); // else // newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(500)}); break; case 9: // if ( clauseContainsVarLargerThan( clause , 500 ) ) newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500+(localSkolem)), this.m_termFactory.getVariable(var2.m_index)}); // else // newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(500), this.m_termFactory.getVariable(var2.m_index)}); break; case 10: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)}); break; case 11: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)}); break; default: return null; } else switch (pi.m_type) { case 10: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)}); break; case 11: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)}); break; default: return null; } } else return null; } Set<Term> newBody = new LinkedHashSet<Term>(); newBody.add(newAtom); // Copy the other atoms from the clause for (int index=0; index < clause.getBody().length; index++) if (index != atomIndex) newBody.add(clause.getBody()[index].apply(Substitution.IDENTITY, this.m_termFactory)); // New body and head Term[] body = new Term[newBody.size()]; newBody.toArray(body); Term head = clause.getHead().apply(Substitution.IDENTITY, this.m_termFactory); Clause newQuery = new Clause(body, head); // // Rename variables in resolvent // ArrayList<Variable> variablesNewQuery = newQuery.getVariables(); // // HashMap<Variable,Integer> variableMapping = new HashMap<Variable,Integer>(); // for(int i=0; i < variablesNewQuery.size(); i++) // variableMapping.put(variablesNewQuery.get(i),i); // // Clause newQueryRenamed = newQuery.renameVariables(this.m_termFactory, variableMapping); return newQuery; } private boolean clauseContainsVarLargerThan(Clause clause , int max) { for ( Variable var : clause.getVariables() ) if ( Integer.parseInt( var.toString().substring( 1 , var.toString().length() ) ) >= max ) return true; return false; } /** * Creates a new query by applying the mgu of two atoms to a given query */ private Clause getNewQuery(Substitution mgu, Clause clause){ Set<Term> newBody = new LinkedHashSet<Term>(); //Copy the atoms from the main premise /* * CHECK HERE * * I arxiki de douleuei swsta me to paradeigma TestABC */ for (int index=0; index < clause.getBody().length; index++) // boolean exists = false; // for (Iterator<Term> iter = newBody.iterator() ; iter.hasNext() ;) // if ( iter.next().toString().equals(clause.getBody()[index].apply(mgu, this.m_termFactory).toString()) ) // exists = true; // if (!exists) newBody.add(clause.getBody()[index].apply(mgu, this.m_termFactory)); //New body and head Term[] body = new Term[newBody.size()]; newBody.toArray(body); Term head = clause.getHead().apply(mgu, this.m_termFactory); Clause newQuery = new Clause(body, head); return newQuery; // Substitution sub = new Substitution(); // //Rename variables in new query // boolean rename = true; // ArrayList<Variable> variablesNewQuery = newQuery.getVariables(); // HashMap<Variable,Integer> variableMapping = new HashMap<Variable,Integer>(); // for(int i=0; i < variablesNewQuery.size(); i++) { // variableMapping.put(variablesNewQuery.get(i), i); // if ( ( Integer.parseInt( variablesNewQuery.get( i ).toString().substring( 1 , variablesNewQuery.get( i ).toString().length() ) ) >= 500 ) ) { // rename = false; // return newQuery; // } //// if ( !( Integer.parseInt( variablesNewQuery.get( i ).toString().substring( 1 , variablesNewQuery.get( i ).toString().length() ) ) >= 500 ) ) //// sub.put(variablesNewQuery.get(i), new Variable( i ) ); // } // // Clause newQueryRenamed = newQuery.renameVariables(this.m_termFactory, variableMapping); // // if ( newQueryRenamed.m_canonicalRepresentation.contains("degreeFrom(X1,X2) ^ headOf(X0,X2)") ) // System.out.println( newQuery + "\t\t" + variableMapping ); // // //avenet //// newQueryRenamed.addUnification( sub ); // // return newQueryRenamed; } /** * Checks if a given clause is contained in m_clausesCanonicals based on its naive canonical representation */ public TreeNode<Clause> getEquivalentNodeAlreadyInDAG(TreeNode<Clause> newNode) { /** * Option 1 */ // Node<Clause> nodeInTree = m_canonicalsToDAGNodes.get(newNode.getNodeLabel().m_canonicalRepresentation); // if( nodeInTree !=null ) // return nodeInTree; /** * Option 2 */ TreeNode<Clause> nodeInTree = m_canonicalsToDAGNodes.get(newNode.getNodeLabel().m_canonicalRepresentation); if( nodeInTree !=null ) return nodeInTree; for (TreeNode<Clause> nodeInRewritingTree : m_nodesAddedToTree) if (nodeInRewritingTree.getNodeLabel().isEquivalentUpToVariableRenaming(newNode.getNodeLabel())) return nodeInRewritingTree; /** * Option 3 */ // for (Node<Clause> nodeInRewritingTree : m_nodesAddedToTree) // if (nodeInRewritingTree.getNodeLabel().isEquivalentUpToVariableRenaming(newNode.getNodeLabel())) // return nodeInRewritingTree; return null; } /** * Η συνάρτηση αυτή<SUF>*/ public Clause getSubsumees(PI pi , Clause clause ){ Term newAtom = null; Term g = clause.getBody()[0]; int gArity = g.getArity(); String name = g.getName(); if(gArity == 1){ Variable var1 = (Variable)g.getArguments()[0]; if(pi.m_right.equals( name )) switch(pi.m_type){ case 1: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var1.m_index)); break; case 4: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(50000)}); break; case 7: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(50000), this.m_termFactory.getVariable(var1.m_index)}); break; default: return null; } else return null; } else{ Variable var1 = (Variable)g.getArguments()[0]; Variable var2 = (Variable)g.getArguments()[1]; if(pi.m_right.equals( name )) // if(!clause.isBound(var2)){ switch(pi.m_type){ case 2: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var1.m_index)); break; case 3: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, this.m_termFactory.getVariable(var2.m_index)); break; case 5: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(50000)}); break; case 6: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(50000)}); break; case 8: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(50000), this.m_termFactory.getVariable(var1.m_index)}); break; case 9: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(50000), this.m_termFactory.getVariable(var2.m_index)}); break; case 10: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var1.m_index), this.m_termFactory.getVariable(var2.m_index)}); break; case 11: newAtom = this.m_termFactory.getFunctionalTerm(pi.m_left, new Term[]{this.m_termFactory.getVariable(var2.m_index), this.m_termFactory.getVariable(var1.m_index)}); break; default: return null; // } } else return null; } Term [] body = new Term[1]; body[0] = newAtom; return new Clause ( body, clause.getHead() ); } public Tree<Clause> saturate(ArrayList<PI> pis, Clause query) { m_unprocessedNodes = new ArrayList<TreeNode<Clause>>(); TreeNode<Clause> givenNode; TreeNode<Clause> rootElement = new TreeNode<Clause>( query ); Tree<Clause> rewritingDAG = new Tree<Clause>(rootElement) ; m_unprocessedNodes.add(rootElement); while (!m_unprocessedNodes.isEmpty()) { givenNode = m_unprocessedNodes.remove( 0 ); Clause givenClause = givenNode.getNodeLabel(); // System.out.println( "m_nodesAddedToTree contains " + givenNode.getNodeLabel() + " is " + m_nodesAddedToTree.contains( givenNode ) ); m_nodesAddedToTree.add(givenNode); for (int i = 0; i < givenClause.getBody().length; i++) for (PI pi: pis) { Clause newQuery = getNewQuery(pi, i, givenClause); if (newQuery!=null) { TreeNode<Clause> newNode = new TreeNode<Clause>( newQuery ); TreeNode<Clause> nodeInRewritingDAG = getEquivalentNodeAlreadyInDAG(newNode); if (nodeInRewritingDAG==null) { for ( Substitution s : givenNode.getNodeLabel().getUnifications() ) newNode.getNodeLabel().addUnification( s ); givenNode.addChild(newNode); m_unprocessedNodes.add(newNode); m_nodesAddedToTree.add(newNode); m_canonicalsToDAGNodes.put(newQuery.m_canonicalRepresentation, newNode); } //if commented on june 8th else //if (!nodeInRewritingDAG.getSubTree().contains(givenNode)) givenNode.addChild( nodeInRewritingDAG ); } } for (int i = 0; i < givenClause.getBody().length - 1; i++) for (int j = i+1; j < givenClause.getBody().length; j++) { Substitution unifier = Substitution.mostGeneralUnifier(givenClause.getBody()[i], givenClause.getBody()[j], this.m_termFactory); // System.out.println( "GivenClause = " + givenClause + "\t\tUnifier = " + unifier + "\t\t" + givenClause.getBody()[i] + "\t\t" + givenClause.getBody()[j]); if (unifier!=null) { Clause newQuery = getNewQuery(unifier, givenClause); TreeNode<Clause> newNode = new TreeNode<Clause>( newQuery ); TreeNode<Clause> nodeInRewritingDAG = getEquivalentNodeAlreadyInDAG(newNode); if(nodeInRewritingDAG==null) { for ( Substitution s : givenNode.getNodeLabel().getUnifications() ) newNode.getNodeLabel().addUnification( s ); for ( Entry<Variable,Term> s : unifier.entrySet() ) { // if ( ! ( Integer.parseInt( s.getKey().toString().substring( 1 , s.getKey().toString().length() ) ) >= 500 || Integer.parseInt( s.getValue().toString().substring( 1 , s.getValue().toString().length() ) ) >= 500 ) ) { Substitution ns = new Substitution(); ns.put( s.getKey(), s.getValue() ); newNode.getNodeLabel().addUnification( ns ); } givenNode.addChild( newNode ); m_unprocessedNodes.add( newNode ); m_nodesAddedToTree.add( newNode ); m_canonicalsToDAGNodes.put(newQuery.m_canonicalRepresentation, newNode); } //if commented on june 8th else //if (!nodeInRewritingDAG.getSubTree().contains(givenNode)) givenNode.addChild( nodeInRewritingDAG ); } } } return rewritingDAG; } }
28838_19
package com.example.smartalert; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; public class Incident { private String userEmail; private String type; private String comment; private String timestamp; private String image; private String location; private String status; // for sorted incidents // 1. keep incident type // 2. comments list // 3. locations lit // 4. keep timestamp // 5. photos list // 6. (new) submission number private List<String> locations = new ArrayList<>(); private List<String> comments = new ArrayList<>(); private List<String> timestamps = new ArrayList<>(); private List<String> photos = new ArrayList<>(); private List<String> keys = new ArrayList<>(); private List<String> usersEmails = new ArrayList<>(); private int subNumber; public Incident() {} public Incident(List<String> keys, List<String> comments, List<String> locations, List<String> timestamps, List<String> photos, int subNumber, String status){ this.keys = keys; this.comments = comments; this.locations = locations; this.timestamps = timestamps; this.photos = photos; this.subNumber = subNumber; this.status = status; } public Incident(String userEmail, String type, String comment, String timestamp,String image,String location) { this.userEmail = userEmail; this.type = type; this.comment = comment; this.timestamp = timestamp; this.image=image; this.location=location; } public Incident(List<String> usersEmails, /*String type,*/ String timestamp){ this.usersEmails = usersEmails; //this.type = type; this.timestamp = timestamp; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getUserEmail() {return userEmail;} public void setUserEmail(String userEmail) { this.userEmail = userEmail; } public List<String> getLocations() { return locations; } public void setLocations(List<String> locations) { this.locations = locations; } public List<String> getComments() { return comments; } public void setComments(List<String> comments) { this.comments = comments; } public List<String> getTimestamps() { return timestamps; } public void setTimestamps(List<String> timestamps) { this.timestamps = timestamps; } public List<String> getPhotos() { return photos; } public void setPhotos(List<String> photos) { this.photos = photos; } public int getSubNumber() { return subNumber; } public void setSubNumber(int subNumber) { this.subNumber = subNumber; } public List<String> getKeys() {return keys;} public void setKeys(List<String> keys) {this.keys = keys;} public String getStatus() {return status;} public void setStatus(String status) {this.status = status;} public List<String> getUsersEmails() {return usersEmails;} public void setUsersEmails(List<String> usersEmails) {this.usersEmails = usersEmails;} static boolean isWithinTimeframe(String prevTimestamp, String timestamp, int hours, int minutes) { try { // Define the timestamp format SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss", Locale.getDefault()); // Parse the timestamps into Date objects Date incidentDate1 = dateFormat.parse(prevTimestamp); Date incidentDate2 = dateFormat.parse(timestamp); // Check if the incidents are on different dates if (!isSameDate(incidentDate1, incidentDate2)) { return false; } // Calculate the difference in minutes long diffInMinutes = Math.abs(incidentDate1.getTime() - incidentDate2.getTime()) / (60 * 1000); // Check if the difference is less than the specified number of hours and minutes return diffInMinutes < (hours * 60 + minutes); } catch (ParseException e) { e.printStackTrace(); return false; // Return false in case of an error } } // Helper method to check if two Dates are on the same date private static boolean isSameDate(Date date1, Date date2) { Calendar cal1 = Calendar.getInstance(); cal1.setTime(date1); Calendar cal2 = Calendar.getInstance(); cal2.setTime(date2); return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) && cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH); } static boolean isWithinDistance(String prevLocation, String location, double distanceKm, double distanceMeters) { double distance = calculateDistance(prevLocation, location); return distance <= distanceKm || (distance <= (distanceMeters / 1000.0)); } private static double calculateDistance(String location1, String location2) { // Εξαγωγή των γεωγραφικών συντεταγμένων από τα strings double lat1 = extractCoordinate(location1, "Lat"); //System.out.println("lat1: " + lat1); double lon1 = extractCoordinate(location1, "Long"); //System.out.println("lon1: " + lon1); double lat2 = extractCoordinate(location2, "Lat"); double lon2 = extractCoordinate(location2, "Long"); // Υπολογισμός της απόστασης με τον τύπο Haversine return haversine(lat1, lon1, lat2, lon2); } // Εξαγωγή των γεωγραφικών συντεταγμένων από τα strings private static double extractCoordinate(String location, String coordinateType) { //String[] parts = location.split(": ")[1].split(", Long: "); //[1].split(","); /*double[] parts1 = Arrays.stream(location.replaceAll("[^\\d.,-]", "").split(", ")) .mapToDouble(Double::parseDouble) .toArray();*/ String[] parts = location.replaceAll("[^\\d.-]+", " ").trim().split("\\s+"); double lat = 0, lon = 0; // Ensure we have at least two parts if (parts.length >= 2) { lat = Double.parseDouble(parts[0]); lon = Double.parseDouble(parts[1]); } //System.out.println("parts: " + Arrays.toString(parts)); //System.out.println("paers[0]: " + parts[1].split(",")[0]); return coordinateType.equals("Lat") ? lat : lon; } // Υπολογισμός της απόστασης με τον τύπο Haversine private static double haversine(double lat1, double lon1, double lat2, double lon2) { final int R = 6371; // Ακτίνα της Γης σε χιλιόμετρα double dLat = Math.toRadians(lat2 - lat1); double dLon = Math.toRadians(lon2 - lon1); double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return R * c; // Επιστροφή της απόστασης σε χιλιόμετρα } }
HelenPolychroni/SmartAlert
app/src/main/java/com/example/smartalert/Incident.java
2,106
// Εξαγωγή των γεωγραφικών συντεταγμένων από τα strings
line_comment
el
package com.example.smartalert; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; public class Incident { private String userEmail; private String type; private String comment; private String timestamp; private String image; private String location; private String status; // for sorted incidents // 1. keep incident type // 2. comments list // 3. locations lit // 4. keep timestamp // 5. photos list // 6. (new) submission number private List<String> locations = new ArrayList<>(); private List<String> comments = new ArrayList<>(); private List<String> timestamps = new ArrayList<>(); private List<String> photos = new ArrayList<>(); private List<String> keys = new ArrayList<>(); private List<String> usersEmails = new ArrayList<>(); private int subNumber; public Incident() {} public Incident(List<String> keys, List<String> comments, List<String> locations, List<String> timestamps, List<String> photos, int subNumber, String status){ this.keys = keys; this.comments = comments; this.locations = locations; this.timestamps = timestamps; this.photos = photos; this.subNumber = subNumber; this.status = status; } public Incident(String userEmail, String type, String comment, String timestamp,String image,String location) { this.userEmail = userEmail; this.type = type; this.comment = comment; this.timestamp = timestamp; this.image=image; this.location=location; } public Incident(List<String> usersEmails, /*String type,*/ String timestamp){ this.usersEmails = usersEmails; //this.type = type; this.timestamp = timestamp; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getUserEmail() {return userEmail;} public void setUserEmail(String userEmail) { this.userEmail = userEmail; } public List<String> getLocations() { return locations; } public void setLocations(List<String> locations) { this.locations = locations; } public List<String> getComments() { return comments; } public void setComments(List<String> comments) { this.comments = comments; } public List<String> getTimestamps() { return timestamps; } public void setTimestamps(List<String> timestamps) { this.timestamps = timestamps; } public List<String> getPhotos() { return photos; } public void setPhotos(List<String> photos) { this.photos = photos; } public int getSubNumber() { return subNumber; } public void setSubNumber(int subNumber) { this.subNumber = subNumber; } public List<String> getKeys() {return keys;} public void setKeys(List<String> keys) {this.keys = keys;} public String getStatus() {return status;} public void setStatus(String status) {this.status = status;} public List<String> getUsersEmails() {return usersEmails;} public void setUsersEmails(List<String> usersEmails) {this.usersEmails = usersEmails;} static boolean isWithinTimeframe(String prevTimestamp, String timestamp, int hours, int minutes) { try { // Define the timestamp format SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss", Locale.getDefault()); // Parse the timestamps into Date objects Date incidentDate1 = dateFormat.parse(prevTimestamp); Date incidentDate2 = dateFormat.parse(timestamp); // Check if the incidents are on different dates if (!isSameDate(incidentDate1, incidentDate2)) { return false; } // Calculate the difference in minutes long diffInMinutes = Math.abs(incidentDate1.getTime() - incidentDate2.getTime()) / (60 * 1000); // Check if the difference is less than the specified number of hours and minutes return diffInMinutes < (hours * 60 + minutes); } catch (ParseException e) { e.printStackTrace(); return false; // Return false in case of an error } } // Helper method to check if two Dates are on the same date private static boolean isSameDate(Date date1, Date date2) { Calendar cal1 = Calendar.getInstance(); cal1.setTime(date1); Calendar cal2 = Calendar.getInstance(); cal2.setTime(date2); return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) && cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH); } static boolean isWithinDistance(String prevLocation, String location, double distanceKm, double distanceMeters) { double distance = calculateDistance(prevLocation, location); return distance <= distanceKm || (distance <= (distanceMeters / 1000.0)); } private static double calculateDistance(String location1, String location2) { // Εξαγωγή των γεωγραφικών συντεταγμένων από τα strings double lat1 = extractCoordinate(location1, "Lat"); //System.out.println("lat1: " + lat1); double lon1 = extractCoordinate(location1, "Long"); //System.out.println("lon1: " + lon1); double lat2 = extractCoordinate(location2, "Lat"); double lon2 = extractCoordinate(location2, "Long"); // Υπολογισμός της απόστασης με τον τύπο Haversine return haversine(lat1, lon1, lat2, lon2); } // Εξαγωγή των<SUF> private static double extractCoordinate(String location, String coordinateType) { //String[] parts = location.split(": ")[1].split(", Long: "); //[1].split(","); /*double[] parts1 = Arrays.stream(location.replaceAll("[^\\d.,-]", "").split(", ")) .mapToDouble(Double::parseDouble) .toArray();*/ String[] parts = location.replaceAll("[^\\d.-]+", " ").trim().split("\\s+"); double lat = 0, lon = 0; // Ensure we have at least two parts if (parts.length >= 2) { lat = Double.parseDouble(parts[0]); lon = Double.parseDouble(parts[1]); } //System.out.println("parts: " + Arrays.toString(parts)); //System.out.println("paers[0]: " + parts[1].split(",")[0]); return coordinateType.equals("Lat") ? lat : lon; } // Υπολογισμός της απόστασης με τον τύπο Haversine private static double haversine(double lat1, double lon1, double lat2, double lon2) { final int R = 6371; // Ακτίνα της Γης σε χιλιόμετρα double dLat = Math.toRadians(lat2 - lat1); double dLon = Math.toRadians(lon2 - lon1); double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return R * c; // Επιστροφή της απόστασης σε χιλιόμετρα } }
44559_1
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template */ package Asteras; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Ηλίας */ @WebServlet(name = "CosSim", urlPatterns = {"/CosSim"}) public class CosSim extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ String query = request.getParameter("query"); query = query.toLowerCase(); String k = request.getParameter("k"); if ( k.equals("")){ k = "5"; } LuceneTester tester = new LuceneTester(); String[] parts = query.split(" "); String result = ""; ArrayList<Author> scores = null; if (parts.length > 1) { result += tester.getCosineSimilarity(parts[0], parts[1]); } else if (parts.length == 1) { scores = tester.getCosineSimilarity(parts[0]); } out.println("<!DOCTYPE html>\n" + "<!--\n" + "Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license\n" + "Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Html.html to edit this template\n" + "-->\n" + "<html>\n" + " <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\">\n" + " <head>\n" + " <title>CosSim</title>\n" + " <meta charset=\"UTF-8\">\n" + " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" + " </head>\n" + "\n" + "\n" + " <body>\n" + " <div class=\"container\">\n" + " <div class=\"ibox-content\">\n" + " <br>\n" + " <a href=\"http://localhost:8080/Asteras/\" class=\"btn btn-primary\">Home</a><br><br>\n" + " <label for=\"k_results\">Top k results: </label>\n" + " <input type=\"text\" id=\"k_results\" name=\"k_results\" required><br>\n" + " <input name =\"submit_btn\" id = \"submit_btn\" type=\"submit\" value=\"Submit\">\n" + " <br>\n" + " </div>\n" + " \n" + " </div>\n" + " \n" + " <table class=\"table\">\n" + " <thead>\n" + " <tr>\n" + " <th scope=\"col\">#</th>\n" + " <th scope=\"col\">Author 1</th>\n" + " <th scope=\"col\">Author 2</th>\n" + " <th scope=\"col\">Score(cos sim)</th>\n" + " </tr>\n" + " </thead>\n" + " <tbody>"); if (scores == null) { out.println("<tr>\n" + " <th scope=\"row\">1</th>\n" + " <td>" + parts[0] + "</td>\n" + " <td>" + parts[1] + "</td>\n" + " <td>" + result + "</td>\n" + " </tr>"); } else { int i = 1; for (Author score : scores) { out.println("<tr>\n" + " <th scope=\"row\">" + i + "</th>\n" + " <td>" + parts[0] + "</td>\n" + " <td>" + score.getName() + "</td>\n" + " <td>" + score.getScore() + "</td>\n" + " </tr>"); i++; if (i > Integer.parseInt(k)) { break; } } } out.println("</tbody>\n" + " </table>\n" + " </body>\n" + "</html>"); out.println("<script>\n" + " function refreshK() {\n" + " window.location.href = 'http://localhost:8080/Asteras/CosSim?query=" + query + "'" + " +' &k=' + document.getElementById(\"k_results\").value;\n" + " }\n" + "\n" + " document.getElementById(\"submit_btn\").addEventListener(\"click\", refreshK);\n" + "\n" + "</script> "); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
IliasAlex/Asteras
src/java/Asteras/CosSim.java
1,709
/** * * @author Ηλίας */
block_comment
el
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template */ package Asteras; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Ηλίας <SUF>*/ @WebServlet(name = "CosSim", urlPatterns = {"/CosSim"}) public class CosSim extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ String query = request.getParameter("query"); query = query.toLowerCase(); String k = request.getParameter("k"); if ( k.equals("")){ k = "5"; } LuceneTester tester = new LuceneTester(); String[] parts = query.split(" "); String result = ""; ArrayList<Author> scores = null; if (parts.length > 1) { result += tester.getCosineSimilarity(parts[0], parts[1]); } else if (parts.length == 1) { scores = tester.getCosineSimilarity(parts[0]); } out.println("<!DOCTYPE html>\n" + "<!--\n" + "Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license\n" + "Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Html.html to edit this template\n" + "-->\n" + "<html>\n" + " <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\">\n" + " <head>\n" + " <title>CosSim</title>\n" + " <meta charset=\"UTF-8\">\n" + " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" + " </head>\n" + "\n" + "\n" + " <body>\n" + " <div class=\"container\">\n" + " <div class=\"ibox-content\">\n" + " <br>\n" + " <a href=\"http://localhost:8080/Asteras/\" class=\"btn btn-primary\">Home</a><br><br>\n" + " <label for=\"k_results\">Top k results: </label>\n" + " <input type=\"text\" id=\"k_results\" name=\"k_results\" required><br>\n" + " <input name =\"submit_btn\" id = \"submit_btn\" type=\"submit\" value=\"Submit\">\n" + " <br>\n" + " </div>\n" + " \n" + " </div>\n" + " \n" + " <table class=\"table\">\n" + " <thead>\n" + " <tr>\n" + " <th scope=\"col\">#</th>\n" + " <th scope=\"col\">Author 1</th>\n" + " <th scope=\"col\">Author 2</th>\n" + " <th scope=\"col\">Score(cos sim)</th>\n" + " </tr>\n" + " </thead>\n" + " <tbody>"); if (scores == null) { out.println("<tr>\n" + " <th scope=\"row\">1</th>\n" + " <td>" + parts[0] + "</td>\n" + " <td>" + parts[1] + "</td>\n" + " <td>" + result + "</td>\n" + " </tr>"); } else { int i = 1; for (Author score : scores) { out.println("<tr>\n" + " <th scope=\"row\">" + i + "</th>\n" + " <td>" + parts[0] + "</td>\n" + " <td>" + score.getName() + "</td>\n" + " <td>" + score.getScore() + "</td>\n" + " </tr>"); i++; if (i > Integer.parseInt(k)) { break; } } } out.println("</tbody>\n" + " </table>\n" + " </body>\n" + "</html>"); out.println("<script>\n" + " function refreshK() {\n" + " window.location.href = 'http://localhost:8080/Asteras/CosSim?query=" + query + "'" + " +' &k=' + document.getElementById(\"k_results\").value;\n" + " }\n" + "\n" + " document.getElementById(\"submit_btn\").addEventListener(\"click\", refreshK);\n" + "\n" + "</script> "); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
9202_0
/* ΠΡΟΗΓΜΕΝΑ ΘΕΜΑΤΑ ΑΝΤΙΚΕΙΜΕΝΟΣΤΕΦΟΥΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΥ ΠΜΣ «Προηγμένα Συστήματα Πληροφορικής - Ανάπτυξη Λογισμικού και Τεχνητής Νοημοσύνης» ΠΑΝΕΠΙΣΤΗΜΙΟ ΠΕΙΡΑΙΩΣ Τίτλος Εργασίας: «Precedence Graph Threading using Blockchains» Φοιτητές: Παπανικολάου Ηλίας ΜΠΣΠ20039 Δαβλιάνη Ιωάννα ΜΠΣΠ20010 14/3/2021 */ package com.unipi.precedence_graph; import java.io.IOException; import java.sql.Connection; import java.time.Instant; import java.util.ArrayList; import java.util.List; /** * * Main thread calls functions to read p_precedence.txt, p_timings.txt * and create process instances which are saved in List<Process> processes. * * When processes are defined, globalTimerStart is set and thread execution * starts. The main thread goes into a waiting state until all processes * are completed. * * After completion the main thread checks if there are already stored blocks * in the repository. * - If there are already saved blocks in the repository a new emulation name is * created and the blockChain continues from the last block that already exists in DB * - If there is not blockChain in DB a new one is created with GenesisBlock * * After blockchain creation blocks are stored in database. * * Lastly, the consistency of the entire BlockChain is checked by calling * repository.verifyBlockChain() ,method. * */ public class PrecedenceGraph { public static Instant globalTimerStart; public static volatile List<Process> blockOrder = new ArrayList<>(); public static List<Block> blockChainList = new ArrayList<>(); public static void main(String[] args){ List<Process> processes = new ArrayList<>(new Parser().readPrecedenceFiles()); System.out.println("================== Precedence ===================="); int countGenesis = 0; int countSecondary = 0; for (Process p : processes){ if (p.isGenesisProcess()) countGenesis++; else countSecondary++; } System.out.println("Number of genesis processes: " +countGenesis); System.out.println("Number of secondary processes: " +countSecondary); for (Process p: processes){ if (p.getWaitTime() != 0) System.out.println(p.getProcessName() +" has to work for " +p.getWaitTime() +"ms"); if (!p.getDependencies().isEmpty()){ System.out.print(p.getProcessName() +" has to wait for "); for (Process proc : p.getDependencies()){ System.out.print(proc.getProcessName() +" "); } System.out.println(); } } System.out.println("=============== Starting Threads ================="); globalTimerStart = Instant.now(); for (Process p: processes){ p.start(); } //Wait for processes to finish before continue processes.forEach(process -> { try { process.join(); } catch (InterruptedException e) { e.printStackTrace(); } }); System.out.println("============= Creating BlockChain ================"); BlockChain blockChain = new BlockChain(); //DB Connection Repository repository = new Repository(); // repository.createNewDatabase(); // repository.createNewTable(); Connection conn = repository.connect(); //If exists, retrieve the last Block from DB Block lastBlock = repository.retrieveLastBlock(conn); if (lastBlock != null) { blockChain.setIsGenesisBlock(false); //retrieve previous Emulation Name int count = Integer.parseInt(lastBlock.getEmulationName().substring(10)); //Create new Emulation Name - Auto Increment String emulationName = String.format("emulation_%d", ++count); //Continue the BlockChain from the last Block that already exists in DB blockChain.createBlock(blockOrder.get(0), emulationName, lastBlock.getPreviousHash()); for (int i=1; i < blockOrder.size(); i++){ blockChain.createBlock(blockOrder.get(i), emulationName); } } //Else if there is not BlockChain in DB, create a new one with GenesisBlock else { for (Process p: blockOrder){ blockChain.createBlock(p, "emulation_1"); } } //print BlockChain blockChainList.forEach(System.out::println); //Save Block Chain to DB System.out.println("============= Saving to DataBase ================"); for (Block b : blockChainList){ repository.insert(conn, b.getEmulationName(), b.getHash(), b.getPreviousHash(), b.getProcessName(), b.getExecutionTime(), b.getDependencies(), b.getTimeStamp(), b.getNonce()); } System.out.println("BlockChain saved Successfully"); System.out.println("============= Validate BlockChain ================"); Boolean isValid = repository.verifyBlockChain(conn, blockChain.getPrefix()); System.out.println("BlockChain Valid: " +isValid); repository.close(conn); System.out.println("\nPress any key to exit..."); try { System.in.read(); } catch (IOException e) { e.printStackTrace(); } } }
IliasPapanikolaou/PrecedenceGraph
src/main/java/com/unipi/precedence_graph/PrecedenceGraph.java
1,475
/* ΠΡΟΗΓΜΕΝΑ ΘΕΜΑΤΑ ΑΝΤΙΚΕΙΜΕΝΟΣΤΕΦΟΥΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΥ ΠΜΣ «Προηγμένα Συστήματα Πληροφορικής - Ανάπτυξη Λογισμικού και Τεχνητής Νοημοσύνης» ΠΑΝΕΠΙΣΤΗΜΙΟ ΠΕΙΡΑΙΩΣ Τίτλος Εργασίας: «Precedence Graph Threading using Blockchains» Φοιτητές: Παπανικολάου Ηλίας ΜΠΣΠ20039 Δαβλιάνη Ιωάννα ΜΠΣΠ20010 14/3/2021 */
block_comment
el
/* ΠΡΟΗΓΜΕΝΑ ΘΕΜΑΤΑ ΑΝΤΙΚΕΙΜΕΝΟΣΤΕΦΟΥΣ<SUF>*/ package com.unipi.precedence_graph; import java.io.IOException; import java.sql.Connection; import java.time.Instant; import java.util.ArrayList; import java.util.List; /** * * Main thread calls functions to read p_precedence.txt, p_timings.txt * and create process instances which are saved in List<Process> processes. * * When processes are defined, globalTimerStart is set and thread execution * starts. The main thread goes into a waiting state until all processes * are completed. * * After completion the main thread checks if there are already stored blocks * in the repository. * - If there are already saved blocks in the repository a new emulation name is * created and the blockChain continues from the last block that already exists in DB * - If there is not blockChain in DB a new one is created with GenesisBlock * * After blockchain creation blocks are stored in database. * * Lastly, the consistency of the entire BlockChain is checked by calling * repository.verifyBlockChain() ,method. * */ public class PrecedenceGraph { public static Instant globalTimerStart; public static volatile List<Process> blockOrder = new ArrayList<>(); public static List<Block> blockChainList = new ArrayList<>(); public static void main(String[] args){ List<Process> processes = new ArrayList<>(new Parser().readPrecedenceFiles()); System.out.println("================== Precedence ===================="); int countGenesis = 0; int countSecondary = 0; for (Process p : processes){ if (p.isGenesisProcess()) countGenesis++; else countSecondary++; } System.out.println("Number of genesis processes: " +countGenesis); System.out.println("Number of secondary processes: " +countSecondary); for (Process p: processes){ if (p.getWaitTime() != 0) System.out.println(p.getProcessName() +" has to work for " +p.getWaitTime() +"ms"); if (!p.getDependencies().isEmpty()){ System.out.print(p.getProcessName() +" has to wait for "); for (Process proc : p.getDependencies()){ System.out.print(proc.getProcessName() +" "); } System.out.println(); } } System.out.println("=============== Starting Threads ================="); globalTimerStart = Instant.now(); for (Process p: processes){ p.start(); } //Wait for processes to finish before continue processes.forEach(process -> { try { process.join(); } catch (InterruptedException e) { e.printStackTrace(); } }); System.out.println("============= Creating BlockChain ================"); BlockChain blockChain = new BlockChain(); //DB Connection Repository repository = new Repository(); // repository.createNewDatabase(); // repository.createNewTable(); Connection conn = repository.connect(); //If exists, retrieve the last Block from DB Block lastBlock = repository.retrieveLastBlock(conn); if (lastBlock != null) { blockChain.setIsGenesisBlock(false); //retrieve previous Emulation Name int count = Integer.parseInt(lastBlock.getEmulationName().substring(10)); //Create new Emulation Name - Auto Increment String emulationName = String.format("emulation_%d", ++count); //Continue the BlockChain from the last Block that already exists in DB blockChain.createBlock(blockOrder.get(0), emulationName, lastBlock.getPreviousHash()); for (int i=1; i < blockOrder.size(); i++){ blockChain.createBlock(blockOrder.get(i), emulationName); } } //Else if there is not BlockChain in DB, create a new one with GenesisBlock else { for (Process p: blockOrder){ blockChain.createBlock(p, "emulation_1"); } } //print BlockChain blockChainList.forEach(System.out::println); //Save Block Chain to DB System.out.println("============= Saving to DataBase ================"); for (Block b : blockChainList){ repository.insert(conn, b.getEmulationName(), b.getHash(), b.getPreviousHash(), b.getProcessName(), b.getExecutionTime(), b.getDependencies(), b.getTimeStamp(), b.getNonce()); } System.out.println("BlockChain saved Successfully"); System.out.println("============= Validate BlockChain ================"); Boolean isValid = repository.verifyBlockChain(conn, blockChain.getPrefix()); System.out.println("BlockChain Valid: " +isValid); repository.close(conn); System.out.println("\nPress any key to exit..."); try { System.in.read(); } catch (IOException e) { e.printStackTrace(); } } }
10412_0
package com.ipap; public abstract class Shape { protected double centerX; // X στο καρτεσιανό επίπεδο protected double centerY; // Y στο καρτεσιανό επίπεδο // Constructor public Shape(double centerX, double centerY) { this.centerX = centerX; this.centerY = centerY; } // Getters public double getCenterX() { return this.centerX; } public double getCenterY() { return this.centerY; } // Setters public void setCenterX(double centerX) { this.centerX = centerX; } public void setCenterY(double centerY) { this.centerY = centerY; } public void printInfo() { System.out.println("Center = (" + this.centerX + "," + this.centerY + ")"); } public abstract double calcArea(); }
IliasPapanikolaou/java-oop-inheritance
src/main/java/com/ipap/Shape.java
236
// X στο καρτεσιανό επίπεδο
line_comment
el
package com.ipap; public abstract class Shape { protected double centerX; // X στο<SUF> protected double centerY; // Y στο καρτεσιανό επίπεδο // Constructor public Shape(double centerX, double centerY) { this.centerX = centerX; this.centerY = centerY; } // Getters public double getCenterX() { return this.centerX; } public double getCenterY() { return this.centerY; } // Setters public void setCenterX(double centerX) { this.centerX = centerX; } public void setCenterY(double centerY) { this.centerY = centerY; } public void printInfo() { System.out.println("Center = (" + this.centerX + "," + this.centerY + ")"); } public abstract double calcArea(); }
20877_3
package org.example; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Scanner; public class DummyApplication { private static ObjectOutputStream out; private static ObjectInputStream in; private static Socket requestSocket; public static void main(String[] args) { try { // Connect to the Master server requestSocket = new Socket("localhost", 4321); // Use the correct IP and port out = new ObjectOutputStream(requestSocket.getOutputStream()); in = new ObjectInputStream(requestSocket.getInputStream()); Scanner scanner = new Scanner(System.in); int userType; // Επιλογή τύπου χρήστη System.out.println("Select user type:"); System.out.println("1. Manager"); System.out.println("2. Customer"); System.out.print("Enter your choice: "); userType = scanner.nextInt(); // Εμφάνιση μενού ανάλογα με τον τύπο χρήστη switch (userType) { case 1: displayManagerMenu(scanner); break; case 2: displayCustomerMenu(scanner); break; default: System.out.println("Invalid user type."); } } catch (UnknownHostException unknownHost) { System.err.println("You are trying to connect to an unknown host!"); } catch (IOException ioException) { ioException.printStackTrace(); } finally { // Close connections try { in.close(); out.close(); requestSocket.close(); } catch (IOException ioException) { ioException.printStackTrace(); } } } public static void displayManagerMenu(Scanner scanner) throws IOException { int choice; do { // Εμφάνιση μενού για τον διαχειριστή του καταλύματος System.out.println("\nManager Menu:"); System.out.println("1. Add accomodation"); System.out.println("2. Add available dates for rental"); System.out.println("3. Display reservations"); System.out.println("4. Logout"); System.out.print("Enter your choice: "); choice = scanner.nextInt(); // Εκτέλεση επιλογής χρήστη switch (choice) { case 1: System.out.println("Adding accomodation..."); System.out.print("Enter the path of the JSON file for the accommodation: "); String jsonFilePath = scanner.next(); File jsonFile = new File(jsonFilePath); String jsonString = new String(Files.readAllBytes(jsonFile.toPath()), StandardCharsets.UTF_8); out.writeObject("add_accommodation"); out.writeObject(jsonString); out.flush(); break; case 2: System.out.println("Adding available dates for rental..."); break; case 3: System.out.println("Displaying reservations..."); break; case 4: System.out.println("Loging out"); default: System.out.println("Invalid choice. Please try again."); } } while (choice != 4); } public static void displayCustomerMenu(Scanner scanner) { int choice; do { // Εμφάνιση μενού για τον πελάτη System.out.println("\nCustomer Menu:"); System.out.println("1. Filter accomodations"); System.out.println("2. Book accomodation"); System.out.println("3. Rank accomodation"); System.out.println("4. Logout"); System.out.print("Enter your choice: "); choice = scanner.nextInt(); // Εκτέλεση επιλογής διαχειριστή switch (choice) { case 1: System.out.println("Filtering accomodations..."); break; case 2: System.out.println("Booking accomodation..."); break; case 3: System.out.println("Ranking accomodation..."); break; case 4: System.out.println("Loging out"); break; default: System.out.println("Invalid choice. Please try again."); } } while (choice != 4); // make display menu and customer menu methods check gpt4 } }
Ioanna-jpg/GetaRoom-App
backend/src/DummyApplication.java
1,152
// Εμφάνιση μενού ανάλογα με τον τύπο χρήστη
line_comment
el
package org.example; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Scanner; public class DummyApplication { private static ObjectOutputStream out; private static ObjectInputStream in; private static Socket requestSocket; public static void main(String[] args) { try { // Connect to the Master server requestSocket = new Socket("localhost", 4321); // Use the correct IP and port out = new ObjectOutputStream(requestSocket.getOutputStream()); in = new ObjectInputStream(requestSocket.getInputStream()); Scanner scanner = new Scanner(System.in); int userType; // Επιλογή τύπου χρήστη System.out.println("Select user type:"); System.out.println("1. Manager"); System.out.println("2. Customer"); System.out.print("Enter your choice: "); userType = scanner.nextInt(); // Εμφάνιση μενού<SUF> switch (userType) { case 1: displayManagerMenu(scanner); break; case 2: displayCustomerMenu(scanner); break; default: System.out.println("Invalid user type."); } } catch (UnknownHostException unknownHost) { System.err.println("You are trying to connect to an unknown host!"); } catch (IOException ioException) { ioException.printStackTrace(); } finally { // Close connections try { in.close(); out.close(); requestSocket.close(); } catch (IOException ioException) { ioException.printStackTrace(); } } } public static void displayManagerMenu(Scanner scanner) throws IOException { int choice; do { // Εμφάνιση μενού για τον διαχειριστή του καταλύματος System.out.println("\nManager Menu:"); System.out.println("1. Add accomodation"); System.out.println("2. Add available dates for rental"); System.out.println("3. Display reservations"); System.out.println("4. Logout"); System.out.print("Enter your choice: "); choice = scanner.nextInt(); // Εκτέλεση επιλογής χρήστη switch (choice) { case 1: System.out.println("Adding accomodation..."); System.out.print("Enter the path of the JSON file for the accommodation: "); String jsonFilePath = scanner.next(); File jsonFile = new File(jsonFilePath); String jsonString = new String(Files.readAllBytes(jsonFile.toPath()), StandardCharsets.UTF_8); out.writeObject("add_accommodation"); out.writeObject(jsonString); out.flush(); break; case 2: System.out.println("Adding available dates for rental..."); break; case 3: System.out.println("Displaying reservations..."); break; case 4: System.out.println("Loging out"); default: System.out.println("Invalid choice. Please try again."); } } while (choice != 4); } public static void displayCustomerMenu(Scanner scanner) { int choice; do { // Εμφάνιση μενού για τον πελάτη System.out.println("\nCustomer Menu:"); System.out.println("1. Filter accomodations"); System.out.println("2. Book accomodation"); System.out.println("3. Rank accomodation"); System.out.println("4. Logout"); System.out.print("Enter your choice: "); choice = scanner.nextInt(); // Εκτέλεση επιλογής διαχειριστή switch (choice) { case 1: System.out.println("Filtering accomodations..."); break; case 2: System.out.println("Booking accomodation..."); break; case 3: System.out.println("Ranking accomodation..."); break; case 4: System.out.println("Loging out"); break; default: System.out.println("Invalid choice. Please try again."); } } while (choice != 4); // make display menu and customer menu methods check gpt4 } }
4388_20
package payroll; import java.util.ArrayList; import java.io.IOException; import java.io.BufferedWriter; import java.io.FileWriter; /** * * @author Alexandros Dimitrakopoulos */ public class Company { //Λίστα με τoυς τύπους των υπαλλήλων final ArrayList<EmployeeType> types = new ArrayList<>(); //Λίστα υπαλλήλων της εταιρείας private ArrayList<Employee> employees = new ArrayList<>(); //Ανάθεση νέου project σε υπάλληλο public void addProjectToEmployee(String empl, Project project) { //Java functional operations (Πρόταση του JDK αντι για την χρήση for) //Αν ο υπάλληλος υπάρχει στη λίστα υπαλλήλων employees.stream().filter((employeeee) -> (empl.equals(employeeee.getName()))).map((employeeee) -> { employeeee.addProject(project); //Ανάθεσέ του project return employeeee; }).forEachOrdered((employeeee) -> { employeeee.getType().setMoney(employeeee.getType().getMoney() + 80); //Προσθήκη Bonus }); } //Αποθήκευση σε αρχείο TXT των επιμέρους αποδοχών καθώς και τη συνολική της εταιρείας public void save() throws IOException { BufferedWriter output; output = new BufferedWriter(new FileWriter("Payroll.txt")); try { output.write(calcPayroll()); } catch (IOException e) { System.out.println(e); } finally { output.close(); } } //Προσθήκη νέου υπαλλήλου στην εταιρεία public void addEmployee(Employee employee) { employees.add(employee); } //Υπολογισμός μισθοδοσίας της εταιρείας για έναν συγκεκριμένο μήνα public String calcPayroll() { String payroll = ""; int total = 0; //Αρχικοποίηση της μισθοδοσίας for (Employee employee : employees) //Για κάθε υπάλληλο (διαπέραση της λίστας των υπαλλήλων) { //θα χρησιμοποιήσουμε το instanceof για τον ελεγχο της σχέσης υπερκλάσης π.χ (EmployeeType) και υποκλάσης (Salary) //Επίσης, για να υπολογίσουμε τις αποδοχές θα διαβάσουμε πρώτα (μέσω της μεθόδου getType()), //Υπολογισμός μηνιαίων αποδοχών if (employee.getType() instanceof Salary) //Έλεγχος σχέσης υπερκλάσης (EmployeeType) και υποκλάσης (Salary) { //Αν ο υπάλληλος είναι Manager if (employee instanceof Manager) { employee.getType().setMoney(employee.getType().getMoney() + 2000); } //Αν ο υπάλληλος είναι Developer if (employee instanceof Developer) { employee.getType().setMoney(employee.getType().getMoney() + 1200); } //Αν ο υπάλληλος είναι Analyst if (employee instanceof Analyst) { employee.getType().setMoney(employee.getType().getMoney() + 1500); } //Αν ο υπάλληλος είναι Technical if (employee instanceof Technical) { employee.getType().setMoney(employee.getType().getMoney() + 800); } } //Υπολογισμός αποδοχών με την ώρα if (employee.getType() instanceof PerHour) { //Αν ο υπάλληλος είναι Analyst if (employee instanceof Analyst) { employee.getType().setMoney(employee.getType().getMoney() + (15 * employee.getType().getHour())); } //Αν ο υπάλληλος είναι Developer if (employee instanceof Developer) { employee.getType().setMoney(employee.getType().getMoney() + (12 * employee.getType().getHour())); } //Αν ο υπάλληλος είναι Technical if (employee instanceof Technical) { employee.getType().setMoney(employee.getType().getMoney() + (8 * employee.getType().getHour())); } //Αν ο υπάλληλος είναι Manager if (employee instanceof Manager) { employee.getType().setMoney(employee.getType().getMoney() + (20 * employee.getType().getHour())); } } //Επιμέρους μισθοδοσίες των υπαλλήλων για έναν μήνα payroll = payroll + "\nΥπάλληλος: " + employee.getName() + "\nΑποδοχές: " + employee.getType().getMoney() + " Ευρώ\n"; total = total + employee.getType().getMoney(); } //Υπολογισμός συνολικής μισθοδοσίας της εταιρείας για έναν μήνα payroll = payroll + "----------------------------------------" + "\nΣυνολική Μισθοδοσία Εταιρείας: " + total + " Ευρώ\n"; return payroll; } }
JaskJohin/Payroll
src/payroll/Company.java
1,759
//Υπολογισμός αποδοχών με την ώρα
line_comment
el
package payroll; import java.util.ArrayList; import java.io.IOException; import java.io.BufferedWriter; import java.io.FileWriter; /** * * @author Alexandros Dimitrakopoulos */ public class Company { //Λίστα με τoυς τύπους των υπαλλήλων final ArrayList<EmployeeType> types = new ArrayList<>(); //Λίστα υπαλλήλων της εταιρείας private ArrayList<Employee> employees = new ArrayList<>(); //Ανάθεση νέου project σε υπάλληλο public void addProjectToEmployee(String empl, Project project) { //Java functional operations (Πρόταση του JDK αντι για την χρήση for) //Αν ο υπάλληλος υπάρχει στη λίστα υπαλλήλων employees.stream().filter((employeeee) -> (empl.equals(employeeee.getName()))).map((employeeee) -> { employeeee.addProject(project); //Ανάθεσέ του project return employeeee; }).forEachOrdered((employeeee) -> { employeeee.getType().setMoney(employeeee.getType().getMoney() + 80); //Προσθήκη Bonus }); } //Αποθήκευση σε αρχείο TXT των επιμέρους αποδοχών καθώς και τη συνολική της εταιρείας public void save() throws IOException { BufferedWriter output; output = new BufferedWriter(new FileWriter("Payroll.txt")); try { output.write(calcPayroll()); } catch (IOException e) { System.out.println(e); } finally { output.close(); } } //Προσθήκη νέου υπαλλήλου στην εταιρεία public void addEmployee(Employee employee) { employees.add(employee); } //Υπολογισμός μισθοδοσίας της εταιρείας για έναν συγκεκριμένο μήνα public String calcPayroll() { String payroll = ""; int total = 0; //Αρχικοποίηση της μισθοδοσίας for (Employee employee : employees) //Για κάθε υπάλληλο (διαπέραση της λίστας των υπαλλήλων) { //θα χρησιμοποιήσουμε το instanceof για τον ελεγχο της σχέσης υπερκλάσης π.χ (EmployeeType) και υποκλάσης (Salary) //Επίσης, για να υπολογίσουμε τις αποδοχές θα διαβάσουμε πρώτα (μέσω της μεθόδου getType()), //Υπολογισμός μηνιαίων αποδοχών if (employee.getType() instanceof Salary) //Έλεγχος σχέσης υπερκλάσης (EmployeeType) και υποκλάσης (Salary) { //Αν ο υπάλληλος είναι Manager if (employee instanceof Manager) { employee.getType().setMoney(employee.getType().getMoney() + 2000); } //Αν ο υπάλληλος είναι Developer if (employee instanceof Developer) { employee.getType().setMoney(employee.getType().getMoney() + 1200); } //Αν ο υπάλληλος είναι Analyst if (employee instanceof Analyst) { employee.getType().setMoney(employee.getType().getMoney() + 1500); } //Αν ο υπάλληλος είναι Technical if (employee instanceof Technical) { employee.getType().setMoney(employee.getType().getMoney() + 800); } } //Υπολογισμός αποδοχών<SUF> if (employee.getType() instanceof PerHour) { //Αν ο υπάλληλος είναι Analyst if (employee instanceof Analyst) { employee.getType().setMoney(employee.getType().getMoney() + (15 * employee.getType().getHour())); } //Αν ο υπάλληλος είναι Developer if (employee instanceof Developer) { employee.getType().setMoney(employee.getType().getMoney() + (12 * employee.getType().getHour())); } //Αν ο υπάλληλος είναι Technical if (employee instanceof Technical) { employee.getType().setMoney(employee.getType().getMoney() + (8 * employee.getType().getHour())); } //Αν ο υπάλληλος είναι Manager if (employee instanceof Manager) { employee.getType().setMoney(employee.getType().getMoney() + (20 * employee.getType().getHour())); } } //Επιμέρους μισθοδοσίες των υπαλλήλων για έναν μήνα payroll = payroll + "\nΥπάλληλος: " + employee.getName() + "\nΑποδοχές: " + employee.getType().getMoney() + " Ευρώ\n"; total = total + employee.getType().getMoney(); } //Υπολογισμός συνολικής μισθοδοσίας της εταιρείας για έναν μήνα payroll = payroll + "----------------------------------------" + "\nΣυνολική Μισθοδοσία Εταιρείας: " + total + " Ευρώ\n"; return payroll; } }
731_4
package basics; import java.io.Serializable; import java.util.ArrayList; /*αναπαράσταση των πληροφοριών που παρέχονται για κάθε επιχείρηση*/ public class Shop implements Serializable{ private String name; //ονομα επιχειρησης private String id; //id επιχειρησης (η αναζητηση με το YelpAPI γινεται με αυτο) private String phone; //τηλεφωνο επιχειρησης private String price; //νομισμα πληρωμης private Double rating; //βαθμολογια private String hours_type; //ειδος ωραριου λειτουργιας private ShopLocation shopLocation; //αντικειμενο που περιεχει τις πληροφοριες τοποθεσιας για την επιχειρηση private ArrayList<OpenHour> workingHours; //ArrayList με τις ωρες λειτουργιας private ArrayList<Review> reviews; //ArrayList με τις κριτικες private ArrayList<String> categories; //ArrayList με τα διαθεσιμα είδη προϊόντων private ArrayList<String> transactions; //ArrayList με τους διαθεσιμους τροπους συναλλαγων public Shop() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public Double getRating() { return rating; } public void setRating(Double rating) { this.rating = rating; } public ShopLocation getShopLocation() { return shopLocation; } public void setShopLocation(ShopLocation shopLocation) { this.shopLocation = shopLocation; } public ArrayList<OpenHour> getWorkingHours() { return workingHours; } public void setWorkingHours(ArrayList<OpenHour> workingHours) { this.workingHours = workingHours; } public ArrayList<Review> getReviews() { return reviews; } public void setReviews(ArrayList<Review> reviews) { this.reviews = reviews; } public ArrayList<String> getCategories() { return categories; } public void setCategories(ArrayList<String> categories) { this.categories = categories; } public ArrayList<String> getTransactions() { return transactions; } public void setTransactions(ArrayList<String> transactions) { this.transactions = transactions; } public String getHours_type() { return hours_type; } public void setHours_type(String hours_type) { this.hours_type = hours_type; } @Override public String toString() { return "Shop{" + "name='" + name + '\'' + ", id='" + id + '\'' + ", phone='" + phone + '\'' + ", price='" + price + '\'' + ", rating='" + rating + '\'' + ", hours_type=" + hours_type + '\'' + ", shopLocation=" + shopLocation.toString() + '}'; } }
JohnChantz/JavaII-YelpAPI-Project
YelpBasics/src/basics/Shop.java
967
//ArrayList με τις ωρες λειτουργιας
line_comment
el
package basics; import java.io.Serializable; import java.util.ArrayList; /*αναπαράσταση των πληροφοριών που παρέχονται για κάθε επιχείρηση*/ public class Shop implements Serializable{ private String name; //ονομα επιχειρησης private String id; //id επιχειρησης (η αναζητηση με το YelpAPI γινεται με αυτο) private String phone; //τηλεφωνο επιχειρησης private String price; //νομισμα πληρωμης private Double rating; //βαθμολογια private String hours_type; //ειδος ωραριου λειτουργιας private ShopLocation shopLocation; //αντικειμενο που περιεχει τις πληροφοριες τοποθεσιας για την επιχειρηση private ArrayList<OpenHour> workingHours; //ArrayList με<SUF> private ArrayList<Review> reviews; //ArrayList με τις κριτικες private ArrayList<String> categories; //ArrayList με τα διαθεσιμα είδη προϊόντων private ArrayList<String> transactions; //ArrayList με τους διαθεσιμους τροπους συναλλαγων public Shop() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public Double getRating() { return rating; } public void setRating(Double rating) { this.rating = rating; } public ShopLocation getShopLocation() { return shopLocation; } public void setShopLocation(ShopLocation shopLocation) { this.shopLocation = shopLocation; } public ArrayList<OpenHour> getWorkingHours() { return workingHours; } public void setWorkingHours(ArrayList<OpenHour> workingHours) { this.workingHours = workingHours; } public ArrayList<Review> getReviews() { return reviews; } public void setReviews(ArrayList<Review> reviews) { this.reviews = reviews; } public ArrayList<String> getCategories() { return categories; } public void setCategories(ArrayList<String> categories) { this.categories = categories; } public ArrayList<String> getTransactions() { return transactions; } public void setTransactions(ArrayList<String> transactions) { this.transactions = transactions; } public String getHours_type() { return hours_type; } public void setHours_type(String hours_type) { this.hours_type = hours_type; } @Override public String toString() { return "Shop{" + "name='" + name + '\'' + ", id='" + id + '\'' + ", phone='" + phone + '\'' + ", price='" + price + '\'' + ", rating='" + rating + '\'' + ", hours_type=" + hours_type + '\'' + ", shopLocation=" + shopLocation.toString() + '}'; } }
3992_6
public class SRTF extends Scheduler { public SRTF() { /* TODO: you _may_ need to add some code here */ } public void addProcess(Process p) { /* TODO: you need to add some code here */ p.getPCB().setState(ProcessState.READY,CPU.clock); // Βαζουμε την διεργασια απο την σε κατασταση NEW σε READY processes.add(p); // Προσθετουμε μια νεα διεργασια στην λιστα διεργασιων προς εκτελεση } public Process getNextProcess() { /* TODO: you need to add some code here * and change the return value */ // If there are no scheduled processes return null. if (processes.size() == 0) { return null; } Process nextProcess = processes.get(0); for (int i = 0 ; i < processes.size(); i++) { if (processes.get(i).getPCB().getState() == ProcessState.RUNNING) { processes.get(i).getPCB().setState(ProcessState.READY, CPU.clock); } if (processes.get(i).getBurstTime() - getRunTime(processes.get(i)) < nextProcess.getBurstTime() - getRunTime(nextProcess)) { nextProcess = processes.get(i); } } return nextProcess; } // Μέθοδος για να βρούμε το run time της διεργασίας μέχρι το τωρινό CPU clock private int getRunTime(Process p) { int runTime = 0; for (int i = 0 ; i < p.getPCB().getStartTimes().size() ; i++) { if (i >= p.getPCB().getStopTimes().size()) { runTime += CPU.clock - p.getPCB().getStartTimes().get(i); } else { runTime += p.getPCB().getStopTimes().get(i) - p.getPCB().getStartTimes().get(i); } } return runTime; } }
JohnOiko/operating-system-scheduler
src/SRTF.java
572
// Μέθοδος για να βρούμε το run time της διεργασίας μέχρι το τωρινό CPU clock
line_comment
el
public class SRTF extends Scheduler { public SRTF() { /* TODO: you _may_ need to add some code here */ } public void addProcess(Process p) { /* TODO: you need to add some code here */ p.getPCB().setState(ProcessState.READY,CPU.clock); // Βαζουμε την διεργασια απο την σε κατασταση NEW σε READY processes.add(p); // Προσθετουμε μια νεα διεργασια στην λιστα διεργασιων προς εκτελεση } public Process getNextProcess() { /* TODO: you need to add some code here * and change the return value */ // If there are no scheduled processes return null. if (processes.size() == 0) { return null; } Process nextProcess = processes.get(0); for (int i = 0 ; i < processes.size(); i++) { if (processes.get(i).getPCB().getState() == ProcessState.RUNNING) { processes.get(i).getPCB().setState(ProcessState.READY, CPU.clock); } if (processes.get(i).getBurstTime() - getRunTime(processes.get(i)) < nextProcess.getBurstTime() - getRunTime(nextProcess)) { nextProcess = processes.get(i); } } return nextProcess; } // Μέθοδος για<SUF> private int getRunTime(Process p) { int runTime = 0; for (int i = 0 ; i < p.getPCB().getStartTimes().size() ; i++) { if (i >= p.getPCB().getStopTimes().size()) { runTime += CPU.clock - p.getPCB().getStartTimes().get(i); } else { runTime += p.getPCB().getStopTimes().get(i) - p.getPCB().getStartTimes().get(i); } } return runTime; } }
3851_7
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package it2021091; import static it2021091.It2021091.personsList; import static it2021091.It2021091.showsList; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; /** * * @author John skoul */ public class Admin extends Account { public Admin(String username, String password) { super(username, password); } //καταχωρηση θεαματος η σειρας public void addShow(){ Scanner input=new Scanner(System.in); /*εισάγω τίτλο θεάματος*/ System.out.print("Title: "); String title = input.nextLine(); //αν είναι ήδη καταχωρημενο if(super.ShowExists(title)){ System.out.println("This Show already exists"); return; } /*εισάγω έτος 1ης προβολής*/ System.out.print("Year: "); int year=input.nextInt(); input.nextLine(); /*εισάγω χώρα παραγωγής*/ System.out.print("Country: "); String country=input.nextLine(); /*εισάγω τύπο θεάματος*/ System.out.print("type or types: "); String types=input.nextLine(); String[] arraytypes = types.split(" "); ArrayList<String> typelist = new ArrayList<>(); for (String str : arraytypes) { typelist.add(str.trim()); } System.out.println("types:" + typelist); /*εισάγω σκηνοθέτη*/ System.out.println("Director details:"); System.out.print("Director fullname:"); String directorName=input.nextLine(); Person director; if( super.personExists(directorName) ){ System.out.println("this Director already exists in the system"); director= super.returnPerson(directorName); System.out.println(director.toString()); } else { //εισαγωγη ημερομηνια γεννησης σκηνοθέτη System.out.print("Director birthdate(enter day/month/year with space between them):"); String directorBirthdate=input.nextLine(); String addslashBirthdate = directorBirthdate.replaceAll("\\s+", "/"); System.out.println("Formatted birthdate: " + addslashBirthdate); //εισαγωγη χωρα καταγωγής σκηνοθέτη System.out.print("Director country:"); String directorCountry=input.nextLine(); //εισαγωγη ιστοσελιδα σκηνοθέτη System.out.print("Director website:"); String directorWebsite=input.nextLine(); director= new Person(directorName,addslashBirthdate,directorCountry,directorWebsite); System.out.print(director.toString()); personsList.add(director); } //εισαγωγη ηθοποιών System.out.print("enter number of actors you want to add:"); int numberOfactors=input.nextInt(); input.nextLine(); ArrayList<Person> actors=new ArrayList<>(); for(int i=0; i<numberOfactors; i++){ Person actor; //εισαγωγη ονόματος System.out.print("enter actor fullName:"); String actorName=input.nextLine(); if( super.personExists(actorName) ){ System.out.println("this Actor already exists in the system"); actor= super.returnPerson(actorName); System.out.println( actor.toString() ); actors.add(actor); }else{ //εισαγωγη ημερομηνιας γεννησης ηθοποιού System.out.print("enter actor birthdate(enter day/month/year with space between them):"); String actorBirthdate=input.nextLine(); String addslashBirthdate = actorBirthdate.replaceAll("\\s+", "/"); System.out.println("Formatted birthdate: " + addslashBirthdate); //εισαγωγη χώρας ηθοποιού System.out.print("enter actor country:"); String actorCountry=input.nextLine(); //εισαγωγη ιστοσελιδας ηθοποιου System.out.print("enter actor website:"); String actorWebsite=input.nextLine(); //δημιουργω τον ηθοποιό actor= new Person(actorName,addslashBirthdate,actorCountry,actorWebsite); System.out.println(actor.toString()); actors.add(actor); personsList.add(actor); } } System.out.println("is the show a series?(y/n)"); char answer=input.nextLine().charAt(0); if( (answer=='Y') || (answer=='y') ){ System.out.println("enter the number of seasons:"); int seasons=input.nextInt(); //εισαγωγή επεισόδια ανα σεασόν int[] episodesPerSeason= new int[seasons]; for(int i=0; i<seasons; i++){ System.out.print("episodes of season " + (i+1) + ":" ); episodesPerSeason[i]=input.nextInt(); } input.nextLine(); //εισαγωγή έτους τελευταίας προβολής System.out.println("enter series last year(leave it blank if the series is still running):"); String lastYear=input.nextLine(); Series series= new Series(seasons,episodesPerSeason,lastYear,title,year,typelist,country,director,actors); System.out.println(series.toString()); showsList.add(series); System.out.println("series added Successfully!!!"); }else { Show show=new Show(title,year,country,director,typelist,actors); System.out.println(show.toString()); showsList.add(show); System.out.println("Show added Successfully!!!"); } } public void updateSeries(){ System.out.print("provide the serie's id or title that you are searching:"); Scanner input= new Scanner(System.in); String search=input.nextLine(); if(!super.ShowExists(search)){ System.out.println("This Show doesnt exist"); }else if(super.returnShow(search) instanceof Series){ Series series = (Series) super.returnShow(search); System.out.println("Series title:" + series.getTitle()); System.out.println(""" Choose what you want to change: 1. number of seasons 2. number of episodes of a season 3. last year 4. add actor to the series """); int choice=input.nextInt(); switch(choice){ case 1: int previousSeasons=series.getSeasons(); int[]previousEpisodesPerSeason=series.getEpisodesPerSeason(); System.out.print("enter new number of seasons:"); int updatedSeasons=input.nextInt(); int[]updatedEpisodesPerSeason=Arrays.copyOf(previousEpisodesPerSeason, updatedSeasons); series.setSeasons(updatedSeasons); series.setEpisodesPerSeason(updatedEpisodesPerSeason); if(updatedSeasons > previousSeasons){ System.out.println("enter the episodes for the new seasons."); for(int i=1; i<=(updatedSeasons - previousSeasons); i++){ System.out.print("enter the episodes for season " + (previousSeasons + i) +":"); int episodes=input.nextInt(); series.setEpisodesForSeason(previousSeasons + i, episodes); } } System.out.println( "New number of seasons is:"+series.getSeasons() ); System.out.println(Arrays.toString(series.getEpisodesPerSeason()) ); for(int i=1; i<=series.getSeasons(); i++){ System.out.println("Season:" + i +" episodes:" + series.getEpisodesForSeason(i) ); } break; case 2: System.out.print("enter a season out of " + series.getSeasons() +":"); int season=input.nextInt(); if( season<=0 || season>series.getSeasons() ){ System.out.println("wrong input"); }else{ System.out.println("enter number of episodes for season " + season +":"); int episodes=input.nextInt(); if(episodes<=0){ System.out.println("wrong input"); }else{ series.setEpisodesForSeason(season, episodes); } for(int i=1; i<=series.getSeasons(); i++){ System.out.println("Season:" + i +" episodes:" + series.getEpisodesForSeason(i) ); } } break; case 3: System.out.print("enter last year:"); input.nextLine(); String lastYear=input.nextLine(); try{ if(lastYear.equalsIgnoreCase("-")){ series.setLastYear("-"); }else if(Integer.parseInt(lastYear)<=0){ System.out.println("wrong input"); }else{ series.setLastYear(lastYear); } }catch(NumberFormatException e){ System.out.println("wrong input"); } break; case 4: System.out.print("enter actor fullname:"); input.nextLine(); String actorName=input.nextLine(); for( Person p:series.getActors() ){ if(p.getFullName().equalsIgnoreCase(actorName)){ System.out.println("this Actor is already added to this series!"); return; } } Person actor; if( super.personExists(actorName) ){ System.out.println("this Actor already exists in the system"); actor= super.returnPerson(actorName); System.out.println( actor.toString() ); series.addActor(actor); System.out.println(actor.getFullName() + " was added to the actors of this series!"); System.out.println(series.getActors()); }else{ //εισαγωγη ημερομηνιας γεννησης ηθοποιού System.out.print("enter actor birthdate(enter day/month/year with space between them):"); String actorBirthdate=input.nextLine(); String addslashBirthdate = actorBirthdate.replaceAll("\\s+", "/"); System.out.println("Formatted birthdate: " + addslashBirthdate); //εισαγωγη χώρας ηθοποιού System.out.print("enter actor country:"); String actorCountry=input.nextLine(); //εισαγωγη ιστοσελιδας ηθοποιου System.out.print("enter actor website:"); String actorWebsite=input.nextLine(); //δημιουργω τον ηθοποιό actor= new Person(actorName,addslashBirthdate,actorCountry,actorWebsite); System.out.println( actor.toString() ); series.addActor(actor); System.out.println(actor.getFullName() + " was added to the actors of this series and to the system!"); System.out.println(series.getActors()); personsList.add(actor); } break; default: System.out.println("This option was not found."); break; } }else{ System.out.println("This is a show not a series"); } } }
JohnSkouloudis/JavaMovieManagement
src/it2021091/Admin.java
3,044
//εισαγωγη ιστοσελιδα σκηνοθέτη
line_comment
el
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package it2021091; import static it2021091.It2021091.personsList; import static it2021091.It2021091.showsList; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; /** * * @author John skoul */ public class Admin extends Account { public Admin(String username, String password) { super(username, password); } //καταχωρηση θεαματος η σειρας public void addShow(){ Scanner input=new Scanner(System.in); /*εισάγω τίτλο θεάματος*/ System.out.print("Title: "); String title = input.nextLine(); //αν είναι ήδη καταχωρημενο if(super.ShowExists(title)){ System.out.println("This Show already exists"); return; } /*εισάγω έτος 1ης προβολής*/ System.out.print("Year: "); int year=input.nextInt(); input.nextLine(); /*εισάγω χώρα παραγωγής*/ System.out.print("Country: "); String country=input.nextLine(); /*εισάγω τύπο θεάματος*/ System.out.print("type or types: "); String types=input.nextLine(); String[] arraytypes = types.split(" "); ArrayList<String> typelist = new ArrayList<>(); for (String str : arraytypes) { typelist.add(str.trim()); } System.out.println("types:" + typelist); /*εισάγω σκηνοθέτη*/ System.out.println("Director details:"); System.out.print("Director fullname:"); String directorName=input.nextLine(); Person director; if( super.personExists(directorName) ){ System.out.println("this Director already exists in the system"); director= super.returnPerson(directorName); System.out.println(director.toString()); } else { //εισαγωγη ημερομηνια γεννησης σκηνοθέτη System.out.print("Director birthdate(enter day/month/year with space between them):"); String directorBirthdate=input.nextLine(); String addslashBirthdate = directorBirthdate.replaceAll("\\s+", "/"); System.out.println("Formatted birthdate: " + addslashBirthdate); //εισαγωγη χωρα καταγωγής σκηνοθέτη System.out.print("Director country:"); String directorCountry=input.nextLine(); //εισαγωγη ιστοσελιδα<SUF> System.out.print("Director website:"); String directorWebsite=input.nextLine(); director= new Person(directorName,addslashBirthdate,directorCountry,directorWebsite); System.out.print(director.toString()); personsList.add(director); } //εισαγωγη ηθοποιών System.out.print("enter number of actors you want to add:"); int numberOfactors=input.nextInt(); input.nextLine(); ArrayList<Person> actors=new ArrayList<>(); for(int i=0; i<numberOfactors; i++){ Person actor; //εισαγωγη ονόματος System.out.print("enter actor fullName:"); String actorName=input.nextLine(); if( super.personExists(actorName) ){ System.out.println("this Actor already exists in the system"); actor= super.returnPerson(actorName); System.out.println( actor.toString() ); actors.add(actor); }else{ //εισαγωγη ημερομηνιας γεννησης ηθοποιού System.out.print("enter actor birthdate(enter day/month/year with space between them):"); String actorBirthdate=input.nextLine(); String addslashBirthdate = actorBirthdate.replaceAll("\\s+", "/"); System.out.println("Formatted birthdate: " + addslashBirthdate); //εισαγωγη χώρας ηθοποιού System.out.print("enter actor country:"); String actorCountry=input.nextLine(); //εισαγωγη ιστοσελιδας ηθοποιου System.out.print("enter actor website:"); String actorWebsite=input.nextLine(); //δημιουργω τον ηθοποιό actor= new Person(actorName,addslashBirthdate,actorCountry,actorWebsite); System.out.println(actor.toString()); actors.add(actor); personsList.add(actor); } } System.out.println("is the show a series?(y/n)"); char answer=input.nextLine().charAt(0); if( (answer=='Y') || (answer=='y') ){ System.out.println("enter the number of seasons:"); int seasons=input.nextInt(); //εισαγωγή επεισόδια ανα σεασόν int[] episodesPerSeason= new int[seasons]; for(int i=0; i<seasons; i++){ System.out.print("episodes of season " + (i+1) + ":" ); episodesPerSeason[i]=input.nextInt(); } input.nextLine(); //εισαγωγή έτους τελευταίας προβολής System.out.println("enter series last year(leave it blank if the series is still running):"); String lastYear=input.nextLine(); Series series= new Series(seasons,episodesPerSeason,lastYear,title,year,typelist,country,director,actors); System.out.println(series.toString()); showsList.add(series); System.out.println("series added Successfully!!!"); }else { Show show=new Show(title,year,country,director,typelist,actors); System.out.println(show.toString()); showsList.add(show); System.out.println("Show added Successfully!!!"); } } public void updateSeries(){ System.out.print("provide the serie's id or title that you are searching:"); Scanner input= new Scanner(System.in); String search=input.nextLine(); if(!super.ShowExists(search)){ System.out.println("This Show doesnt exist"); }else if(super.returnShow(search) instanceof Series){ Series series = (Series) super.returnShow(search); System.out.println("Series title:" + series.getTitle()); System.out.println(""" Choose what you want to change: 1. number of seasons 2. number of episodes of a season 3. last year 4. add actor to the series """); int choice=input.nextInt(); switch(choice){ case 1: int previousSeasons=series.getSeasons(); int[]previousEpisodesPerSeason=series.getEpisodesPerSeason(); System.out.print("enter new number of seasons:"); int updatedSeasons=input.nextInt(); int[]updatedEpisodesPerSeason=Arrays.copyOf(previousEpisodesPerSeason, updatedSeasons); series.setSeasons(updatedSeasons); series.setEpisodesPerSeason(updatedEpisodesPerSeason); if(updatedSeasons > previousSeasons){ System.out.println("enter the episodes for the new seasons."); for(int i=1; i<=(updatedSeasons - previousSeasons); i++){ System.out.print("enter the episodes for season " + (previousSeasons + i) +":"); int episodes=input.nextInt(); series.setEpisodesForSeason(previousSeasons + i, episodes); } } System.out.println( "New number of seasons is:"+series.getSeasons() ); System.out.println(Arrays.toString(series.getEpisodesPerSeason()) ); for(int i=1; i<=series.getSeasons(); i++){ System.out.println("Season:" + i +" episodes:" + series.getEpisodesForSeason(i) ); } break; case 2: System.out.print("enter a season out of " + series.getSeasons() +":"); int season=input.nextInt(); if( season<=0 || season>series.getSeasons() ){ System.out.println("wrong input"); }else{ System.out.println("enter number of episodes for season " + season +":"); int episodes=input.nextInt(); if(episodes<=0){ System.out.println("wrong input"); }else{ series.setEpisodesForSeason(season, episodes); } for(int i=1; i<=series.getSeasons(); i++){ System.out.println("Season:" + i +" episodes:" + series.getEpisodesForSeason(i) ); } } break; case 3: System.out.print("enter last year:"); input.nextLine(); String lastYear=input.nextLine(); try{ if(lastYear.equalsIgnoreCase("-")){ series.setLastYear("-"); }else if(Integer.parseInt(lastYear)<=0){ System.out.println("wrong input"); }else{ series.setLastYear(lastYear); } }catch(NumberFormatException e){ System.out.println("wrong input"); } break; case 4: System.out.print("enter actor fullname:"); input.nextLine(); String actorName=input.nextLine(); for( Person p:series.getActors() ){ if(p.getFullName().equalsIgnoreCase(actorName)){ System.out.println("this Actor is already added to this series!"); return; } } Person actor; if( super.personExists(actorName) ){ System.out.println("this Actor already exists in the system"); actor= super.returnPerson(actorName); System.out.println( actor.toString() ); series.addActor(actor); System.out.println(actor.getFullName() + " was added to the actors of this series!"); System.out.println(series.getActors()); }else{ //εισαγωγη ημερομηνιας γεννησης ηθοποιού System.out.print("enter actor birthdate(enter day/month/year with space between them):"); String actorBirthdate=input.nextLine(); String addslashBirthdate = actorBirthdate.replaceAll("\\s+", "/"); System.out.println("Formatted birthdate: " + addslashBirthdate); //εισαγωγη χώρας ηθοποιού System.out.print("enter actor country:"); String actorCountry=input.nextLine(); //εισαγωγη ιστοσελιδας ηθοποιου System.out.print("enter actor website:"); String actorWebsite=input.nextLine(); //δημιουργω τον ηθοποιό actor= new Person(actorName,addslashBirthdate,actorCountry,actorWebsite); System.out.println( actor.toString() ); series.addActor(actor); System.out.println(actor.getFullName() + " was added to the actors of this series and to the system!"); System.out.println(series.getActors()); personsList.add(actor); } break; default: System.out.println("This option was not found."); break; } }else{ System.out.println("This is a show not a series"); } } }
6263_2
package com.example.myevents; import java.lang.*; import android.content.Intent; import androidx.appcompat.app.AppCompatActivity; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import android.widget.RadioGroup; import java.util.List; public class Register extends AppCompatActivity { private static final String TAG = "RegisterActivity"; private EditText signupInputName, signupInputEmail, signupInputPassword ; //Πλαίσια εγγραφής private RadioGroup genderRadioGroup; private static String Name; private static String Password; private static String Email; SharedPreferences pref; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); //Ένωση της κλάσης με το αντίστοιχο xml αρχείο που περιέχει το view της κλάσης pref = PreferenceManager.getDefaultSharedPreferences(this); final Button btnLogin = (Button) findViewById(R.id.btnLogin2); btnLogin.setOnClickListener(new OnClickListener() { public void onClick(View view) { signupInputName = (EditText) findViewById(R.id.signup_input_name); //Αρχικοποίσηση EditTexts βάσει του διαθέσιμου view signupInputEmail = (EditText) findViewById(R.id.signup_input_email); signupInputPassword = (EditText) findViewById(R.id.signup_input_password); genderRadioGroup = (RadioGroup) findViewById(R.id.gender_radio_group); btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Name = signupInputName.getText().toString(); //Λήψη κειμένου από τα EditTexts και αποθήκευσή του σε μορφή String Password = signupInputPassword.getText().toString(); Email = signupInputEmail.getText().toString(); SharedPreferences.Editor editor = pref.edit(); editor.putString("email",Email); editor.apply(); if (Name.isEmpty() || Password.isEmpty() || Email.isEmpty()) { //Σε περίπτωση που ο χρήστης έχει ξεχάσει να συμπληρώσει κάποιο πεδίο Toast.makeText(Register.this, "Παρακαλώ συμπληρώστε τα κενά πεδία.", Toast.LENGTH_SHORT).show(); } else { User newUser = new User(Name,Password,Email,submitForm()); //Δημιουργία Αντικειμένου User SendUser(newUser); //Αποστολή User Intent intent = new Intent(getApplicationContext(), MainActivity.class); //Μεταφορά στην αρχική οθόνη startActivity(intent); Toast.makeText(Register.this, "Επιτυχής Δημιουργία Λογαριασμού.", Toast.LENGTH_SHORT).show(); } } }); } private String submitForm() { //Επιλογή Φύλου και αποθήκευση στη μεταβλητή Gender String Gender = ""; int selectedId = genderRadioGroup.getCheckedRadioButtonId(); if (selectedId == R.id.female_radio_btn) Gender = "Female"; else Gender = "Male"; return Gender; } }); } private void SendUser(User user) //Συνάρτηση upload user { Retrofit send = new Retrofit.Builder() .baseUrl("https://api.e-events.drosatos.eu/android/") //URL στο οποίο θα σταλούν τα δεδομένα .addConverterFactory(GsonConverterFactory.create()) .build(); FetchData sendUser = send.create(FetchData.class); Call<List<User>> Upload = sendUser.UploadUser(user); //Σύνδεση με τη κλάση FetchData Upload.enqueue(new Callback<List<User>>() { @Override public void onResponse(Call<List<User>> call, Response<List<User>> response) { if (!response.isSuccessful()) { Log.e(TAG,Integer.toString(response.code())); return; } Log.e(TAG,response.toString()); } @Override public void onFailure(Call<List<User>> call, Throwable t) { Log.e(TAG,t.getMessage()); } }); } }
Johnylil/E-Events
app/src/main/java/com/example/myevents/Register.java
1,317
//Λήψη κειμένου από τα EditTexts και αποθήκευσή του σε μορφή String
line_comment
el
package com.example.myevents; import java.lang.*; import android.content.Intent; import androidx.appcompat.app.AppCompatActivity; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import android.widget.RadioGroup; import java.util.List; public class Register extends AppCompatActivity { private static final String TAG = "RegisterActivity"; private EditText signupInputName, signupInputEmail, signupInputPassword ; //Πλαίσια εγγραφής private RadioGroup genderRadioGroup; private static String Name; private static String Password; private static String Email; SharedPreferences pref; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); //Ένωση της κλάσης με το αντίστοιχο xml αρχείο που περιέχει το view της κλάσης pref = PreferenceManager.getDefaultSharedPreferences(this); final Button btnLogin = (Button) findViewById(R.id.btnLogin2); btnLogin.setOnClickListener(new OnClickListener() { public void onClick(View view) { signupInputName = (EditText) findViewById(R.id.signup_input_name); //Αρχικοποίσηση EditTexts βάσει του διαθέσιμου view signupInputEmail = (EditText) findViewById(R.id.signup_input_email); signupInputPassword = (EditText) findViewById(R.id.signup_input_password); genderRadioGroup = (RadioGroup) findViewById(R.id.gender_radio_group); btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Name = signupInputName.getText().toString(); //Λήψη κειμένου<SUF> Password = signupInputPassword.getText().toString(); Email = signupInputEmail.getText().toString(); SharedPreferences.Editor editor = pref.edit(); editor.putString("email",Email); editor.apply(); if (Name.isEmpty() || Password.isEmpty() || Email.isEmpty()) { //Σε περίπτωση που ο χρήστης έχει ξεχάσει να συμπληρώσει κάποιο πεδίο Toast.makeText(Register.this, "Παρακαλώ συμπληρώστε τα κενά πεδία.", Toast.LENGTH_SHORT).show(); } else { User newUser = new User(Name,Password,Email,submitForm()); //Δημιουργία Αντικειμένου User SendUser(newUser); //Αποστολή User Intent intent = new Intent(getApplicationContext(), MainActivity.class); //Μεταφορά στην αρχική οθόνη startActivity(intent); Toast.makeText(Register.this, "Επιτυχής Δημιουργία Λογαριασμού.", Toast.LENGTH_SHORT).show(); } } }); } private String submitForm() { //Επιλογή Φύλου και αποθήκευση στη μεταβλητή Gender String Gender = ""; int selectedId = genderRadioGroup.getCheckedRadioButtonId(); if (selectedId == R.id.female_radio_btn) Gender = "Female"; else Gender = "Male"; return Gender; } }); } private void SendUser(User user) //Συνάρτηση upload user { Retrofit send = new Retrofit.Builder() .baseUrl("https://api.e-events.drosatos.eu/android/") //URL στο οποίο θα σταλούν τα δεδομένα .addConverterFactory(GsonConverterFactory.create()) .build(); FetchData sendUser = send.create(FetchData.class); Call<List<User>> Upload = sendUser.UploadUser(user); //Σύνδεση με τη κλάση FetchData Upload.enqueue(new Callback<List<User>>() { @Override public void onResponse(Call<List<User>> call, Response<List<User>> response) { if (!response.isSuccessful()) { Log.e(TAG,Integer.toString(response.code())); return; } Log.e(TAG,response.toString()); } @Override public void onFailure(Call<List<User>> call, Throwable t) { Log.e(TAG,t.getMessage()); } }); } }
37010_0
import java.awt.List; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; import java.util.logging.Logger; import ithakimodem.*; /* * * Δίκτυα Υπολογιστών I * * Experimental Virtual Lab * * Παπαδόπουλος Κωνσταντίνος, Α.Ε.Μ. 8677 * */ public class virtualModem { /////////////////////////////////////////// initializing values String echo="E7281\r"; // Echo request code String imgfree="M4464\r"; // Image request code (Tx/Rx error free) String imgerror="G5996\r"; // Image request code (Tx/Rx with errors) String gps="P2812R=1000099\r"; // GPS request code String gps2="P2812R=1011099\r"; // GPS request code 2 String gps_plain="P2812"; String ack="Q9734\r"; // ACK result code String nack="R9531\r"; // NACK result code /////////////////////////////////////////// public static void main(String[] param) { //(new virtualModem()).nechopackets(5); //(new virtualModem()).imagepackets("error"); //(new virtualModem()).chronoechopackets(480000); //(new virtualModem()).gpspackets(); //(new virtualModem()).acknackpackets(480000); } ////////////////////////////////////////////////// // creates and initializes modem public Modem setmodem(int speed, int timeout){ Modem modem; modem=new Modem(); modem.setSpeed(speed); // set new speed at 8000 (old speed was at 1000) modem.setTimeout(timeout); return modem; } ////////////////////////////////////////////////// /////////////////////////////////////////////////// creates files for input data public FileOutputStream makefile(String filename, String extension){ FileOutputStream fout = null; try { fout = new FileOutputStream(filename + "" + extension); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return fout; } public FileOutputStream makefileappend(String filename, String extension){ // creates appended files for input data FileOutputStream fout = null; try { fout = new FileOutputStream(filename + "" + extension, true); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return fout; } /////////////////////////////////////////////////// public void nechopackets(int number) { // for requesting n number of echo packets int k; Modem modem = setmodem(10000, 2000); // creates and initializes modem FileOutputStream fout = makefile("necho", ".txt"); // opening file to store input data modem.open("ithaki"); for ( ; ; ) { //// it's for emptying the initial message try { k=modem.read(); if (k==-1){ break;} System.out.print((char)k); } catch (Exception x) { break; } } ////////////////////////////////// for (int i = 0; i<number; i++){ modem.write(echo.getBytes()); for ( ; ; ) { //// it's for reading the characters try { k=modem.read(); if (k==-1){fout.write("\r\n".getBytes()); break;} System.out.print((char)k); fout.write(k); } catch (Exception x) { break; } } } modem.close(); }// end of nechopackets ///////////////////////////////////////////////////////////////////////////////// public void imagepackets(String quality) { // error or free int k; Modem modem = setmodem(10000, 2000); // creates and initializes modem FileOutputStream fout = makefile("image", ".jpeg"); // opening file to store input data String img; if (quality == "error") img = imgerror; else img = imgfree; modem.open("ithaki"); for ( ; ; ) { //// it's for emptying the initial message try { k=modem.read(); if (k==-1){ break;} System.out.print((char)k); } catch (Exception x) { break; } } for (int i = 0; i<1; i++){ modem.write(img.getBytes()); for ( ; ; ) { //// it's for reading the characters try { k=modem.read(); if (k==-1){fout.write("\r\n".getBytes()); break;} System.out.print((char)k); fout.write(k); } catch (Exception x) { break; } } } modem.close(); }// end of imagepackets public void acknackpackets(long acktime) { int k; Modem modem = setmodem(10000, 2000); // creates and initializes modem FileOutputStream fout = makefile("ack", ".txt"); // opening file to store input data modem.open("ithaki"); for ( ; ; ) { //// it's for emptying the initial message try { k=modem.read(); if (k==-1){ break;} System.out.print((char)k); } catch (Exception x) { break; } } ////////////////////////////////// String[] fcs; // it is the FCS string in the packet int[] fcsint = new int[1000]; // it is the FCS string in the packet converted to int int[] fcsxor = new int[1000]; // it is the FCS in decimal that comes from the XOR between the characters byte[][] fcsxorbyte = new byte[1000][1000]; // it turns every sequence into bytes byte[] fcsxorbinary = new byte[1000]; // the outcome of every packet that is XORed that needs to become from binary to decimal int whilecounter = 0; // how many times in the while loop int kmscounter = 0; // how many times k==-1 int[] nackpackets = new int[1000]; // for every ack requests how many nack there are for(int i = 0; i <1000; i++){ nackpackets[i] = 0; } int requests = 0; //number of ack requests long[] responsetime = new long[1000]; // measures response time responsetime[0] = 0; long[] tmp = new long[1000]; // counts from ack to ack long tmp2 = 0; // counts inside nack String[] sequence = new String[1000]; // the string sequence of every packet int ackresponseflag = 0; // flag to measure time between two ack packets long[][] tmpn = new long[1000][1000]; //--new long[] responsetimen = new long[1000]; // measures response time //--new responsetimen[0] = 0; //--new long[] responsetimetotal = new long[1000]; //--new long start= System.currentTimeMillis(); long end = start + acktime; while (System.currentTimeMillis() < end){ if ( fcsxor[kmscounter] != fcsint[kmscounter] ){ // result -> ack or nack tmpn[requests][nackpackets[requests]] = System.currentTimeMillis(); //--new counts nack time to receive as well modem.write(nack.getBytes()); ackresponseflag = 0; nackpackets[requests]++; } else{ tmp[requests] = System.currentTimeMillis(); modem.write(ack.getBytes()); ackresponseflag = 1; requests++; } for ( ; ; ) { //// it's for reading the characters try { k=modem.read(); System.out.print((char)k); if (k==-1){ fout.write("\r\n".getBytes()); if (ackresponseflag == 0) //--new counts nack time to receive as well responsetimen[requests] += System.currentTimeMillis() - tmpn[requests][nackpackets[requests]-1]; //--new if (ackresponseflag == 1) responsetime[requests] = System.currentTimeMillis() - tmp[requests-1]; responsetimetotal[requests] = responsetimen[requests] + responsetime[requests]; //--new //////////////////////////////////////////////////////////////////////// kmscounter++; break; } // end of if k==-1 fout.write(k); } catch (Exception x) { break; } } // end of infinite for loop BufferedReader in = null; // opens reader for the file to be scanned try { in = new BufferedReader(new FileReader("ack.txt")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String str; ArrayList list = new ArrayList(); // puts every line of the file into list try { while((str = in.readLine()) != null){ list.add(str); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String[] stockArr = new String[list.size()]; // converts list into String array String[] stringArr = (String[]) list.toArray(stockArr); String temp = ""; for(int y = 49; y <=51 ; y++){ temp += Character.toString(stringArr[kmscounter-1].charAt(y)); } //System.out.print("---fcsint---" + temp + "\n"); fcsint[kmscounter] = Integer.parseInt(temp); // gets integer value of fcs temp =""; for(int y = 31; y <=46 ; y++){ temp += Character.toString(stringArr[kmscounter-1].charAt(y)); } sequence[kmscounter] = temp; try { in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } fcsxorbyte[kmscounter] = sequence[kmscounter].getBytes(); // turns every sequence into bytes byte tmpbyte = fcsxorbyte[kmscounter][0]; // initializes tmpbyte for(int y = 0; y<15 ; y++){ // do xor to all characters tmpbyte = (byte)(tmpbyte^fcsxorbyte[kmscounter][y+1]); fcsxorbinary[kmscounter] = tmpbyte; //System.out.print("--sequence--" + kmscounter + " is " + (int)fcsxorbinary[kmscounter] + "\n"); } fcsxor[kmscounter] = (int) fcsxorbinary[kmscounter]; //System.out.print("--THE fcsxor[kmscounter]-- " + fcsxor[kmscounter] + "\n"); //System.out.print("--fcsxorbyte[kmscounter][0]--" + fcsxorbyte[kmscounter][0] + "\n"); //System.out.print("--fcsxorbyte[kmscounter][1]--" + fcsxorbyte[kmscounter][1] + "\n"); //byte test = (byte)(fcsxorbyte[kmscounter][2]^((byte) (fcsxorbyte[kmscounter][0]^fcsxorbyte[kmscounter][0+1]))); //System.out.print("--test--" + test + "\n"); //System.out.print("--final--" + fcsxor[kmscounter] + "\n"); whilecounter++; } // end of while modem.close(); String[] str = new String[requests]; for (int y=1;y<requests;y++){ // write input data of response times into file, start from 1 (0+1) // because if you send n ack packets there are n-1 response times //str[y] = Long.toString(responsetime[y]); //--new bring back str[y] = Long.toString(responsetimetotal[y]); //--new try (FileWriter out = new FileWriter("response_ack_nack.txt",true)) { out.write(str[y]); out.write("\r\n"); } catch (IOException exc) { System.out.println("Exception "); } } System.out.print("\n"+"--NUMBER OF REQUESTS (ACK PACKETS)--" + requests + "\n"); for(int i=0; i<requests; i++) System.out.print("--NUMBER OF NACK (NACK PACKETS)--" + (i+1) + " " + nackpackets[i] + "\n"); } // end of acknackpackets2 public void chronoechopackets(long echotime) { int k; String[] str = new String[200]; // to save response times as strings long[] responsetime = new long[200]; // to save response times Modem modem = setmodem(10000, 2000); // creates and initializes modem FileOutputStream fout = makefile("chronoecho", ".txt"); // opening file to store input data int t = 0; modem.open("ithaki"); for ( ; ; ) { //// it's for emptying the initial message try { k=modem.read(); if (k==-1){ break;} System.out.print((char)k); } catch (Exception x) { break; } } ////////////////////////////////// long start= System.currentTimeMillis(); long end = start + echotime; long timesent; while (System.currentTimeMillis() < end){ timesent = System.currentTimeMillis(); // start of measuring response time modem.write(echo.getBytes()); for ( ; ; ) { //// it's for reading the characters try { k=modem.read(); // while k!=0 if (k==-1){ responsetime[t] = System.currentTimeMillis() - timesent; // end of measuring response time fout.write("\r\n".getBytes()); t++; break;} System.out.print((char)k); fout.write(k); } catch (Exception x) { break; } } } modem.close(); for (int y=0;y<t;y++){ // write input data of response times into file str[y] = Long.toString(responsetime[y]); try (FileWriter out = new FileWriter("echoresponse.txt",true)) { out.write(str[y]); out.write("\r\n"); } catch (IOException exc) { System.out.println("Exception "); } } }// end of chronoechopackets2 public void gpspackets() { int k; Modem modem = setmodem(10000, 2000); // creates and initializes modem FileOutputStream fout = makefile("gps", ".txt"); // opening file to store input data int l = 0; // lines of N,E arrays, increases every time we find a packet with the correct format modem.open("ithaki"); for ( ; ; ) { //// it's for emptying the initial message try { k=modem.read(); if (k==-1){ break;} System.out.print((char)k); } catch (Exception x) { break; } } ////////////////////////////////// for (int i = 0; i<1; i++){ modem.write(gps.getBytes()); modem.write(gps2.getBytes()); // two different gps routes for the data files for ( ; ; ) { //// it's for reading the characters try { k=modem.read(); if (k==-1){fout.write("\r\n".getBytes()); break;} System.out.print((char)k); fout.write(k); } catch (Exception x) { break; } } } modem.close(); //blankremover("gpstest.txt"); ///////////////////////////////////////////////////////////////this part scans for the coordinates BufferedReader in = null; // opens reader for the file to be scanned try { in = new BufferedReader(new FileReader("gps.txt")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String str; ArrayList list = new ArrayList(); // puts every line of the file into list try { while((str = in.readLine()) != null){ list.add(str); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String[] stockArr = new String[list.size()]; // converts list into String array String[] stringArr = (String[]) list.toArray(stockArr); int numtraces=0; // traces that have 4" difference String[] North = new String[1000]; //initialize Strings for North and South coordinates for(int i = 0; i < 1000; i++){ North[i] = ""; } String[] East = new String[1000]; for(int i = 0; i < 1000; i++){ East[i] = ""; } String[] Northconvert = new String[198]; //initialize Strings for North and South coordinates to be converted for(int i = 0; i < 198; i++){ Northconvert[i] = ""; } String[] Eastconvert = new String[198]; // 198 because that's the lines of the gps file for(int i = 0; i < 198; i++){ Eastconvert[i] = ""; } /////////////////////////////////////////////////////// initialize Strings for Hours, Minutes, Seconds String[] Hours = new String[1000]; //initialize Strings for North and South coordinates for(int i = 0; i < 1000; i++){ Hours[i] = "0"; } String[] Minutes = new String[1000]; //initialize Strings for North and South coordinates for(int i = 0; i < 1000; i++){ Minutes[i] = "0"; } String[] Seconds = new String[1000]; //initialize Strings for North and South coordinates for(int i = 0; i < 1000; i++){ Seconds[i] = "0"; } int[] conversioneast= new int[1000]; // converts to " of degrees int[] conversionnorth= new int[1000]; // converts to " of degrees /////////////////////////////////////////////////////// String[] trace = new String[6]; // the final traces for (int i = 1; i<(stringArr.length-2); i++){ if (stringArr[i].charAt(4) == 'G' ){ // checking for correct gps format for(int y = 18; y<=21 ; y++){ North[l] += Character.toString(stringArr[i].charAt(y)); } for(int y = 23; y<=24 ; y++){ Northconvert[l] += Character.toString(stringArr[i].charAt(y)); } for(int y = 31; y<=34 ; y++ ){ East[l] += Character.toString(stringArr[i].charAt(y)); } for(int y = 36; y<=37; y++){ Eastconvert[l] += Character.toString(stringArr[i].charAt(y)); } ////////////////////////////////////////get time for(int y = 7; y<=8 ; y++){ // hours Hours[l] += Character.toString(stringArr[i].charAt(y)); } for(int y = 9; y<=10 ; y++){ // minutes Minutes[l] += Character.toString(stringArr[i].charAt(y)); } for(int y = 10; y<=11 ; y++){ // seconds Seconds[l] += Character.toString(stringArr[i].charAt(y)); } l++; } } /////////////////////////////////////////////////////////// conversions for (int y = 0; y < Northconvert.length; y++){ conversionnorth[y] = (int) (0.6 * Integer.valueOf(Northconvert[y])); // converts to " Northconvert[y] = String.valueOf(conversionnorth[y]); // converts to String again North[y] += Northconvert[y]; // re-attaches to String conversioneast[y] = (int) (0.6 * Integer.valueOf(Eastconvert[y])); Eastconvert[y] = String.valueOf(conversioneast[y]); East[y] += Eastconvert[y]; } //////////////////////////////////////////// making arrays for reading time int[] hoursint = new int[Hours.length]; int[] minutesint = new int[Minutes.length]; int[] secondsint = new int[Seconds.length]; int[] timeint = new int[Hours.length]; for (int y = 0; y < Hours.length; y++){ hoursint[y] = 3600 * Integer.valueOf(Hours[y]); minutesint[y] = 60 * Integer.valueOf(Minutes[y]); secondsint[y] = 1 * Integer.valueOf(Seconds[y]); timeint[y] = hoursint[y] + minutesint[y] + secondsint[y]; } //////////////////////////////////////////////////////// int z; // trying to find traces that are 4" away, the numbers of z and y are random for (z = 20; z < l; z++){ for(int y= z + 100; y<l;y=y+30, z += 50){ if ((Math.abs(timeint[z] - timeint[y])) >= 50 && numtraces!=4){ trace[numtraces] = East[z] + North[z]; trace[numtraces+1] = East[y] + North[y]; numtraces=numtraces+2; System.out.print(z + "\n"); } } } /* trace[0] = East[0] + North[0]; // since the time in the data is increasing by 1 sec in every packet trace[1] = East[50] + North[50]; // the traces are definitely 4" away (50 secs to be exact) trace[2] = East[100] + North[100]; trace[3] = East[150] + North[150]; */ /////////////////////////////////////////////////////////////////////////new image String newgpscode = new String(); newgpscode = gps_plain + "T=" + trace[0] + "T=" + trace[1] + "T=" + trace[2] + "T=" + trace[3] + "\r"; System.out.print("THIS IS THE NEW GPS CODE " + newgpscode +"\n"); int k2; Modem modem2 = setmodem(10000, 2000); // creates and initializes modem FileOutputStream fout2 = makefile("gps", ".jpeg"); // opening file to store input data modem2.open("ithaki"); for ( ; ; ) { //// it's for emptying the initial message try { k2=modem2.read(); if (k2==-1){ break;} System.out.print((char)k2); } catch (Exception x) { break; } } for (int i = 0; i<1; i++){ modem2.write(newgpscode.getBytes()); for ( ; ; ) { //// it's for reading the characters try { k2=modem2.read(); if (k2==-1){fout2.write("\r\n".getBytes()); break;} System.out.print((char)k2); fout2.write(k2); } catch (Exception x) { break; } } } modem2.close(); }// end of gpspackets //////////////////removes empty lines from files (it isn't used eventually) public void blankremover(String args) { Scanner file; PrintWriter writer; try { file = new Scanner(new File(args)); writer = new PrintWriter("gpstest100.txt"); while (file.hasNext()) { String line = file.nextLine(); if (!line.isEmpty()) { writer.write(line); writer.write("\n"); } } file.close(); writer.close(); } catch (FileNotFoundException ex) { //Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex); } } // end of blankremover } // end of class
KAUTH/University-Projects
Computer Networks (Java)/Course 1/userApplication.java
6,673
/* * * Δίκτυα Υπολογιστών I * * Experimental Virtual Lab * * Παπαδόπουλος Κωνσταντίνος, Α.Ε.Μ. 8677 * */
block_comment
el
import java.awt.List; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; import java.util.logging.Logger; import ithakimodem.*; /* * * Δίκτυα Υπολογιστών I <SUF>*/ public class virtualModem { /////////////////////////////////////////// initializing values String echo="E7281\r"; // Echo request code String imgfree="M4464\r"; // Image request code (Tx/Rx error free) String imgerror="G5996\r"; // Image request code (Tx/Rx with errors) String gps="P2812R=1000099\r"; // GPS request code String gps2="P2812R=1011099\r"; // GPS request code 2 String gps_plain="P2812"; String ack="Q9734\r"; // ACK result code String nack="R9531\r"; // NACK result code /////////////////////////////////////////// public static void main(String[] param) { //(new virtualModem()).nechopackets(5); //(new virtualModem()).imagepackets("error"); //(new virtualModem()).chronoechopackets(480000); //(new virtualModem()).gpspackets(); //(new virtualModem()).acknackpackets(480000); } ////////////////////////////////////////////////// // creates and initializes modem public Modem setmodem(int speed, int timeout){ Modem modem; modem=new Modem(); modem.setSpeed(speed); // set new speed at 8000 (old speed was at 1000) modem.setTimeout(timeout); return modem; } ////////////////////////////////////////////////// /////////////////////////////////////////////////// creates files for input data public FileOutputStream makefile(String filename, String extension){ FileOutputStream fout = null; try { fout = new FileOutputStream(filename + "" + extension); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return fout; } public FileOutputStream makefileappend(String filename, String extension){ // creates appended files for input data FileOutputStream fout = null; try { fout = new FileOutputStream(filename + "" + extension, true); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return fout; } /////////////////////////////////////////////////// public void nechopackets(int number) { // for requesting n number of echo packets int k; Modem modem = setmodem(10000, 2000); // creates and initializes modem FileOutputStream fout = makefile("necho", ".txt"); // opening file to store input data modem.open("ithaki"); for ( ; ; ) { //// it's for emptying the initial message try { k=modem.read(); if (k==-1){ break;} System.out.print((char)k); } catch (Exception x) { break; } } ////////////////////////////////// for (int i = 0; i<number; i++){ modem.write(echo.getBytes()); for ( ; ; ) { //// it's for reading the characters try { k=modem.read(); if (k==-1){fout.write("\r\n".getBytes()); break;} System.out.print((char)k); fout.write(k); } catch (Exception x) { break; } } } modem.close(); }// end of nechopackets ///////////////////////////////////////////////////////////////////////////////// public void imagepackets(String quality) { // error or free int k; Modem modem = setmodem(10000, 2000); // creates and initializes modem FileOutputStream fout = makefile("image", ".jpeg"); // opening file to store input data String img; if (quality == "error") img = imgerror; else img = imgfree; modem.open("ithaki"); for ( ; ; ) { //// it's for emptying the initial message try { k=modem.read(); if (k==-1){ break;} System.out.print((char)k); } catch (Exception x) { break; } } for (int i = 0; i<1; i++){ modem.write(img.getBytes()); for ( ; ; ) { //// it's for reading the characters try { k=modem.read(); if (k==-1){fout.write("\r\n".getBytes()); break;} System.out.print((char)k); fout.write(k); } catch (Exception x) { break; } } } modem.close(); }// end of imagepackets public void acknackpackets(long acktime) { int k; Modem modem = setmodem(10000, 2000); // creates and initializes modem FileOutputStream fout = makefile("ack", ".txt"); // opening file to store input data modem.open("ithaki"); for ( ; ; ) { //// it's for emptying the initial message try { k=modem.read(); if (k==-1){ break;} System.out.print((char)k); } catch (Exception x) { break; } } ////////////////////////////////// String[] fcs; // it is the FCS string in the packet int[] fcsint = new int[1000]; // it is the FCS string in the packet converted to int int[] fcsxor = new int[1000]; // it is the FCS in decimal that comes from the XOR between the characters byte[][] fcsxorbyte = new byte[1000][1000]; // it turns every sequence into bytes byte[] fcsxorbinary = new byte[1000]; // the outcome of every packet that is XORed that needs to become from binary to decimal int whilecounter = 0; // how many times in the while loop int kmscounter = 0; // how many times k==-1 int[] nackpackets = new int[1000]; // for every ack requests how many nack there are for(int i = 0; i <1000; i++){ nackpackets[i] = 0; } int requests = 0; //number of ack requests long[] responsetime = new long[1000]; // measures response time responsetime[0] = 0; long[] tmp = new long[1000]; // counts from ack to ack long tmp2 = 0; // counts inside nack String[] sequence = new String[1000]; // the string sequence of every packet int ackresponseflag = 0; // flag to measure time between two ack packets long[][] tmpn = new long[1000][1000]; //--new long[] responsetimen = new long[1000]; // measures response time //--new responsetimen[0] = 0; //--new long[] responsetimetotal = new long[1000]; //--new long start= System.currentTimeMillis(); long end = start + acktime; while (System.currentTimeMillis() < end){ if ( fcsxor[kmscounter] != fcsint[kmscounter] ){ // result -> ack or nack tmpn[requests][nackpackets[requests]] = System.currentTimeMillis(); //--new counts nack time to receive as well modem.write(nack.getBytes()); ackresponseflag = 0; nackpackets[requests]++; } else{ tmp[requests] = System.currentTimeMillis(); modem.write(ack.getBytes()); ackresponseflag = 1; requests++; } for ( ; ; ) { //// it's for reading the characters try { k=modem.read(); System.out.print((char)k); if (k==-1){ fout.write("\r\n".getBytes()); if (ackresponseflag == 0) //--new counts nack time to receive as well responsetimen[requests] += System.currentTimeMillis() - tmpn[requests][nackpackets[requests]-1]; //--new if (ackresponseflag == 1) responsetime[requests] = System.currentTimeMillis() - tmp[requests-1]; responsetimetotal[requests] = responsetimen[requests] + responsetime[requests]; //--new //////////////////////////////////////////////////////////////////////// kmscounter++; break; } // end of if k==-1 fout.write(k); } catch (Exception x) { break; } } // end of infinite for loop BufferedReader in = null; // opens reader for the file to be scanned try { in = new BufferedReader(new FileReader("ack.txt")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String str; ArrayList list = new ArrayList(); // puts every line of the file into list try { while((str = in.readLine()) != null){ list.add(str); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String[] stockArr = new String[list.size()]; // converts list into String array String[] stringArr = (String[]) list.toArray(stockArr); String temp = ""; for(int y = 49; y <=51 ; y++){ temp += Character.toString(stringArr[kmscounter-1].charAt(y)); } //System.out.print("---fcsint---" + temp + "\n"); fcsint[kmscounter] = Integer.parseInt(temp); // gets integer value of fcs temp =""; for(int y = 31; y <=46 ; y++){ temp += Character.toString(stringArr[kmscounter-1].charAt(y)); } sequence[kmscounter] = temp; try { in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } fcsxorbyte[kmscounter] = sequence[kmscounter].getBytes(); // turns every sequence into bytes byte tmpbyte = fcsxorbyte[kmscounter][0]; // initializes tmpbyte for(int y = 0; y<15 ; y++){ // do xor to all characters tmpbyte = (byte)(tmpbyte^fcsxorbyte[kmscounter][y+1]); fcsxorbinary[kmscounter] = tmpbyte; //System.out.print("--sequence--" + kmscounter + " is " + (int)fcsxorbinary[kmscounter] + "\n"); } fcsxor[kmscounter] = (int) fcsxorbinary[kmscounter]; //System.out.print("--THE fcsxor[kmscounter]-- " + fcsxor[kmscounter] + "\n"); //System.out.print("--fcsxorbyte[kmscounter][0]--" + fcsxorbyte[kmscounter][0] + "\n"); //System.out.print("--fcsxorbyte[kmscounter][1]--" + fcsxorbyte[kmscounter][1] + "\n"); //byte test = (byte)(fcsxorbyte[kmscounter][2]^((byte) (fcsxorbyte[kmscounter][0]^fcsxorbyte[kmscounter][0+1]))); //System.out.print("--test--" + test + "\n"); //System.out.print("--final--" + fcsxor[kmscounter] + "\n"); whilecounter++; } // end of while modem.close(); String[] str = new String[requests]; for (int y=1;y<requests;y++){ // write input data of response times into file, start from 1 (0+1) // because if you send n ack packets there are n-1 response times //str[y] = Long.toString(responsetime[y]); //--new bring back str[y] = Long.toString(responsetimetotal[y]); //--new try (FileWriter out = new FileWriter("response_ack_nack.txt",true)) { out.write(str[y]); out.write("\r\n"); } catch (IOException exc) { System.out.println("Exception "); } } System.out.print("\n"+"--NUMBER OF REQUESTS (ACK PACKETS)--" + requests + "\n"); for(int i=0; i<requests; i++) System.out.print("--NUMBER OF NACK (NACK PACKETS)--" + (i+1) + " " + nackpackets[i] + "\n"); } // end of acknackpackets2 public void chronoechopackets(long echotime) { int k; String[] str = new String[200]; // to save response times as strings long[] responsetime = new long[200]; // to save response times Modem modem = setmodem(10000, 2000); // creates and initializes modem FileOutputStream fout = makefile("chronoecho", ".txt"); // opening file to store input data int t = 0; modem.open("ithaki"); for ( ; ; ) { //// it's for emptying the initial message try { k=modem.read(); if (k==-1){ break;} System.out.print((char)k); } catch (Exception x) { break; } } ////////////////////////////////// long start= System.currentTimeMillis(); long end = start + echotime; long timesent; while (System.currentTimeMillis() < end){ timesent = System.currentTimeMillis(); // start of measuring response time modem.write(echo.getBytes()); for ( ; ; ) { //// it's for reading the characters try { k=modem.read(); // while k!=0 if (k==-1){ responsetime[t] = System.currentTimeMillis() - timesent; // end of measuring response time fout.write("\r\n".getBytes()); t++; break;} System.out.print((char)k); fout.write(k); } catch (Exception x) { break; } } } modem.close(); for (int y=0;y<t;y++){ // write input data of response times into file str[y] = Long.toString(responsetime[y]); try (FileWriter out = new FileWriter("echoresponse.txt",true)) { out.write(str[y]); out.write("\r\n"); } catch (IOException exc) { System.out.println("Exception "); } } }// end of chronoechopackets2 public void gpspackets() { int k; Modem modem = setmodem(10000, 2000); // creates and initializes modem FileOutputStream fout = makefile("gps", ".txt"); // opening file to store input data int l = 0; // lines of N,E arrays, increases every time we find a packet with the correct format modem.open("ithaki"); for ( ; ; ) { //// it's for emptying the initial message try { k=modem.read(); if (k==-1){ break;} System.out.print((char)k); } catch (Exception x) { break; } } ////////////////////////////////// for (int i = 0; i<1; i++){ modem.write(gps.getBytes()); modem.write(gps2.getBytes()); // two different gps routes for the data files for ( ; ; ) { //// it's for reading the characters try { k=modem.read(); if (k==-1){fout.write("\r\n".getBytes()); break;} System.out.print((char)k); fout.write(k); } catch (Exception x) { break; } } } modem.close(); //blankremover("gpstest.txt"); ///////////////////////////////////////////////////////////////this part scans for the coordinates BufferedReader in = null; // opens reader for the file to be scanned try { in = new BufferedReader(new FileReader("gps.txt")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String str; ArrayList list = new ArrayList(); // puts every line of the file into list try { while((str = in.readLine()) != null){ list.add(str); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String[] stockArr = new String[list.size()]; // converts list into String array String[] stringArr = (String[]) list.toArray(stockArr); int numtraces=0; // traces that have 4" difference String[] North = new String[1000]; //initialize Strings for North and South coordinates for(int i = 0; i < 1000; i++){ North[i] = ""; } String[] East = new String[1000]; for(int i = 0; i < 1000; i++){ East[i] = ""; } String[] Northconvert = new String[198]; //initialize Strings for North and South coordinates to be converted for(int i = 0; i < 198; i++){ Northconvert[i] = ""; } String[] Eastconvert = new String[198]; // 198 because that's the lines of the gps file for(int i = 0; i < 198; i++){ Eastconvert[i] = ""; } /////////////////////////////////////////////////////// initialize Strings for Hours, Minutes, Seconds String[] Hours = new String[1000]; //initialize Strings for North and South coordinates for(int i = 0; i < 1000; i++){ Hours[i] = "0"; } String[] Minutes = new String[1000]; //initialize Strings for North and South coordinates for(int i = 0; i < 1000; i++){ Minutes[i] = "0"; } String[] Seconds = new String[1000]; //initialize Strings for North and South coordinates for(int i = 0; i < 1000; i++){ Seconds[i] = "0"; } int[] conversioneast= new int[1000]; // converts to " of degrees int[] conversionnorth= new int[1000]; // converts to " of degrees /////////////////////////////////////////////////////// String[] trace = new String[6]; // the final traces for (int i = 1; i<(stringArr.length-2); i++){ if (stringArr[i].charAt(4) == 'G' ){ // checking for correct gps format for(int y = 18; y<=21 ; y++){ North[l] += Character.toString(stringArr[i].charAt(y)); } for(int y = 23; y<=24 ; y++){ Northconvert[l] += Character.toString(stringArr[i].charAt(y)); } for(int y = 31; y<=34 ; y++ ){ East[l] += Character.toString(stringArr[i].charAt(y)); } for(int y = 36; y<=37; y++){ Eastconvert[l] += Character.toString(stringArr[i].charAt(y)); } ////////////////////////////////////////get time for(int y = 7; y<=8 ; y++){ // hours Hours[l] += Character.toString(stringArr[i].charAt(y)); } for(int y = 9; y<=10 ; y++){ // minutes Minutes[l] += Character.toString(stringArr[i].charAt(y)); } for(int y = 10; y<=11 ; y++){ // seconds Seconds[l] += Character.toString(stringArr[i].charAt(y)); } l++; } } /////////////////////////////////////////////////////////// conversions for (int y = 0; y < Northconvert.length; y++){ conversionnorth[y] = (int) (0.6 * Integer.valueOf(Northconvert[y])); // converts to " Northconvert[y] = String.valueOf(conversionnorth[y]); // converts to String again North[y] += Northconvert[y]; // re-attaches to String conversioneast[y] = (int) (0.6 * Integer.valueOf(Eastconvert[y])); Eastconvert[y] = String.valueOf(conversioneast[y]); East[y] += Eastconvert[y]; } //////////////////////////////////////////// making arrays for reading time int[] hoursint = new int[Hours.length]; int[] minutesint = new int[Minutes.length]; int[] secondsint = new int[Seconds.length]; int[] timeint = new int[Hours.length]; for (int y = 0; y < Hours.length; y++){ hoursint[y] = 3600 * Integer.valueOf(Hours[y]); minutesint[y] = 60 * Integer.valueOf(Minutes[y]); secondsint[y] = 1 * Integer.valueOf(Seconds[y]); timeint[y] = hoursint[y] + minutesint[y] + secondsint[y]; } //////////////////////////////////////////////////////// int z; // trying to find traces that are 4" away, the numbers of z and y are random for (z = 20; z < l; z++){ for(int y= z + 100; y<l;y=y+30, z += 50){ if ((Math.abs(timeint[z] - timeint[y])) >= 50 && numtraces!=4){ trace[numtraces] = East[z] + North[z]; trace[numtraces+1] = East[y] + North[y]; numtraces=numtraces+2; System.out.print(z + "\n"); } } } /* trace[0] = East[0] + North[0]; // since the time in the data is increasing by 1 sec in every packet trace[1] = East[50] + North[50]; // the traces are definitely 4" away (50 secs to be exact) trace[2] = East[100] + North[100]; trace[3] = East[150] + North[150]; */ /////////////////////////////////////////////////////////////////////////new image String newgpscode = new String(); newgpscode = gps_plain + "T=" + trace[0] + "T=" + trace[1] + "T=" + trace[2] + "T=" + trace[3] + "\r"; System.out.print("THIS IS THE NEW GPS CODE " + newgpscode +"\n"); int k2; Modem modem2 = setmodem(10000, 2000); // creates and initializes modem FileOutputStream fout2 = makefile("gps", ".jpeg"); // opening file to store input data modem2.open("ithaki"); for ( ; ; ) { //// it's for emptying the initial message try { k2=modem2.read(); if (k2==-1){ break;} System.out.print((char)k2); } catch (Exception x) { break; } } for (int i = 0; i<1; i++){ modem2.write(newgpscode.getBytes()); for ( ; ; ) { //// it's for reading the characters try { k2=modem2.read(); if (k2==-1){fout2.write("\r\n".getBytes()); break;} System.out.print((char)k2); fout2.write(k2); } catch (Exception x) { break; } } } modem2.close(); }// end of gpspackets //////////////////removes empty lines from files (it isn't used eventually) public void blankremover(String args) { Scanner file; PrintWriter writer; try { file = new Scanner(new File(args)); writer = new PrintWriter("gpstest100.txt"); while (file.hasNext()) { String line = file.nextLine(); if (!line.isEmpty()) { writer.write(line); writer.write("\n"); } } file.close(); writer.close(); } catch (FileNotFoundException ex) { //Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex); } } // end of blankremover } // end of class
1470_6
package gr.aueb.cf.c1.ch10; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.nio.file.Path; import java.nio.file.Paths; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.Arrays; import java.util.Scanner; public class MobileContactsApp { final static String[][] contacts = new String[500][3]; static int pivot = -1; final static Path path = Paths.get("C:/tmp/log-mobile.txt"); static Scanner in = new Scanner(System.in); public static void main(String[] args) { boolean quit = false; String s; int choice; String phoneNumber; do { printMenu(); s = getChoice(); if (s.matches("[qQ]")) quit = true; else { try { choice = Integer.parseInt(s); if (!(isValid(choice))) { throw new IllegalArgumentException("Error - Choice"); } switch (choice) { case 1: printContactMenu(); insertController(getFirstname(), getLastname(), getPhoneNumber()); System.out.println("Επιτυχής Εισαγωγή"); break; case 2: phoneNumber = getPhoneNumber(); deleteController(phoneNumber); System.out.println("Επιτυχής Διαγραφή"); break; case 3: phoneNumber = getPhoneNumber(); printContactMenu(); updateController(phoneNumber, getFirstname(), getLastname(), getPhoneNumber()); System.out.println("Επιτυχής Ενημέρωση"); break; case 4: phoneNumber = getPhoneNumber(); String[] contact = getOneController(phoneNumber); printContact(contact); break; case 5: String[][] allContacts = getAllController(); printAllContacts(allContacts); break; default: throw new IllegalArgumentException("Bad choice"); } } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } } }while (!quit); } public static void printContact(String[] contact) { for (String s : contact) { System.out.print(s + " "); } } public static void printAllContacts(String[][] contacts) { for (String[] contact : contacts) { printContact(contact); } } public static boolean isValid(int choice) { return ((choice >= 1) && (choice <= 5)); } public static void printMenu() { System.out.println("Επιλέξτε ένα από τα παρακάτω"); System.out.println("1. Εισαγωγή επαφής"); System.out.println("2. Διαγραφή επαφής"); System.out.println("3. Ενημέρωση επαφής"); System.out.println("4. Αναζήτηση επαφής"); System.out.println("5. Εκτύπωση επαφής"); System.out.println("Q. Έξοδος επαφής"); } public static String getChoice() { System.out.println("Εισάγετε επιλογή"); return in.nextLine().trim(); } public static void printContactMenu() { System.out.println("Εισάγετε όνομα, επώνυμο, τηλέφωνο"); } public static String getFirstname(){ System.out.println("Εισάγετε όνομα"); return in.nextLine().trim(); } public static String getLastname(){ System.out.println("Εισάγετε επώνυμο"); return in.nextLine().trim(); } public static String getPhoneNumber(){ System.out.println("Εισάγετε τηλέφωνο"); return in.nextLine().trim(); } public static void insertController(String firstname, String lastname, String phoneNumber) { try { //validation if (firstname == null || lastname == null || phoneNumber == null){ throw new IllegalArgumentException("Null are not allowed"); } if (firstname.length() < 2 || firstname.length() > 50) { throw new IllegalArgumentException("Firstname is not valid"); } if (lastname.length() < 2 || lastname.length() > 50) { throw new IllegalArgumentException("Last name is not valid"); } if (phoneNumber.length() < 2 || phoneNumber.length() > 12) { throw new IllegalArgumentException("Phone number is not valid"); } //call services insertContactServices(firstname.trim(), lastname.trim(), phoneNumber.trim()); } catch (IllegalArgumentException e) { e.printStackTrace(); throw e; } } public static void updateController(String oldPhoneNumber, String firstname, String lastname, String newPhoneNumber) { try { //validation if (oldPhoneNumber == null || firstname == null || lastname == null || newPhoneNumber == null){ throw new IllegalArgumentException("Null are not allowed"); } if (oldPhoneNumber.length() < 2 || oldPhoneNumber.length() > 50) { throw new IllegalArgumentException("Old number is not valid"); } if (firstname.length() < 2 || firstname.length() > 50) { throw new IllegalArgumentException("First name is not valid"); } if (lastname.length() < 2 || lastname.length() > 50) { throw new IllegalArgumentException("Last number is not valid"); } if (newPhoneNumber.length() < 2 || newPhoneNumber.length() > 12) { throw new IllegalArgumentException("New phone number is not valid"); } //call services updateContactServices(oldPhoneNumber.trim(), firstname.trim(), lastname.trim(), newPhoneNumber.trim()); } catch (IllegalArgumentException e) { e.printStackTrace(); throw e; } } public static String[] deleteController(String phoneNumber) { try { if (phoneNumber.length() < 2 || phoneNumber.length() > 12) { throw new IllegalArgumentException("Phone number is not valid"); } return deleteController(phoneNumber); }catch (IllegalArgumentException e) { e.printStackTrace(); throw e; } } public static String[] getOneController(String phoneNumber) { try { if (phoneNumber.length() < 2 || phoneNumber.length() > 12) { throw new IllegalArgumentException("Phone number is not valid"); } return getOneController(phoneNumber); }catch (IllegalArgumentException e) { e.printStackTrace(); throw e; } } public static String[][] getAllController() { try { return getAllContactsServices(); } catch (IllegalArgumentException e) { e.printStackTrace(); throw e; } } /* CRUD services that are provided to Services Layer */ public static int getIndexByPhone(String phoneNumber) { for (int i = 0; i <= pivot; i++) { if (contacts[i][2].equals(phoneNumber)) { return i; } } return -1; // if not found } public static boolean insert(String firstname, String lastname, String phoneNumber) { boolean inserted = false; if(isFull(contacts)) { return false; } if (getIndexByPhone(phoneNumber) != -1) { return false; } pivot++; contacts[pivot][0] = firstname; contacts[pivot][1] = lastname; contacts[pivot][2] = phoneNumber; return true; } public static boolean update(String oldPhoneNumber, String firstname, String lastname, String newPhoneNumber) { int positionToUpdate = getIndexByPhone(oldPhoneNumber); String[] contact = new String[3]; if (positionToUpdate == -1) { return false; // return new String[] {}; } // contact[0] = contacts[positionToUpdate][0]; // contact[1] = contacts[positionToUpdate][1]; // contact[2] = contacts[positionToUpdate][2]; contacts[positionToUpdate][0] = firstname; contacts[positionToUpdate][1] = lastname; contacts[positionToUpdate][2] = newPhoneNumber; return true; } public static String[] delete(String phoneNumber) { int positionToDelete = getIndexByPhone(phoneNumber); String[] contact = new String[3]; if (positionToDelete == -1) { return new String[] {}; } System.arraycopy(contacts[positionToDelete], 0, contact, 0, contact.length); if (!(positionToDelete == contacts.length - 1)) { System.arraycopy(contacts, positionToDelete + 1, contacts, positionToDelete, pivot - positionToDelete); } pivot--; return contact; } public static String[] getContactByPhoneNumber(String phoneNumber) { int positionToReturn = getIndexByPhone(phoneNumber); if (positionToReturn == -1) { return new String[] {}; } return contacts[positionToReturn]; } public static String[][] getAllContacts() { return Arrays.copyOf(contacts, pivot + 1); } // όταν ο pivot δείχνει στην arr.length - 1 αυτό σημαίνει ότι δείχνει στην τελευταία θέση και είναι full public static boolean isFull(String[][] arr) { return pivot == arr.length - 1; } /* * Service layer */ public static String[] getOneContactService(String phoneNumber) { try { String[] contact = getContactByPhoneNumber(phoneNumber); if (contact.length == 0) { throw new IllegalArgumentException("Contact not found"); } return contact; }catch (IllegalArgumentException e) { log(e); throw e; } } public static String[][] getAllContactsServices() { try { String[][] contactsList = getAllContacts(); if (contactsList.length == 0) { throw new IllegalArgumentException("List is empty"); } return contactsList; } catch (IllegalArgumentException e) { log(e); throw e; } } public static void insertContactServices(String firstname, String lastname, String phoneNumber){ try { if (!(insert(firstname,lastname,phoneNumber))) { throw new IllegalArgumentException("Error in insert"); } } catch (IllegalArgumentException e) { log(e); throw e; } } public static void updateContactServices(String oldPhoneNumber, String firstname, String lastname, String newPhoneNumber) { try { if (!(update(oldPhoneNumber, firstname, lastname, newPhoneNumber))) { throw new IllegalArgumentException("Error in update"); } } catch (IllegalArgumentException e) { log(e); throw e; } } public static String[] deleteContactServices(String phoneNumber) { String[] contact; try { contact = delete(phoneNumber); if (contact.length == 0) { throw new IllegalArgumentException("Error in delete"); } return contact; } catch (IllegalArgumentException e) { log(e); throw e; } } /* * Custom logger * ... varargs */ public static void log(Exception e, String... message) { try(PrintStream ps = new PrintStream(new FileOutputStream(path.toFile(), true))) { ps.println(LocalDateTime.now() + "\n" + e.toString()); ps.printf("%s", (message.length == 1) ? message[0] : ""); } catch (FileNotFoundException ex) { ex.printStackTrace(); } } }
KONSTANTINOS-EL/MobileContact
MobileContactsApp.java
2,789
// όταν ο pivot δείχνει στην arr.length - 1 αυτό σημαίνει ότι δείχνει στην τελευταία θέση και είναι full
line_comment
el
package gr.aueb.cf.c1.ch10; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.nio.file.Path; import java.nio.file.Paths; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.Arrays; import java.util.Scanner; public class MobileContactsApp { final static String[][] contacts = new String[500][3]; static int pivot = -1; final static Path path = Paths.get("C:/tmp/log-mobile.txt"); static Scanner in = new Scanner(System.in); public static void main(String[] args) { boolean quit = false; String s; int choice; String phoneNumber; do { printMenu(); s = getChoice(); if (s.matches("[qQ]")) quit = true; else { try { choice = Integer.parseInt(s); if (!(isValid(choice))) { throw new IllegalArgumentException("Error - Choice"); } switch (choice) { case 1: printContactMenu(); insertController(getFirstname(), getLastname(), getPhoneNumber()); System.out.println("Επιτυχής Εισαγωγή"); break; case 2: phoneNumber = getPhoneNumber(); deleteController(phoneNumber); System.out.println("Επιτυχής Διαγραφή"); break; case 3: phoneNumber = getPhoneNumber(); printContactMenu(); updateController(phoneNumber, getFirstname(), getLastname(), getPhoneNumber()); System.out.println("Επιτυχής Ενημέρωση"); break; case 4: phoneNumber = getPhoneNumber(); String[] contact = getOneController(phoneNumber); printContact(contact); break; case 5: String[][] allContacts = getAllController(); printAllContacts(allContacts); break; default: throw new IllegalArgumentException("Bad choice"); } } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } } }while (!quit); } public static void printContact(String[] contact) { for (String s : contact) { System.out.print(s + " "); } } public static void printAllContacts(String[][] contacts) { for (String[] contact : contacts) { printContact(contact); } } public static boolean isValid(int choice) { return ((choice >= 1) && (choice <= 5)); } public static void printMenu() { System.out.println("Επιλέξτε ένα από τα παρακάτω"); System.out.println("1. Εισαγωγή επαφής"); System.out.println("2. Διαγραφή επαφής"); System.out.println("3. Ενημέρωση επαφής"); System.out.println("4. Αναζήτηση επαφής"); System.out.println("5. Εκτύπωση επαφής"); System.out.println("Q. Έξοδος επαφής"); } public static String getChoice() { System.out.println("Εισάγετε επιλογή"); return in.nextLine().trim(); } public static void printContactMenu() { System.out.println("Εισάγετε όνομα, επώνυμο, τηλέφωνο"); } public static String getFirstname(){ System.out.println("Εισάγετε όνομα"); return in.nextLine().trim(); } public static String getLastname(){ System.out.println("Εισάγετε επώνυμο"); return in.nextLine().trim(); } public static String getPhoneNumber(){ System.out.println("Εισάγετε τηλέφωνο"); return in.nextLine().trim(); } public static void insertController(String firstname, String lastname, String phoneNumber) { try { //validation if (firstname == null || lastname == null || phoneNumber == null){ throw new IllegalArgumentException("Null are not allowed"); } if (firstname.length() < 2 || firstname.length() > 50) { throw new IllegalArgumentException("Firstname is not valid"); } if (lastname.length() < 2 || lastname.length() > 50) { throw new IllegalArgumentException("Last name is not valid"); } if (phoneNumber.length() < 2 || phoneNumber.length() > 12) { throw new IllegalArgumentException("Phone number is not valid"); } //call services insertContactServices(firstname.trim(), lastname.trim(), phoneNumber.trim()); } catch (IllegalArgumentException e) { e.printStackTrace(); throw e; } } public static void updateController(String oldPhoneNumber, String firstname, String lastname, String newPhoneNumber) { try { //validation if (oldPhoneNumber == null || firstname == null || lastname == null || newPhoneNumber == null){ throw new IllegalArgumentException("Null are not allowed"); } if (oldPhoneNumber.length() < 2 || oldPhoneNumber.length() > 50) { throw new IllegalArgumentException("Old number is not valid"); } if (firstname.length() < 2 || firstname.length() > 50) { throw new IllegalArgumentException("First name is not valid"); } if (lastname.length() < 2 || lastname.length() > 50) { throw new IllegalArgumentException("Last number is not valid"); } if (newPhoneNumber.length() < 2 || newPhoneNumber.length() > 12) { throw new IllegalArgumentException("New phone number is not valid"); } //call services updateContactServices(oldPhoneNumber.trim(), firstname.trim(), lastname.trim(), newPhoneNumber.trim()); } catch (IllegalArgumentException e) { e.printStackTrace(); throw e; } } public static String[] deleteController(String phoneNumber) { try { if (phoneNumber.length() < 2 || phoneNumber.length() > 12) { throw new IllegalArgumentException("Phone number is not valid"); } return deleteController(phoneNumber); }catch (IllegalArgumentException e) { e.printStackTrace(); throw e; } } public static String[] getOneController(String phoneNumber) { try { if (phoneNumber.length() < 2 || phoneNumber.length() > 12) { throw new IllegalArgumentException("Phone number is not valid"); } return getOneController(phoneNumber); }catch (IllegalArgumentException e) { e.printStackTrace(); throw e; } } public static String[][] getAllController() { try { return getAllContactsServices(); } catch (IllegalArgumentException e) { e.printStackTrace(); throw e; } } /* CRUD services that are provided to Services Layer */ public static int getIndexByPhone(String phoneNumber) { for (int i = 0; i <= pivot; i++) { if (contacts[i][2].equals(phoneNumber)) { return i; } } return -1; // if not found } public static boolean insert(String firstname, String lastname, String phoneNumber) { boolean inserted = false; if(isFull(contacts)) { return false; } if (getIndexByPhone(phoneNumber) != -1) { return false; } pivot++; contacts[pivot][0] = firstname; contacts[pivot][1] = lastname; contacts[pivot][2] = phoneNumber; return true; } public static boolean update(String oldPhoneNumber, String firstname, String lastname, String newPhoneNumber) { int positionToUpdate = getIndexByPhone(oldPhoneNumber); String[] contact = new String[3]; if (positionToUpdate == -1) { return false; // return new String[] {}; } // contact[0] = contacts[positionToUpdate][0]; // contact[1] = contacts[positionToUpdate][1]; // contact[2] = contacts[positionToUpdate][2]; contacts[positionToUpdate][0] = firstname; contacts[positionToUpdate][1] = lastname; contacts[positionToUpdate][2] = newPhoneNumber; return true; } public static String[] delete(String phoneNumber) { int positionToDelete = getIndexByPhone(phoneNumber); String[] contact = new String[3]; if (positionToDelete == -1) { return new String[] {}; } System.arraycopy(contacts[positionToDelete], 0, contact, 0, contact.length); if (!(positionToDelete == contacts.length - 1)) { System.arraycopy(contacts, positionToDelete + 1, contacts, positionToDelete, pivot - positionToDelete); } pivot--; return contact; } public static String[] getContactByPhoneNumber(String phoneNumber) { int positionToReturn = getIndexByPhone(phoneNumber); if (positionToReturn == -1) { return new String[] {}; } return contacts[positionToReturn]; } public static String[][] getAllContacts() { return Arrays.copyOf(contacts, pivot + 1); } // όταν ο<SUF> public static boolean isFull(String[][] arr) { return pivot == arr.length - 1; } /* * Service layer */ public static String[] getOneContactService(String phoneNumber) { try { String[] contact = getContactByPhoneNumber(phoneNumber); if (contact.length == 0) { throw new IllegalArgumentException("Contact not found"); } return contact; }catch (IllegalArgumentException e) { log(e); throw e; } } public static String[][] getAllContactsServices() { try { String[][] contactsList = getAllContacts(); if (contactsList.length == 0) { throw new IllegalArgumentException("List is empty"); } return contactsList; } catch (IllegalArgumentException e) { log(e); throw e; } } public static void insertContactServices(String firstname, String lastname, String phoneNumber){ try { if (!(insert(firstname,lastname,phoneNumber))) { throw new IllegalArgumentException("Error in insert"); } } catch (IllegalArgumentException e) { log(e); throw e; } } public static void updateContactServices(String oldPhoneNumber, String firstname, String lastname, String newPhoneNumber) { try { if (!(update(oldPhoneNumber, firstname, lastname, newPhoneNumber))) { throw new IllegalArgumentException("Error in update"); } } catch (IllegalArgumentException e) { log(e); throw e; } } public static String[] deleteContactServices(String phoneNumber) { String[] contact; try { contact = delete(phoneNumber); if (contact.length == 0) { throw new IllegalArgumentException("Error in delete"); } return contact; } catch (IllegalArgumentException e) { log(e); throw e; } } /* * Custom logger * ... varargs */ public static void log(Exception e, String... message) { try(PrintStream ps = new PrintStream(new FileOutputStream(path.toFile(), true))) { ps.println(LocalDateTime.now() + "\n" + e.toString()); ps.printf("%s", (message.length == 1) ? message[0] : ""); } catch (FileNotFoundException ex) { ex.printStackTrace(); } } }
867_11
import java.io.IOException; import java.util.HashMap; import java.util.HashSet; /** * Αυτή η κλάση χειρίζεται τους χρήστες και τα δεδομένα τους, τόσο ατομικά, όσο και συνολικά */ public class User { /** * Η βάση στην οποία αποθηκεύονται τα δεδομένα όλων των χρηστών */ private static Database credDatabase; /** * Το ΜΟΝΑΔΙΚΟ αναγνωριστικό κάθε χρήστη */ private String userName; /** * Ο πίνακας με τα στοιχεία κάθε χρήστη */ private HashMap<String,String> credentials; //Basic Methods (Constructor and getters setters) //---------------------------------------------------------------------------------------------------------------------- /** * Δημιουργεί ένα νέο χρήστη, και αν ο χρήστης υπάρχει ήδη στη βάση, φορτίζει τα δεδομένα του * @param userName το Αναγνωριστικό του χρήστη */ public User(String userName) { this.userName=userName; this.credentials = new HashMap<>(); if (!checkUsernameAvailability(userName)) { this.loadCredentials(); } else { this.create(); } } /** * @return το αναγνωριστικό του χρήστη */ public String getUserName() { return userName; } /** * Αλλάζει την τιμή ενός δεδομένου του χρήστη * @param type ο τύπος του δεδομένου που θα αλλάξει * @param value η νέα τιμή του δεδομένου που θα αλλάξει * @return <p>false αν δεν υπήρχε ο τύπος δεδομένου στα credentials</p> * <p>true αν άλλαξε επιτυχώς</p> */ public boolean setCredential(String type,String value) { if(!credentials.keySet().contains(type)) { return false; } credentials.put(type,value); return true; } /** * Δημιουργεί ένα καινούργιο δεδομένο για το χρήστη * @param type ο τύπος του νέου δεδομένου * @param value η τιμή του νέου δεδομένου * @return <p>false αν υπήρχε ήδη ο τύπος δεδομένου στα credentials</p> * <p>true αν προστέθηκε επιτυχώς</p> */ public boolean addCredential(String type,String value) { if(credentials.keySet().contains(type)) { return false; } credentials.put(type,value); return true; } /** * @param type ο τύπος του δεδομένου που θέλουμε * @return η τιμή του δεδομένου που θέλουμε */ public String getCredential(String type) { return credentials.get(type); } /** * Διαγράφει ένα δεδομένο του χρήστη * @param type ο τύπος του δεδομένου που θα διαγραφεί * @return <p>false αν δεν υπήρχε ο τύπος δεδομένου στα credentials</p> * <p>true αν διαγράφηκε επιτυχώς</p> */ public boolean deleteCredential(String type) { if(!credentials.keySet().contains(type)) { return false; } credentials.remove(type); return true; } /** * Μέθοδος ελέγχου για χρήση με δεδομένα των οποίων οι τιμές λειτουργούν σαν boolean (παίρνουν τιμες "yes" ή "no") * @param type ο τύπος δεδομένου που θέλουμε * @return <p>true η τιμή του δεδομένου είναι "yes"</p> * <p>false διαφορετικά</p> */ public boolean is(String type) { if(!has(type)) { return false; } if(getCredential(type).equals("yes")) { return true; } else { return false; } } /** * Μας λέει αν ένας χρήστης έχει έναν τύπο δεδομένου * @param type ο τύπος του δεδομένου * @return <p>true αν το δεδομένο υπάρχει για τον χρήστη</p> * <p>false αν δεν υπάρχει</p> */ public boolean has(String type) { return credentials.containsKey(type); } //Database Methods (communication between single object and Database) //---------------------------------------------------------------------------------------------------------------------- /** * Φορτίζει τα δεδομένα ενός χρήστη απο το credDataBase στο credentials */ private void loadCredentials() { int from = credDatabase.search(userName,SearchType.first); int to = credDatabase.search(userName,SearchType.last); for (int i = from; i <= to; i++) { credentials.put(credDatabase.get(1,i), credDatabase.get(2,i)); } } /** * Φορτίζει τις αλλαγές που έγιναν κατά την εκτέλεση του προγράμματος, στο εσωτερικό μέρος της credDatabase (το ArrayList) * ΠΡΟΣΟΧΗ: Πρέπει να καλείται πάντα όταν κάνει Logout ένας χρήστης */ public void updateCredentials() { int from = credDatabase.search(userName,SearchType.first); int to = credDatabase.search(userName,SearchType.last); for (int i = from; i <= to; i++) { credDatabase.remove(i); i--; to--; } for (String cType:credentials.keySet()) { credDatabase.add(userName,cType,credentials.get(cType)); } } //Holistic Methods (static methods that work with all rentals in the database) //---------------------------------------------------------------------------------------------------------------------- /** * Φορτίζει τις αλλαγές που έγιναν κατά την εκτέλεση του προγράμματος στο εξωτερικό μέρος του credDatabase (το αρχείο .txt) * ΠΡΟΣΟΧΗ: Πρέπει να καλείται πάντα στο τέλος του προγράμματος */ public static void updateDatabase(User user) throws IOException { user.updateCredentials(); credDatabase.update(); } /** * Δημιουργεί καινούργιο database με το όνομα που του δίνεται για τα credentials ΟΛΩΝ των χρηστών * (και αυτόματα φορτίζει και τα δεδομένα της) * ΠΡΟΣΟΧΗ: Πρέπει να καλείται στην αρχή κάθε προγράμματος * @param filename Το όνομα του φακέλου που θα εμπεριέχει το credDataBase */ public static void initializeDatabase(String filename) throws IOException { credDatabase = new Database(filename); } /** * Βλέπει αν υπάρχει χρήστης με αυτό το όνομα στη βάση δεδομένων * @param userName το όνομα προς έλεγχο * @return<p>true αν είναι διαθέσιμο το όνομα</p> * <p>false αν δεν είναι διαθέσιμο το όνομα</p> */ public static boolean checkUsernameAvailability(String userName) { if (credDatabase.search(userName) == -1) { return true; } else { return false; } } /** * Βλέπει αν υπάρχουν άλλοι χρήστες με το ίδιο credential * Για χρήση με δεδομένα που δεν μπορούν να είναι ίδια για διαφορετικούς χρήστες (πχ email) * @param type o τύπος του δεδομένου * @param value η τιμή του δεδομένου * @return <p>true αν είναι διαθέσιμο</p> * <p>false αν δεν είναι διαθέσιμο</p> */ public static boolean checkCredentialAvailability(String type, String value) { HashSet<String> userNames = credDatabase.getCategorySet(); for (String name:userNames) { if(credDatabase.search(name,type,value) != -1) { return false; } } return true; } /** * Μέθοδος αναζήτησης με κριτήριο κάποιο δεδομένο * @param type ο τύπος του δεδομένου * @param value η τιμή του δεδομένου * @return HashSet με τα usernames όλων των χρηστών που έχουν αυτά τα δεδομένα */ public static HashSet<String> findAllWith(String type,String value) { HashSet<String> usernames = credDatabase.getCategorySet(); HashSet<String> filteredNames = new HashSet<>(); for (String name:usernames) { User user = new User(name); if(user.has(type)) { if(user.getCredential(type).equals(value)) { filteredNames.add(user.getUserName()); } } } return filteredNames; } /** * Μέθοδος αναζήτησης που βρίσκει τον χρήστη που έχει ένα συγκεκριμένο δεδομένο * (Για χρήση ΜΟΝΟ με δεδομένα που είναι μοναδικά για κάθε χρήστη (πχ email)) * @param type ο τύπος του δεδομένου * @param value η τιμή του δεδομένου * @return το username του χρήστη που έχει το συγκεκριμένο δεδομένο */ public static String findWith(String type,String value) { HashSet<String> usernames = credDatabase.getCategorySet(); for (String name:usernames) { int search = credDatabase.search(name,type,value); if (search != -1) { return name; } } return "-1"; } /** * Εκτυπώνει όλη τη βάση δεδομένων στο terminal */ public static void showAll() { credDatabase.show(); } //Helper methods (Help with other methods and smaller stuff) //---------------------------------------------------------------------------------------------------------------------- /** * Αρχικοποιεί έναν χρήστη μέσα στη βάση δεδομένων <p> * (Είναι απαραίτητη η είσοδος ενός δεδομένου στο credDatabase όταν ένας χρήστης δεν υπάρχει ήδη μέσα της, * έτσι ώστε να λειτουργούν ομαλά οι άλλοι μέθοδοι. * Το τι θα βάλουμε δε μετράει) <p> * ΠΡΟΣΟΧΗ: Αυτή η μέθοδος πρέπει να καλείται κάθε φορά που δημιουργούμε νέο χρήστη (όχι αντικείμενο, αλλά χρήστη μέσα στο database) */ private void create() { credDatabase.add(userName,"initializer","nothing"); } /** * @return τα usernames όλων των χρηστών */ public static HashSet<String> getAll() { return credDatabase.getCategorySet(); } }
KonnosBaz/AUTh_CSD_Projects
Object Oriented Programming (2021)/src/User.java
4,111
/** * Μέθοδος ελέγχου για χρήση με δεδομένα των οποίων οι τιμές λειτουργούν σαν boolean (παίρνουν τιμες "yes" ή "no") * @param type ο τύπος δεδομένου που θέλουμε * @return <p>true η τιμή του δεδομένου είναι "yes"</p> * <p>false διαφορετικά</p> */
block_comment
el
import java.io.IOException; import java.util.HashMap; import java.util.HashSet; /** * Αυτή η κλάση χειρίζεται τους χρήστες και τα δεδομένα τους, τόσο ατομικά, όσο και συνολικά */ public class User { /** * Η βάση στην οποία αποθηκεύονται τα δεδομένα όλων των χρηστών */ private static Database credDatabase; /** * Το ΜΟΝΑΔΙΚΟ αναγνωριστικό κάθε χρήστη */ private String userName; /** * Ο πίνακας με τα στοιχεία κάθε χρήστη */ private HashMap<String,String> credentials; //Basic Methods (Constructor and getters setters) //---------------------------------------------------------------------------------------------------------------------- /** * Δημιουργεί ένα νέο χρήστη, και αν ο χρήστης υπάρχει ήδη στη βάση, φορτίζει τα δεδομένα του * @param userName το Αναγνωριστικό του χρήστη */ public User(String userName) { this.userName=userName; this.credentials = new HashMap<>(); if (!checkUsernameAvailability(userName)) { this.loadCredentials(); } else { this.create(); } } /** * @return το αναγνωριστικό του χρήστη */ public String getUserName() { return userName; } /** * Αλλάζει την τιμή ενός δεδομένου του χρήστη * @param type ο τύπος του δεδομένου που θα αλλάξει * @param value η νέα τιμή του δεδομένου που θα αλλάξει * @return <p>false αν δεν υπήρχε ο τύπος δεδομένου στα credentials</p> * <p>true αν άλλαξε επιτυχώς</p> */ public boolean setCredential(String type,String value) { if(!credentials.keySet().contains(type)) { return false; } credentials.put(type,value); return true; } /** * Δημιουργεί ένα καινούργιο δεδομένο για το χρήστη * @param type ο τύπος του νέου δεδομένου * @param value η τιμή του νέου δεδομένου * @return <p>false αν υπήρχε ήδη ο τύπος δεδομένου στα credentials</p> * <p>true αν προστέθηκε επιτυχώς</p> */ public boolean addCredential(String type,String value) { if(credentials.keySet().contains(type)) { return false; } credentials.put(type,value); return true; } /** * @param type ο τύπος του δεδομένου που θέλουμε * @return η τιμή του δεδομένου που θέλουμε */ public String getCredential(String type) { return credentials.get(type); } /** * Διαγράφει ένα δεδομένο του χρήστη * @param type ο τύπος του δεδομένου που θα διαγραφεί * @return <p>false αν δεν υπήρχε ο τύπος δεδομένου στα credentials</p> * <p>true αν διαγράφηκε επιτυχώς</p> */ public boolean deleteCredential(String type) { if(!credentials.keySet().contains(type)) { return false; } credentials.remove(type); return true; } /** * Μέθοδος ελέγχου για<SUF>*/ public boolean is(String type) { if(!has(type)) { return false; } if(getCredential(type).equals("yes")) { return true; } else { return false; } } /** * Μας λέει αν ένας χρήστης έχει έναν τύπο δεδομένου * @param type ο τύπος του δεδομένου * @return <p>true αν το δεδομένο υπάρχει για τον χρήστη</p> * <p>false αν δεν υπάρχει</p> */ public boolean has(String type) { return credentials.containsKey(type); } //Database Methods (communication between single object and Database) //---------------------------------------------------------------------------------------------------------------------- /** * Φορτίζει τα δεδομένα ενός χρήστη απο το credDataBase στο credentials */ private void loadCredentials() { int from = credDatabase.search(userName,SearchType.first); int to = credDatabase.search(userName,SearchType.last); for (int i = from; i <= to; i++) { credentials.put(credDatabase.get(1,i), credDatabase.get(2,i)); } } /** * Φορτίζει τις αλλαγές που έγιναν κατά την εκτέλεση του προγράμματος, στο εσωτερικό μέρος της credDatabase (το ArrayList) * ΠΡΟΣΟΧΗ: Πρέπει να καλείται πάντα όταν κάνει Logout ένας χρήστης */ public void updateCredentials() { int from = credDatabase.search(userName,SearchType.first); int to = credDatabase.search(userName,SearchType.last); for (int i = from; i <= to; i++) { credDatabase.remove(i); i--; to--; } for (String cType:credentials.keySet()) { credDatabase.add(userName,cType,credentials.get(cType)); } } //Holistic Methods (static methods that work with all rentals in the database) //---------------------------------------------------------------------------------------------------------------------- /** * Φορτίζει τις αλλαγές που έγιναν κατά την εκτέλεση του προγράμματος στο εξωτερικό μέρος του credDatabase (το αρχείο .txt) * ΠΡΟΣΟΧΗ: Πρέπει να καλείται πάντα στο τέλος του προγράμματος */ public static void updateDatabase(User user) throws IOException { user.updateCredentials(); credDatabase.update(); } /** * Δημιουργεί καινούργιο database με το όνομα που του δίνεται για τα credentials ΟΛΩΝ των χρηστών * (και αυτόματα φορτίζει και τα δεδομένα της) * ΠΡΟΣΟΧΗ: Πρέπει να καλείται στην αρχή κάθε προγράμματος * @param filename Το όνομα του φακέλου που θα εμπεριέχει το credDataBase */ public static void initializeDatabase(String filename) throws IOException { credDatabase = new Database(filename); } /** * Βλέπει αν υπάρχει χρήστης με αυτό το όνομα στη βάση δεδομένων * @param userName το όνομα προς έλεγχο * @return<p>true αν είναι διαθέσιμο το όνομα</p> * <p>false αν δεν είναι διαθέσιμο το όνομα</p> */ public static boolean checkUsernameAvailability(String userName) { if (credDatabase.search(userName) == -1) { return true; } else { return false; } } /** * Βλέπει αν υπάρχουν άλλοι χρήστες με το ίδιο credential * Για χρήση με δεδομένα που δεν μπορούν να είναι ίδια για διαφορετικούς χρήστες (πχ email) * @param type o τύπος του δεδομένου * @param value η τιμή του δεδομένου * @return <p>true αν είναι διαθέσιμο</p> * <p>false αν δεν είναι διαθέσιμο</p> */ public static boolean checkCredentialAvailability(String type, String value) { HashSet<String> userNames = credDatabase.getCategorySet(); for (String name:userNames) { if(credDatabase.search(name,type,value) != -1) { return false; } } return true; } /** * Μέθοδος αναζήτησης με κριτήριο κάποιο δεδομένο * @param type ο τύπος του δεδομένου * @param value η τιμή του δεδομένου * @return HashSet με τα usernames όλων των χρηστών που έχουν αυτά τα δεδομένα */ public static HashSet<String> findAllWith(String type,String value) { HashSet<String> usernames = credDatabase.getCategorySet(); HashSet<String> filteredNames = new HashSet<>(); for (String name:usernames) { User user = new User(name); if(user.has(type)) { if(user.getCredential(type).equals(value)) { filteredNames.add(user.getUserName()); } } } return filteredNames; } /** * Μέθοδος αναζήτησης που βρίσκει τον χρήστη που έχει ένα συγκεκριμένο δεδομένο * (Για χρήση ΜΟΝΟ με δεδομένα που είναι μοναδικά για κάθε χρήστη (πχ email)) * @param type ο τύπος του δεδομένου * @param value η τιμή του δεδομένου * @return το username του χρήστη που έχει το συγκεκριμένο δεδομένο */ public static String findWith(String type,String value) { HashSet<String> usernames = credDatabase.getCategorySet(); for (String name:usernames) { int search = credDatabase.search(name,type,value); if (search != -1) { return name; } } return "-1"; } /** * Εκτυπώνει όλη τη βάση δεδομένων στο terminal */ public static void showAll() { credDatabase.show(); } //Helper methods (Help with other methods and smaller stuff) //---------------------------------------------------------------------------------------------------------------------- /** * Αρχικοποιεί έναν χρήστη μέσα στη βάση δεδομένων <p> * (Είναι απαραίτητη η είσοδος ενός δεδομένου στο credDatabase όταν ένας χρήστης δεν υπάρχει ήδη μέσα της, * έτσι ώστε να λειτουργούν ομαλά οι άλλοι μέθοδοι. * Το τι θα βάλουμε δε μετράει) <p> * ΠΡΟΣΟΧΗ: Αυτή η μέθοδος πρέπει να καλείται κάθε φορά που δημιουργούμε νέο χρήστη (όχι αντικείμενο, αλλά χρήστη μέσα στο database) */ private void create() { credDatabase.add(userName,"initializer","nothing"); } /** * @return τα usernames όλων των χρηστών */ public static HashSet<String> getAll() { return credDatabase.getCategorySet(); } }
1175_15
package gr.aueb.cf.ch10miniprojects; import static java.lang.Math.max; /** * Finds the maximum sum subArray of a given Array. Popular algorithm called Kadane's algorithm. * It is based on the simple notion that , while using a for loop to examine the whole Array once * (in order to not increase the time complexity), because each next possible array we * examine has next number of the array added to it , we don't need to recalculate. We just examine * if the past max array , when having the next array element added to it . . . if it has bigger sum than the previous. * * @author kountouris panagiotis */ public class MaximumSumSubArray { public static void main(String[] args) { int[] arr = {-2, 1, -3, 4, -1, 2, 1}; printSeparator(); System.out.println("The expanded solution for the Max Sum Sub Array gives us: " + myLargeSumSubArraySolution(arr)); System.out.println("The short solution with the use of java.lang.math method we learned: " + myCompactSolution(arr)); printSeparator(); } public static int myLargeSumSubArraySolution(int[] arr) { //Κάνουμε initialize το γενικό μέγιστο στην ελάχιστη τιμή που η Java κλάση Integer μπορεί να μας δώσει // για να μην παρεμβληθεί στην πρώτη IF σύγκριση που θα βρούμε με το τοπικό μέγιστο. int myTotalFinalMaxSoFar = Integer.MIN_VALUE; // Τοπικό μέγιστο αρχικοποιούμε στο μηδέν αλλά στην πραγματικότητα στην πρώτη επανάληψη θα πάρει την τιμή // του πρώτου στοιχείου του Array. Η πρώτη επανάληψη δηλαδή θεωρεί ως τοπικό μέγιστό μόνο την πρώτη τιμή // του πίνακα. int myMaxEndingUntilHere = 0; //Μια for loop επανάληψης για να έχουμε γραμμική πολυπλοκότητα χρόνου. Να είναι γραμμικής μορφής δηλαδή //η αύξηση τον computations που χρειάζεται να γίνουν (όχι ο χρόνος) εάν αυξηθεί το μέγεθος του πίνακα. //Σε αυτή την περίπτωση εάν διπλασιαστεί το μέγεθος του πίνακα, θα διπλασιαστεί και ο αριθμός των υπολογισμών // που πρέπει να κάνει ο υπολογιστής για να κάνει τους υπολογισμούς. Γραμμική σχέση της μορφής y = ax for (int i = 0; i < arr.length; i++) { //Στο πρώτο loop θα πάρει την τιμή του πρώτου στοιχείου του πίνακα, από το δεύτερο και μετά // προσθέτει το κάθε στοιχείο του πίνακα. myMaxEndingUntilHere = myMaxEndingUntilHere + arr[i]; //Επειδή σε όλα τα πιθανά sub array μέχρι εδώ, προστίθεται το καινούριο arr[i], αρκεί να //κάνουμε τη σύγκριση να δούμε εάν με την πρόσθεση αυτού του στοιχείου, το καινούριο υπό εξέταση // array θα είναι το καινούριο max sum subArray. Δηλαδή εάν θα συμπεριλαμβάνετε και //αυτό το στοιχείο στο max sum subArray. if (myTotalFinalMaxSoFar < myMaxEndingUntilHere) //Εαν είναι μεγαλύτερο τότε αυτό παίρνει τη θέση του υποθετικού max. Μπορεί να αλλάξει πάλι // εάν π.χ. το επόμενο στοιχείο arr[i] δημιουργεί μεγαλύτερο sum sub Array μέχρι να φτάσουμε στο τέλος // του array που εξετάζουμε. myTotalFinalMaxSoFar = myMaxEndingUntilHere; // Εδώ εάν το subArray μέχρι το σημείο ελέγχου είναι μικρότερο από το μηδέν, το θέτουμε με μηδέν. // Εδώ παρουσιάζετε και το πρόβλημα με αυτήν μεθοδολογία για τον αλγόριθμο του Kadane. // Μόνο πρόβλημα εδώ, εάν υπάρξουν αρκετοί αρνητικοί αριθμοί έτσι ώστε το άθροισμα του // sub-array να είναι αρνητικός αριθμός. // Εάν υπάρχουν μόνο αρνητικοί αριθμοί θα επιστρέψει απλά όλο το array ! :-D if (myMaxEndingUntilHere < 0) myMaxEndingUntilHere = 0; } return myTotalFinalMaxSoFar; } /** * Alternative way with the use of the Math method that java.lang provides us. * @param arr The given Array * @return The max sum sub array */ public static int myCompactSolution(int[] arr){ int myMaxEndingUntilHere = Integer.MIN_VALUE; //Με τη βοήθεια του java.lang.math που μάθαμε for (int i = 0; i < arr.length; i++) { myMaxEndingUntilHere = max((myMaxEndingUntilHere + arr[i]) , arr[i]); } return myMaxEndingUntilHere; } public static void printSeparator(){ System.out.println("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); } }
KountourisPanagiotis/aueb-mini-projects
MaximumSumSubArray.java
2,117
//Εαν είναι μεγαλύτερο τότε αυτό παίρνει τη θέση του υποθετικού max. Μπορεί να αλλάξει πάλι
line_comment
el
package gr.aueb.cf.ch10miniprojects; import static java.lang.Math.max; /** * Finds the maximum sum subArray of a given Array. Popular algorithm called Kadane's algorithm. * It is based on the simple notion that , while using a for loop to examine the whole Array once * (in order to not increase the time complexity), because each next possible array we * examine has next number of the array added to it , we don't need to recalculate. We just examine * if the past max array , when having the next array element added to it . . . if it has bigger sum than the previous. * * @author kountouris panagiotis */ public class MaximumSumSubArray { public static void main(String[] args) { int[] arr = {-2, 1, -3, 4, -1, 2, 1}; printSeparator(); System.out.println("The expanded solution for the Max Sum Sub Array gives us: " + myLargeSumSubArraySolution(arr)); System.out.println("The short solution with the use of java.lang.math method we learned: " + myCompactSolution(arr)); printSeparator(); } public static int myLargeSumSubArraySolution(int[] arr) { //Κάνουμε initialize το γενικό μέγιστο στην ελάχιστη τιμή που η Java κλάση Integer μπορεί να μας δώσει // για να μην παρεμβληθεί στην πρώτη IF σύγκριση που θα βρούμε με το τοπικό μέγιστο. int myTotalFinalMaxSoFar = Integer.MIN_VALUE; // Τοπικό μέγιστο αρχικοποιούμε στο μηδέν αλλά στην πραγματικότητα στην πρώτη επανάληψη θα πάρει την τιμή // του πρώτου στοιχείου του Array. Η πρώτη επανάληψη δηλαδή θεωρεί ως τοπικό μέγιστό μόνο την πρώτη τιμή // του πίνακα. int myMaxEndingUntilHere = 0; //Μια for loop επανάληψης για να έχουμε γραμμική πολυπλοκότητα χρόνου. Να είναι γραμμικής μορφής δηλαδή //η αύξηση τον computations που χρειάζεται να γίνουν (όχι ο χρόνος) εάν αυξηθεί το μέγεθος του πίνακα. //Σε αυτή την περίπτωση εάν διπλασιαστεί το μέγεθος του πίνακα, θα διπλασιαστεί και ο αριθμός των υπολογισμών // που πρέπει να κάνει ο υπολογιστής για να κάνει τους υπολογισμούς. Γραμμική σχέση της μορφής y = ax for (int i = 0; i < arr.length; i++) { //Στο πρώτο loop θα πάρει την τιμή του πρώτου στοιχείου του πίνακα, από το δεύτερο και μετά // προσθέτει το κάθε στοιχείο του πίνακα. myMaxEndingUntilHere = myMaxEndingUntilHere + arr[i]; //Επειδή σε όλα τα πιθανά sub array μέχρι εδώ, προστίθεται το καινούριο arr[i], αρκεί να //κάνουμε τη σύγκριση να δούμε εάν με την πρόσθεση αυτού του στοιχείου, το καινούριο υπό εξέταση // array θα είναι το καινούριο max sum subArray. Δηλαδή εάν θα συμπεριλαμβάνετε και //αυτό το στοιχείο στο max sum subArray. if (myTotalFinalMaxSoFar < myMaxEndingUntilHere) //Εαν είναι<SUF> // εάν π.χ. το επόμενο στοιχείο arr[i] δημιουργεί μεγαλύτερο sum sub Array μέχρι να φτάσουμε στο τέλος // του array που εξετάζουμε. myTotalFinalMaxSoFar = myMaxEndingUntilHere; // Εδώ εάν το subArray μέχρι το σημείο ελέγχου είναι μικρότερο από το μηδέν, το θέτουμε με μηδέν. // Εδώ παρουσιάζετε και το πρόβλημα με αυτήν μεθοδολογία για τον αλγόριθμο του Kadane. // Μόνο πρόβλημα εδώ, εάν υπάρξουν αρκετοί αρνητικοί αριθμοί έτσι ώστε το άθροισμα του // sub-array να είναι αρνητικός αριθμός. // Εάν υπάρχουν μόνο αρνητικοί αριθμοί θα επιστρέψει απλά όλο το array ! :-D if (myMaxEndingUntilHere < 0) myMaxEndingUntilHere = 0; } return myTotalFinalMaxSoFar; } /** * Alternative way with the use of the Math method that java.lang provides us. * @param arr The given Array * @return The max sum sub array */ public static int myCompactSolution(int[] arr){ int myMaxEndingUntilHere = Integer.MIN_VALUE; //Με τη βοήθεια του java.lang.math που μάθαμε for (int i = 0; i < arr.length; i++) { myMaxEndingUntilHere = max((myMaxEndingUntilHere + arr[i]) , arr[i]); } return myMaxEndingUntilHere; } public static void printSeparator(){ System.out.println("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); } }
2682_2
package gr.aueb.cf.unitconverter; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; /** * The MainActivity class represents the main activity of the Unit Converter application. * It allows the user to convert kilograms to pounds. * * @Author Kountouris Panagiotis */ public class MainActivity extends AppCompatActivity { private Button button1; private EditText inputET; private TextView outputTV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button1 = findViewById(R.id.button1); inputET = findViewById(R.id.inputET); outputTV = findViewById(R.id.outputTV); outputTV.setVisibility(View.INVISIBLE); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String kilograms = inputET.getText().toString().trim(); double pounds; String message = "Please enter a valid value"; final double KILOGRAMS_TO_POUNDS_RATIO = 2.20462; // Regular Expression για να σιγουρεψουμε πως ο χρήστης θα δώσει : // χαρακτήρες ψηφία από το 0 μέχρι το 9 , (+) μία η περισσότερες φορές // δεν μπορεί να δώσει αρνητικές τιμές διότι δεν έχουμε βάλει το (-) if(kilograms.isEmpty() || !kilograms.matches("[0-9.]+")) { Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show(); }else{ pounds = Double.parseDouble(kilograms) * KILOGRAMS_TO_POUNDS_RATIO; outputTV.setText(String.valueOf(pounds)); outputTV.setVisibility(View.VISIBLE); // Εμφανίζουμε το textView με το αποτέλεσμα } } }); } }
KountourisPanagiotis/unit-converter
app/src/main/java/gr/aueb/cf/unitconverter/MainActivity.java
619
// χαρακτήρες ψηφία από το 0 μέχρι το 9 , (+) μία η περισσότερες φορές
line_comment
el
package gr.aueb.cf.unitconverter; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; /** * The MainActivity class represents the main activity of the Unit Converter application. * It allows the user to convert kilograms to pounds. * * @Author Kountouris Panagiotis */ public class MainActivity extends AppCompatActivity { private Button button1; private EditText inputET; private TextView outputTV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button1 = findViewById(R.id.button1); inputET = findViewById(R.id.inputET); outputTV = findViewById(R.id.outputTV); outputTV.setVisibility(View.INVISIBLE); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String kilograms = inputET.getText().toString().trim(); double pounds; String message = "Please enter a valid value"; final double KILOGRAMS_TO_POUNDS_RATIO = 2.20462; // Regular Expression για να σιγουρεψουμε πως ο χρήστης θα δώσει : // χαρακτήρες ψηφία<SUF> // δεν μπορεί να δώσει αρνητικές τιμές διότι δεν έχουμε βάλει το (-) if(kilograms.isEmpty() || !kilograms.matches("[0-9.]+")) { Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show(); }else{ pounds = Double.parseDouble(kilograms) * KILOGRAMS_TO_POUNDS_RATIO; outputTV.setText(String.valueOf(pounds)); outputTV.setVisibility(View.VISIBLE); // Εμφανίζουμε το textView με το αποτέλεσμα } } }); } }
23974_3
package gr.aueb.cf.ch5; /** * Παραστάσεις floating point */ public class FloatingExpressionsApp { public static void main(String[] args) { int intNum = 10; double doubleNum = 0.1; float floatNum = 10.5F; double doubleNum2 = 250; float floatResult = 0.0F; double doubleResult = 0.0; //Αν υπάρχει ένας float μικρότερου μεγέθους οι //τύποι μετατρέπονται σε float. floatResult = floatNum + intNum; //Αν υπάρχει έστω και ένας double, τα intNum // και floatNum μετατρέπονται σε double doubleResult = doubleNum + floatNum + intNum; System.out.printf("FloatResult = %f\n", floatResult); System.out.printf("DoubleResult = %f%n", doubleResult); } }
KruglovaOlga/CodingFactoryJava
src/gr/aueb/cf/ch5/FloatingExpressionsApp.java
292
//Αν υπάρχει έστω και ένας double, τα intNum
line_comment
el
package gr.aueb.cf.ch5; /** * Παραστάσεις floating point */ public class FloatingExpressionsApp { public static void main(String[] args) { int intNum = 10; double doubleNum = 0.1; float floatNum = 10.5F; double doubleNum2 = 250; float floatResult = 0.0F; double doubleResult = 0.0; //Αν υπάρχει ένας float μικρότερου μεγέθους οι //τύποι μετατρέπονται σε float. floatResult = floatNum + intNum; //Αν υπάρχει<SUF> // και floatNum μετατρέπονται σε double doubleResult = doubleNum + floatNum + intNum; System.out.printf("FloatResult = %f\n", floatResult); System.out.printf("DoubleResult = %f%n", doubleResult); } }
6782_9
package com.example.physiohut.R3; import android.content.DialogInterface; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.Fragment; import androidx.navigation.Navigation; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.physiohut.AuthenticateUser; import com.example.physiohut.NetworkConstants; import com.example.physiohut.R; import com.google.android.material.bottomnavigation.BottomNavigationView; /** * A simple {@link Fragment} subclass. * Use the {@link R3Fragment#newInstance} factory method to * create an instance of this fragment. */ public class R3Fragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; public R3Fragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment R3Fragment. */ // TODO: Rename and change types and number of parameters public static R3Fragment newInstance(String param1, String param2) { R3Fragment fragment = new R3Fragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_r3, container, false); } private int doc_id= AuthenticateUser.doctorID; @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); BottomNavigationView bottomNavigationView = getActivity().findViewById(R.id.bottomNavigationView); bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.back: case R.id.home: Navigation.findNavController(view).navigate(R.id.action_r3Fragment_to_doctorFragment); break; } return false; } }); //code_Eleni Button buttonSubmission = getActivity().findViewById(R.id.button_submition); buttonSubmission.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { boolean validationFailed =false; EditText editTextName = getActivity().findViewById(R.id.editText_name); String name = String.valueOf(editTextName.getText()); if (name.isEmpty()) { editTextName.requestFocus(); editTextName.setError("Το πεδίο Όνομαεπωνύμο είναι κενό!"); validationFailed = true; } else if (name.length() <= 8) { editTextName.requestFocus(); editTextName.setError("Το πεδίο Όνομαεπωνύμο έχει λάθος δεδομένα!"); validationFailed = true; } EditText editTextAddress = getActivity().findViewById(R.id.editText_address); String address = String.valueOf(editTextAddress.getText()); if (address.isEmpty()) { editTextAddress.requestFocus(); editTextAddress.setError("Το πεδίο Διεύθυνση είναι κενό!"); validationFailed= true; } else if (address.length() <=4 ) { editTextAddress.requestFocus(); editTextAddress.setError("Το πεδίο Διεύθυνση έχει λάθος δεδομένα!"); validationFailed = true; } EditText editTextAmka = getActivity().findViewById(R.id.editText_amka); String amka = String.valueOf(editTextAmka.getText()); if (amka.isEmpty()) { editTextAmka.requestFocus(); editTextAmka.setError("Το πεδίο AMKA είναι κενό!"); validationFailed = true; } else if(amka.length()!=11) { editTextAmka.requestFocus(); editTextAmka.setError("Το πεδίο AMKA έχει λάθος δεδομένα!"); validationFailed=true; } editTextAmka.setText(" "); editTextAddress.setText(" "); editTextName.setText(" "); if (!validationFailed) //pop up message { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setCancelable(true); builder.setTitle("Επιβεβαίωση ασθενή"); builder.setMessage("Όνομα:{" + name + "}\n" + "Δίευθυνση:{" + address + "}\n" + "ΑΜΚΑ:{" + amka + "}"); builder.setNegativeButton("Ακύρωση", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast myToast = Toast.makeText(getActivity(), "H υποβολή ασθενή ακυρώθηκε!", Toast.LENGTH_SHORT); myToast.show(); Navigation.findNavController(view).navigate(R.id.action_r3Fragment_to_doctorFragment); dialogInterface.cancel(); } }); builder.setPositiveButton("Υποβολή", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast myToast = Toast.makeText(getActivity(), "H υποβολή ασθενή έγινε!", Toast.LENGTH_SHORT); myToast.show(); //Navigation.findNavController(view).navigate(R.id.action_r3Fragment_to_doctorFragment); //εδω θα γίνει η αποστολή των δεδομένων στην ΒΔ String url = NetworkConstants.getUrlOfFile("r3.php") + "?doc_id="+doc_id+"&NAME="+name+"&address="+address +"&amka="+amka; try{ R3DataFetcher r1DataLog = new R3DataFetcher(); System.out.println(url); r1DataLog.physioLog(url); Toast.makeText(getContext(),"NAME: "+name +" Address: "+address+" Amka: "+amka,Toast.LENGTH_SHORT).show(); }catch (Exception e){ e.printStackTrace(); } } }); builder.show(); } else if (validationFailed) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setCancelable(true); builder.setTitle("Επιβεβαίωση ασθενή"); builder.setMessage("Απαιτείται διόρθωση δεδομένων παρακαλώ επαναλάβεται την διαδικάσια από την αρχή!"); builder.setNegativeButton("Ακύρωση", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast myToast = Toast.makeText(getActivity(), "H υποβολή ασθενή ακυρώθηκε!", Toast.LENGTH_SHORT); myToast.show(); Navigation.findNavController(view).navigate(R.id.action_r3Fragment_to_doctorFragment); dialogInterface.cancel(); } }); builder.show(); } } }); } }
Lab-eurs/physiohut-code
app/src/main/java/com/example/physiohut/R3/R3Fragment.java
2,151
//εδω θα γίνει η αποστολή των δεδομένων στην ΒΔ
line_comment
el
package com.example.physiohut.R3; import android.content.DialogInterface; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.Fragment; import androidx.navigation.Navigation; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.physiohut.AuthenticateUser; import com.example.physiohut.NetworkConstants; import com.example.physiohut.R; import com.google.android.material.bottomnavigation.BottomNavigationView; /** * A simple {@link Fragment} subclass. * Use the {@link R3Fragment#newInstance} factory method to * create an instance of this fragment. */ public class R3Fragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; public R3Fragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment R3Fragment. */ // TODO: Rename and change types and number of parameters public static R3Fragment newInstance(String param1, String param2) { R3Fragment fragment = new R3Fragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_r3, container, false); } private int doc_id= AuthenticateUser.doctorID; @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); BottomNavigationView bottomNavigationView = getActivity().findViewById(R.id.bottomNavigationView); bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.back: case R.id.home: Navigation.findNavController(view).navigate(R.id.action_r3Fragment_to_doctorFragment); break; } return false; } }); //code_Eleni Button buttonSubmission = getActivity().findViewById(R.id.button_submition); buttonSubmission.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { boolean validationFailed =false; EditText editTextName = getActivity().findViewById(R.id.editText_name); String name = String.valueOf(editTextName.getText()); if (name.isEmpty()) { editTextName.requestFocus(); editTextName.setError("Το πεδίο Όνομαεπωνύμο είναι κενό!"); validationFailed = true; } else if (name.length() <= 8) { editTextName.requestFocus(); editTextName.setError("Το πεδίο Όνομαεπωνύμο έχει λάθος δεδομένα!"); validationFailed = true; } EditText editTextAddress = getActivity().findViewById(R.id.editText_address); String address = String.valueOf(editTextAddress.getText()); if (address.isEmpty()) { editTextAddress.requestFocus(); editTextAddress.setError("Το πεδίο Διεύθυνση είναι κενό!"); validationFailed= true; } else if (address.length() <=4 ) { editTextAddress.requestFocus(); editTextAddress.setError("Το πεδίο Διεύθυνση έχει λάθος δεδομένα!"); validationFailed = true; } EditText editTextAmka = getActivity().findViewById(R.id.editText_amka); String amka = String.valueOf(editTextAmka.getText()); if (amka.isEmpty()) { editTextAmka.requestFocus(); editTextAmka.setError("Το πεδίο AMKA είναι κενό!"); validationFailed = true; } else if(amka.length()!=11) { editTextAmka.requestFocus(); editTextAmka.setError("Το πεδίο AMKA έχει λάθος δεδομένα!"); validationFailed=true; } editTextAmka.setText(" "); editTextAddress.setText(" "); editTextName.setText(" "); if (!validationFailed) //pop up message { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setCancelable(true); builder.setTitle("Επιβεβαίωση ασθενή"); builder.setMessage("Όνομα:{" + name + "}\n" + "Δίευθυνση:{" + address + "}\n" + "ΑΜΚΑ:{" + amka + "}"); builder.setNegativeButton("Ακύρωση", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast myToast = Toast.makeText(getActivity(), "H υποβολή ασθενή ακυρώθηκε!", Toast.LENGTH_SHORT); myToast.show(); Navigation.findNavController(view).navigate(R.id.action_r3Fragment_to_doctorFragment); dialogInterface.cancel(); } }); builder.setPositiveButton("Υποβολή", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast myToast = Toast.makeText(getActivity(), "H υποβολή ασθενή έγινε!", Toast.LENGTH_SHORT); myToast.show(); //Navigation.findNavController(view).navigate(R.id.action_r3Fragment_to_doctorFragment); //εδω θα<SUF> String url = NetworkConstants.getUrlOfFile("r3.php") + "?doc_id="+doc_id+"&NAME="+name+"&address="+address +"&amka="+amka; try{ R3DataFetcher r1DataLog = new R3DataFetcher(); System.out.println(url); r1DataLog.physioLog(url); Toast.makeText(getContext(),"NAME: "+name +" Address: "+address+" Amka: "+amka,Toast.LENGTH_SHORT).show(); }catch (Exception e){ e.printStackTrace(); } } }); builder.show(); } else if (validationFailed) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setCancelable(true); builder.setTitle("Επιβεβαίωση ασθενή"); builder.setMessage("Απαιτείται διόρθωση δεδομένων παρακαλώ επαναλάβεται την διαδικάσια από την αρχή!"); builder.setNegativeButton("Ακύρωση", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast myToast = Toast.makeText(getActivity(), "H υποβολή ασθενή ακυρώθηκε!", Toast.LENGTH_SHORT); myToast.show(); Navigation.findNavController(view).navigate(R.id.action_r3Fragment_to_doctorFragment); dialogInterface.cancel(); } }); builder.show(); } } }); } }
1475_0
package com.evaluation.encryption; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; // μπορει να μπει ότι θέλουμε μεταξυ MD2, MD5, SHA-1, SHA-224, SHA-256, SHA-384, SHA-512 // public class Encryption { public static String getHash (String password) { try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(password.getBytes()); byte[] resultByteArray = messageDigest.digest(); StringBuilder sb = new StringBuilder(); for (byte b : resultByteArray) { sb.append(String.format("%02x", b)); } return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } }
Lefteris-Souflas/Java-Web-App-For-Military-Staff-Evaluation
application/Evaluation/src/main/java/com/evaluation/encryption/Encryption.java
216
// μπορει να μπει ότι θέλουμε μεταξυ MD2, MD5, SHA-1, SHA-224, SHA-256, SHA-384, SHA-512 //
line_comment
el
package com.evaluation.encryption; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; // μπορει να<SUF> public class Encryption { public static String getHash (String password) { try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(password.getBytes()); byte[] resultByteArray = messageDigest.digest(); StringBuilder sb = new StringBuilder(); for (byte b : resultByteArray) { sb.append(String.format("%02x", b)); } return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } }
11717_7
package bookstorePack; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class BookDao { // Συνδεόμαστε στην βάση δεδομένων books, με username "Vaggelis" και password "123456789". public static Connection getConnection(){ Connection conn = null; try { Class.forName("org.mariadb.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mariadb://localhost:3306/bookstore", "Vaggelis", "123456789"); } catch (ClassNotFoundException | SQLException ex) {} return conn; } // Λειτουργια 1. Παίρνουμε μια λίστα με όλα τα διαθέσιμα βιβλία. public static List<Book> getAvailableBooks(){ List<Book> list = new ArrayList<>(); Connection conn = BookDao.getConnection(); try { PreparedStatement ps = conn.prepareStatement("SELECT * FROM books WHERE AVAILABILITY > 0"); ResultSet rs=ps.executeQuery(); while(rs.next()){ Book book = new Book(); book.setId(rs.getInt(1)); book.setTitle(rs.getString(2)); book.setAuthor(rs.getString(3)); book.setPublisher(rs.getString(4)); book.setPages(rs.getInt(5)); book.setPubl_year(rs.getInt(6)); book.setGenre(rs.getString(7)); book.setAvailability(rs.getInt(8)); list.add(book); } conn.close(); } catch (SQLException ex) {} return list; } // Λειτουργία 2. Παίρνουμε ένα βιβλίο με ένα ID public static Book getBook(int id){ Book book = null; Connection conn = BookDao.getConnection(); try { PreparedStatement ps = conn.prepareStatement("SELECT * FROM books WHERE ID = ?"); ps.setInt(1, id); ResultSet rs=ps.executeQuery(); if(rs.next()){ book = new Book(); book.setId(rs.getInt(1)); book.setTitle(rs.getString(2)); book.setAuthor(rs.getString(3)); book.setPublisher(rs.getString(4)); book.setPages(rs.getInt(5)); book.setPubl_year(rs.getInt(6)); book.setGenre(rs.getString(7)); book.setAvailability(rs.getInt(8)); } conn.close(); } catch (SQLException ex) {} return book; } // Λειτουργίας 3. Παραγγελία ενός συγγράματος, x αντίτυπα. public static int orderBook(int id, int x){ Book book = BookDao.getBook(id); if((book == null) || (x <= 0)){ return 2; // Order Error } else if(x >= book.getAvailability()){ return 1; // Out of Stock } else{ Connection conn = BookDao.getConnection(); try { PreparedStatement ps = conn.prepareStatement("UPDATE books SET AVAILABILITY = AVAILABILITY - ? WHERE ID = ?;"); ps.setInt(1, x); ps.setInt(2, id); ps.executeQuery(); conn.close(); } catch (SQLException ex) {} return 0; // Succesfull Order } } // Λειτουργία 4. Καταχώρηση νέου συγγράματος. public static int addBook(Book newBook){ Connection conn = BookDao.getConnection(); try { PreparedStatement ps = conn.prepareStatement( "INSERT INTO books (TITLE, AUTHOR, PUBLISHER, PAGES, PUBL_YEAR, GENRE, AVAILABILITY) VALUES(?, ?, ?, ?, ?, ?, ?)"); ps.setString(1, newBook.getTitle()); ps.setString(2, newBook.getAuthor()); ps.setString(3, newBook.getPublisher()); ps.setInt(4, newBook.getPages()); ps.setInt(5, newBook.getPubl_year()); ps.setString(6, newBook.getGenre()); ps.setInt(7, newBook.getAvailability()); ps.executeQuery(); conn.close(); } catch (SQLException ex) { return 1; // Insert Error } return 0; // Insert Completed } // Λειτουργία 5. Ενημέρωση συγγράματος. public static int updateBook(Book updatedBook){ Book oldBook = BookDao.getBook(updatedBook.getId()); if(oldBook == null){ return 1; // Update Error } else{ Connection conn = BookDao.getConnection(); try { PreparedStatement ps = conn.prepareStatement( "UPDATE books SET TITLE = ?, AUTHOR = ?, PUBLISHER = ?, PAGES = ?, PUBL_YEAR = ?, GENRE = ?, AVAILABILITY = ? WHERE ID = ?"); ps.setString(1, updatedBook.getTitle()); ps.setString(2, updatedBook.getAuthor()); ps.setString(3, updatedBook.getPublisher()); ps.setInt(4, updatedBook.getPages()); ps.setInt(5, updatedBook.getPubl_year()); ps.setString(6, updatedBook.getGenre()); ps.setInt(7, updatedBook.getAvailability()); ps.setInt(8, updatedBook.getId()); ps.executeQuery(); conn.close(); } catch (SQLException ex) { return 2; // Update Error } return 0; // Update Completed } } // Λειτουργία 6. Διαγραφή συγγράματος. public static int deleteBook(int id){ Book book = BookDao.getBook(id); if(book == null){ return 1; // Delete Error }else{ Connection conn = BookDao.getConnection(); try { PreparedStatement ps = conn.prepareStatement( "DELETE FROM books WHERE ID = ?"); ps.setInt(1, id); ps.executeQuery(); conn.close(); } catch (SQLException ex) { return 1; // Delete Error } return 0; // Delete Completed } } }
Lefti97/UniversityWorks
Network Programming (JAVA)/Final Work/Bookstore/src/java/bookstorePack/BookDao.java
1,628
// Λειτουργία 5. Ενημέρωση συγγράματος.
line_comment
el
package bookstorePack; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class BookDao { // Συνδεόμαστε στην βάση δεδομένων books, με username "Vaggelis" και password "123456789". public static Connection getConnection(){ Connection conn = null; try { Class.forName("org.mariadb.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mariadb://localhost:3306/bookstore", "Vaggelis", "123456789"); } catch (ClassNotFoundException | SQLException ex) {} return conn; } // Λειτουργια 1. Παίρνουμε μια λίστα με όλα τα διαθέσιμα βιβλία. public static List<Book> getAvailableBooks(){ List<Book> list = new ArrayList<>(); Connection conn = BookDao.getConnection(); try { PreparedStatement ps = conn.prepareStatement("SELECT * FROM books WHERE AVAILABILITY > 0"); ResultSet rs=ps.executeQuery(); while(rs.next()){ Book book = new Book(); book.setId(rs.getInt(1)); book.setTitle(rs.getString(2)); book.setAuthor(rs.getString(3)); book.setPublisher(rs.getString(4)); book.setPages(rs.getInt(5)); book.setPubl_year(rs.getInt(6)); book.setGenre(rs.getString(7)); book.setAvailability(rs.getInt(8)); list.add(book); } conn.close(); } catch (SQLException ex) {} return list; } // Λειτουργία 2. Παίρνουμε ένα βιβλίο με ένα ID public static Book getBook(int id){ Book book = null; Connection conn = BookDao.getConnection(); try { PreparedStatement ps = conn.prepareStatement("SELECT * FROM books WHERE ID = ?"); ps.setInt(1, id); ResultSet rs=ps.executeQuery(); if(rs.next()){ book = new Book(); book.setId(rs.getInt(1)); book.setTitle(rs.getString(2)); book.setAuthor(rs.getString(3)); book.setPublisher(rs.getString(4)); book.setPages(rs.getInt(5)); book.setPubl_year(rs.getInt(6)); book.setGenre(rs.getString(7)); book.setAvailability(rs.getInt(8)); } conn.close(); } catch (SQLException ex) {} return book; } // Λειτουργίας 3. Παραγγελία ενός συγγράματος, x αντίτυπα. public static int orderBook(int id, int x){ Book book = BookDao.getBook(id); if((book == null) || (x <= 0)){ return 2; // Order Error } else if(x >= book.getAvailability()){ return 1; // Out of Stock } else{ Connection conn = BookDao.getConnection(); try { PreparedStatement ps = conn.prepareStatement("UPDATE books SET AVAILABILITY = AVAILABILITY - ? WHERE ID = ?;"); ps.setInt(1, x); ps.setInt(2, id); ps.executeQuery(); conn.close(); } catch (SQLException ex) {} return 0; // Succesfull Order } } // Λειτουργία 4. Καταχώρηση νέου συγγράματος. public static int addBook(Book newBook){ Connection conn = BookDao.getConnection(); try { PreparedStatement ps = conn.prepareStatement( "INSERT INTO books (TITLE, AUTHOR, PUBLISHER, PAGES, PUBL_YEAR, GENRE, AVAILABILITY) VALUES(?, ?, ?, ?, ?, ?, ?)"); ps.setString(1, newBook.getTitle()); ps.setString(2, newBook.getAuthor()); ps.setString(3, newBook.getPublisher()); ps.setInt(4, newBook.getPages()); ps.setInt(5, newBook.getPubl_year()); ps.setString(6, newBook.getGenre()); ps.setInt(7, newBook.getAvailability()); ps.executeQuery(); conn.close(); } catch (SQLException ex) { return 1; // Insert Error } return 0; // Insert Completed } // Λειτουργία 5.<SUF> public static int updateBook(Book updatedBook){ Book oldBook = BookDao.getBook(updatedBook.getId()); if(oldBook == null){ return 1; // Update Error } else{ Connection conn = BookDao.getConnection(); try { PreparedStatement ps = conn.prepareStatement( "UPDATE books SET TITLE = ?, AUTHOR = ?, PUBLISHER = ?, PAGES = ?, PUBL_YEAR = ?, GENRE = ?, AVAILABILITY = ? WHERE ID = ?"); ps.setString(1, updatedBook.getTitle()); ps.setString(2, updatedBook.getAuthor()); ps.setString(3, updatedBook.getPublisher()); ps.setInt(4, updatedBook.getPages()); ps.setInt(5, updatedBook.getPubl_year()); ps.setString(6, updatedBook.getGenre()); ps.setInt(7, updatedBook.getAvailability()); ps.setInt(8, updatedBook.getId()); ps.executeQuery(); conn.close(); } catch (SQLException ex) { return 2; // Update Error } return 0; // Update Completed } } // Λειτουργία 6. Διαγραφή συγγράματος. public static int deleteBook(int id){ Book book = BookDao.getBook(id); if(book == null){ return 1; // Delete Error }else{ Connection conn = BookDao.getConnection(); try { PreparedStatement ps = conn.prepareStatement( "DELETE FROM books WHERE ID = ?"); ps.setInt(1, id); ps.executeQuery(); conn.close(); } catch (SQLException ex) { return 1; // Delete Error } return 0; // Delete Completed } } }
290_5
import java.util.*; public class Board { /*ιδιοτητες του πλεγματος του παιχνιδιου μας * η γραμμες , η στηλες και ενας δισδιαστατος πινακας με μεγεθος γραμμες επι στηλες */ private int rows; private int colums; private char grid[][]; /*ο κατασκευαστης του πλεγματος εχει σαν ορισμα ενα αντικειμενο Scanner * επειδη καλει την μεθοδο που διαβαζει και αρχικοποιει τις γραμμες και τις στηλες * επισης καλει και την μεθοδο που αρχικοποιει τον πινακα μας */ public Board(Scanner scan) { read_rows_colums(scan); this.grid = new char[rows][colums]; makeboard(); } /*εχει σαν ορισμα ενα αντεικειμενο Scanner * διαβαζει και ελεγχει αν αν οι γραμμες και οι στηλες ειναι * μεγαλυτερες ή ισες του 4 και μικροτερες η ισες του 15 */ public void read_rows_colums(Scanner scan) { System.out.print("Please enter the number of rows:"); while (!scan.hasNextInt()) { scan.next(); System.out.println("wrong input enter an integer"); } this.rows = scan.nextInt(); while(rows<4 || rows>15) { System.out.println("The numbers of rows can be >= to 4 and <= 15"); while (!scan.hasNextInt()) { scan.next(); System.out.println("wrong input enter an integer"); } this.rows = scan.nextInt(); } System.out.print("Please enter the number of colums:"); while (!scan.hasNextInt()) { scan.next(); System.out.println("wrong input enter an integer"); } this.colums = scan.nextInt(); while(colums<4 || colums>15) { System.out.println("The numbers of colums can be >= to 4 and <= 15"); while (!scan.hasNextInt()) { scan.next(); System.out.println("wrong input enter an integer"); } this.colums = scan.nextInt(); } } //αρχικοποιει τον πινακα με παυλες που στο παιχνιδι μας σημαινει οτι ειναι κενος public void makeboard() { for(int i=0; i<rows; i++) { for(int j=0; j<colums; j++) { grid[i][j]='-'; } } } //εμφανιζει στην οθονη τον πινακα public void display() { //εμφανιση πινακα for(int i=0; i<rows; i++ ) { System.out.print("|"); for(int j=0; j<colums; j++) { if(colums > 10) { System.out.print(" " + grid[i][j]+" "); } else { System.out.print(grid[i][j]+" "); } } System.out.println("|"); } //εμφανιση παλας κατω απο τον πινακα if(colums > 10) { for(int i=0; i<(colums*2+2)*2; i++) { System.out.print("-"); } } else { for(int i=0; i<(colums*2+2); i++) { System.out.print("-"); } } System.out.println(); //εμφανιση αριθμου στηλης for(int i=1; i<=colums; i++) { if(i > 10 && i!=1) { System.out.print(" " + i + " " ); } else if(colums>10) { System.out.print(" " + i + " "); } else System.out.print(" " + i); } System.out.println(); } /*ελεγχοι αν η στηλη που επιλεχθηκε ειναι μεσα στα ορια * και αν δεν ειναι γεματη τοποθετη το chip του παιχτη */ public void putcoin(Player player,Scanner scan) { int column = scan.nextInt(); while(column>this.colums || column-1<0 ) { System.out.println("Out of boards bound Try again"); column=scan.nextInt(); } for(int i=rows-1; i>=0; i--) { if(grid[i][column-1]=='-') { grid[i][column-1]=player.getChip(); break; } //αν φτασαμε στη κορυφη της στηλης και δεν εχει γεμισει ο πινακας //προτρεπουμε τον παιχτη να επιλεξει αλλη στηλη αφου αυτη ειναι γεματη if(i==0 && !fullboard()) { System.out.println("The colum is full please try another colum"); //καλουμε ξανα την συναρτηση με τα ιδια ορισματα για να ξανα επιλεξει στηλη putcoin(player,scan); } } } //ελεχγος για το αν γεμισε ο πινακας public boolean fullboard() { int count=0; for(int i=0; i<rows; i++) { for(int j=0; j<colums; j++) { if(grid[i][j]!='-') { count++; } } } if(count==rows*colums) { return true; } else return false; } //ελεγχος για το αν υπαρχουν 4 ιδια συμβολα στην ιδια οριζοντια σειρα public boolean horizontally_connected(Player player) { int count=0; for(int i=0; i<rows; i++) { count=0; for(int j=0; j<colums; j++) { if(grid[i][j]==player.getChip()) { count++; } else { count=0; } if(count==4) { return true; } } } return false; } //ελεγχος αν υπαρχουν 4 ιδια συμβολα στην ιδια καθετη σειρα public boolean vertically_connected(Player player) { int count=0; for(int j=0; j<colums; j++) { count=0; for(int i=0; i<rows; i++) { if(grid[i][j]==player.getChip()) { count++; } else { count=0; } if(count==4) { return true; } } } return false; } // ελεγχος αν υπαρχουν 4 ιδια συμβολα διαγωνια public boolean diagonal_connected(Player player) { /*ελεγχοι αν υπαρχουν 4 ιδια συμβολα διαγωννια ξεκινοντας απο τα αριστερα κατω * προς τα δεξια πανω */ for(int i=3; i<rows; i++){ for(int j=0; j<colums-3; j++){ if (grid[i][j] == player.getChip() && grid[i-1][j+1] == player.getChip() && grid[i-2][j+2] == player.getChip() && grid[i-3][j+3] == player.getChip()){ return true; } } } /*ελεγχοι αν υπαρχνουν 4 ιδια συμβολα διαγωνια ξεκινοντας απο τα αριστερα πανω * προς τα δεξια κατω */ for(int i=0; i<rows-3; i++){ for(int j=0; j<colums-3; j++){ if (grid[i][j] == player.getChip() && grid[i+1][j+1] == player.getChip() && grid[i+2][j+2] == player.getChip() && grid[i+3][j+3] == player.getChip()){ return true; } } } return false; } //ελεγχει αν υπαρχει νικητης οριζοντια ,καθετα ή διαγωνια και επιστρεφει αληθης αν ισχυει public boolean is_winner(Player player) { return (horizontally_connected(player) || vertically_connected(player) || diagonal_connected(player) ); } public int getrows() { return rows; } public int getcolums() { return colums; } }
Leonardpepa/Connect4
src/Board.java
3,006
//εμφανιση παλας κατω απο τον πινακα
line_comment
el
import java.util.*; public class Board { /*ιδιοτητες του πλεγματος του παιχνιδιου μας * η γραμμες , η στηλες και ενας δισδιαστατος πινακας με μεγεθος γραμμες επι στηλες */ private int rows; private int colums; private char grid[][]; /*ο κατασκευαστης του πλεγματος εχει σαν ορισμα ενα αντικειμενο Scanner * επειδη καλει την μεθοδο που διαβαζει και αρχικοποιει τις γραμμες και τις στηλες * επισης καλει και την μεθοδο που αρχικοποιει τον πινακα μας */ public Board(Scanner scan) { read_rows_colums(scan); this.grid = new char[rows][colums]; makeboard(); } /*εχει σαν ορισμα ενα αντεικειμενο Scanner * διαβαζει και ελεγχει αν αν οι γραμμες και οι στηλες ειναι * μεγαλυτερες ή ισες του 4 και μικροτερες η ισες του 15 */ public void read_rows_colums(Scanner scan) { System.out.print("Please enter the number of rows:"); while (!scan.hasNextInt()) { scan.next(); System.out.println("wrong input enter an integer"); } this.rows = scan.nextInt(); while(rows<4 || rows>15) { System.out.println("The numbers of rows can be >= to 4 and <= 15"); while (!scan.hasNextInt()) { scan.next(); System.out.println("wrong input enter an integer"); } this.rows = scan.nextInt(); } System.out.print("Please enter the number of colums:"); while (!scan.hasNextInt()) { scan.next(); System.out.println("wrong input enter an integer"); } this.colums = scan.nextInt(); while(colums<4 || colums>15) { System.out.println("The numbers of colums can be >= to 4 and <= 15"); while (!scan.hasNextInt()) { scan.next(); System.out.println("wrong input enter an integer"); } this.colums = scan.nextInt(); } } //αρχικοποιει τον πινακα με παυλες που στο παιχνιδι μας σημαινει οτι ειναι κενος public void makeboard() { for(int i=0; i<rows; i++) { for(int j=0; j<colums; j++) { grid[i][j]='-'; } } } //εμφανιζει στην οθονη τον πινακα public void display() { //εμφανιση πινακα for(int i=0; i<rows; i++ ) { System.out.print("|"); for(int j=0; j<colums; j++) { if(colums > 10) { System.out.print(" " + grid[i][j]+" "); } else { System.out.print(grid[i][j]+" "); } } System.out.println("|"); } //εμφανιση παλας<SUF> if(colums > 10) { for(int i=0; i<(colums*2+2)*2; i++) { System.out.print("-"); } } else { for(int i=0; i<(colums*2+2); i++) { System.out.print("-"); } } System.out.println(); //εμφανιση αριθμου στηλης for(int i=1; i<=colums; i++) { if(i > 10 && i!=1) { System.out.print(" " + i + " " ); } else if(colums>10) { System.out.print(" " + i + " "); } else System.out.print(" " + i); } System.out.println(); } /*ελεγχοι αν η στηλη που επιλεχθηκε ειναι μεσα στα ορια * και αν δεν ειναι γεματη τοποθετη το chip του παιχτη */ public void putcoin(Player player,Scanner scan) { int column = scan.nextInt(); while(column>this.colums || column-1<0 ) { System.out.println("Out of boards bound Try again"); column=scan.nextInt(); } for(int i=rows-1; i>=0; i--) { if(grid[i][column-1]=='-') { grid[i][column-1]=player.getChip(); break; } //αν φτασαμε στη κορυφη της στηλης και δεν εχει γεμισει ο πινακας //προτρεπουμε τον παιχτη να επιλεξει αλλη στηλη αφου αυτη ειναι γεματη if(i==0 && !fullboard()) { System.out.println("The colum is full please try another colum"); //καλουμε ξανα την συναρτηση με τα ιδια ορισματα για να ξανα επιλεξει στηλη putcoin(player,scan); } } } //ελεχγος για το αν γεμισε ο πινακας public boolean fullboard() { int count=0; for(int i=0; i<rows; i++) { for(int j=0; j<colums; j++) { if(grid[i][j]!='-') { count++; } } } if(count==rows*colums) { return true; } else return false; } //ελεγχος για το αν υπαρχουν 4 ιδια συμβολα στην ιδια οριζοντια σειρα public boolean horizontally_connected(Player player) { int count=0; for(int i=0; i<rows; i++) { count=0; for(int j=0; j<colums; j++) { if(grid[i][j]==player.getChip()) { count++; } else { count=0; } if(count==4) { return true; } } } return false; } //ελεγχος αν υπαρχουν 4 ιδια συμβολα στην ιδια καθετη σειρα public boolean vertically_connected(Player player) { int count=0; for(int j=0; j<colums; j++) { count=0; for(int i=0; i<rows; i++) { if(grid[i][j]==player.getChip()) { count++; } else { count=0; } if(count==4) { return true; } } } return false; } // ελεγχος αν υπαρχουν 4 ιδια συμβολα διαγωνια public boolean diagonal_connected(Player player) { /*ελεγχοι αν υπαρχουν 4 ιδια συμβολα διαγωννια ξεκινοντας απο τα αριστερα κατω * προς τα δεξια πανω */ for(int i=3; i<rows; i++){ for(int j=0; j<colums-3; j++){ if (grid[i][j] == player.getChip() && grid[i-1][j+1] == player.getChip() && grid[i-2][j+2] == player.getChip() && grid[i-3][j+3] == player.getChip()){ return true; } } } /*ελεγχοι αν υπαρχνουν 4 ιδια συμβολα διαγωνια ξεκινοντας απο τα αριστερα πανω * προς τα δεξια κατω */ for(int i=0; i<rows-3; i++){ for(int j=0; j<colums-3; j++){ if (grid[i][j] == player.getChip() && grid[i+1][j+1] == player.getChip() && grid[i+2][j+2] == player.getChip() && grid[i+3][j+3] == player.getChip()){ return true; } } } return false; } //ελεγχει αν υπαρχει νικητης οριζοντια ,καθετα ή διαγωνια και επιστρεφει αληθης αν ισχυει public boolean is_winner(Player player) { return (horizontally_connected(player) || vertically_connected(player) || diagonal_connected(player) ); } public int getrows() { return rows; } public int getcolums() { return colums; } }
12_1
package order; import java.awt.Color; import java.util.Date; import java.util.Random; import gui.windows.CartWindow; import login.Login; import resources.TextResources; public class CouponFactory { static Random rand = new Random(); public static Coupon GenerateCoupon(String email) { String code = ""; // Βαλαμε στατικο για τεστ αλλα θα παιρνει ορισμα τον χρηστη και θα παιρνουμε // απο κει το μειλ for (int i = 0; i < 3; i++) { code += email.toCharArray()[rand.nextInt(email.length())]; } int randomNumber = rand.nextInt(9990 + 1 - 1000) + 1000; code += Integer.toString(randomNumber); return new Coupon(code.toUpperCase(), new Date()); } public static boolean isValid(String code) { Coupon couponProvided = searchCoupon(code); Date today = new Date(); try { // calculates the time that takes for a useer to use the coupon in milliseconds long mill = today.getTime() - couponProvided.getDate().getTime(); // converts the millseconds to days long days = (long) (mill / (1000 * 60 * 60 * 24)); if (days < 3) { Login.loggedCustomer.removeCoupon(couponProvided); CartWindow.couponField.setBackground(new Color(158, 232, 178)); CartWindow.couponField.setText(TextResources.submitted); return true; } } catch (NullPointerException e) { CartWindow.couponField.setBackground(new Color(232, 158, 158)); CartWindow.couponField.setText(TextResources.invalidCoupon); } return false; } public static Coupon searchCoupon(String code) { for (Coupon coupon : Login.loggedCustomer.getCoupons()) { if (coupon.getCode().equals(code)) { return coupon; } } return null; } }
Leonardpepa/Segaleo
src/order/CouponFactory.java
574
// απο κει το μειλ
line_comment
el
package order; import java.awt.Color; import java.util.Date; import java.util.Random; import gui.windows.CartWindow; import login.Login; import resources.TextResources; public class CouponFactory { static Random rand = new Random(); public static Coupon GenerateCoupon(String email) { String code = ""; // Βαλαμε στατικο για τεστ αλλα θα παιρνει ορισμα τον χρηστη και θα παιρνουμε // απο κει<SUF> for (int i = 0; i < 3; i++) { code += email.toCharArray()[rand.nextInt(email.length())]; } int randomNumber = rand.nextInt(9990 + 1 - 1000) + 1000; code += Integer.toString(randomNumber); return new Coupon(code.toUpperCase(), new Date()); } public static boolean isValid(String code) { Coupon couponProvided = searchCoupon(code); Date today = new Date(); try { // calculates the time that takes for a useer to use the coupon in milliseconds long mill = today.getTime() - couponProvided.getDate().getTime(); // converts the millseconds to days long days = (long) (mill / (1000 * 60 * 60 * 24)); if (days < 3) { Login.loggedCustomer.removeCoupon(couponProvided); CartWindow.couponField.setBackground(new Color(158, 232, 178)); CartWindow.couponField.setText(TextResources.submitted); return true; } } catch (NullPointerException e) { CartWindow.couponField.setBackground(new Color(232, 158, 158)); CartWindow.couponField.setText(TextResources.invalidCoupon); } return false; } public static Coupon searchCoupon(String code) { for (Coupon coupon : Login.loggedCustomer.getCoupons()) { if (coupon.getCode().equals(code)) { return coupon; } } return null; } }
621_6
package tillerino.tillerinobot.lang; import java.util.List; import java.util.Random; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import tillerino.tillerinobot.BeatmapMeta; import tillerino.tillerinobot.IRCBot.IRCBotUser; import tillerino.tillerinobot.RecommendationsManager.Recommendation; /** * @author Till https://github.com/nikosbks https://osu.ppy.sh/u/3619345 */ public class Greek implements Language { @Override public String unknownBeatmap() { return "Συγνώμη, δεν γνωρίζω αυτό το τραγούδι. Ίσως είναι αρκετά νεο, πολυ δύσκολο, μη εγκεκριμένο ή να μην είναι για το osu standard mode." ; } @Override public String internalException(String marker) { return "Εχ... μάλλον φαίνεται ότι ο ανθρώπινος Tillerino έκανε μαντάρα την σύνδεσή μου." +" Εάν δεν το παρατηρήσει σύντομα, μπορείς [https://github.com/Tillerino/Tillerinobot/wiki/Contact να τον ενημερώσεις]; (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Τί συμβαίνει; Παίρνω μονο παραλογίες από τον server του osu. Μπορείς να μου πείς τι σημαίνει αυτο; 0011101001010000" + " Ο ανθρώπινος Tillerino λέει ότι δεν υπάρχει κάτι για να ανησυχείς, και ότι πρέπει να ξαναπροσπαθήσουμε." + " Εάν ανησυχείς πάρα πολύ για κάποιο λογο, μπορείς να [https://github.com/Tillerino/Tillerinobot/wiki/Contact του το πείς]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Δεν υπάρχουν δεδομένα για τα ζητούμενα mods." ; } @Override public void welcomeUser(IRCBotUser user, OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { user.message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { user.message("Καλώς ήρθες πίσω," + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { user.message(apiUser.getUserName() + "..."); user.message("...είσαι εσύ αυτός; Πάει πολύς καιρός!"); user.message("Είναι ωραίο να σε έχουμε πίσω. Μπορώ να σε ενδιαφέρω με μια πρόταση;"); } else { String[] messages = { "Φαίνεσαι σαν να θες μια πρόταση.", "Πόσο ωραίο να σε βλέπω :)", "Ο αγαπημένος μου άνθρωπος. (Μην το πείς στούς άλλους!)", "Τι ευχάριστη έκπληξη! ^.^", "Περίμενα ότι θα εμφανιστείς. Όλοι οι άλλοι άνθρωποι ειναι μπούφοι, αλλα μην τους πείς ότι το ειπα! :3", "Τι έχεις την διάθεση να κάνεις σήμερα;", }; Random random = new Random(); String message = messages[random.nextInt(messages.length)]; user.message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Άγνωστη εντολή \"" + command + "\". Πληκτρολόγησε !help αν χρειάζεσαι βοήθεια!"; } @Override public String noInformationForMods() { return "Συγνώμη, δεν μπορώ να παρέχω πληροφορίες για αυτά τα mods αυτή τη στιγμή"; } @Override public String malformattedMods(String mods) { return "Αυτα τα mods δεν φαίνονται σωστά. Τα mods μπορεί να είναι ενας συνδυασμός από DT HR HD HT EZ NC FL SO NF.Συνδυάζοντάς τα χωρίς κενά ή ειδικούς χαρακτήρες. Παράδειγμα: !with HDHR, !with DTEZ"; } @Override public String noLastSongInfo() { return "Δεν θυμάμαι να πήρες καμία πληροφορία τραγουδιού..."; } @Override public String tryWithMods() { return "Δοκίμασε αυτό το τραγούδι με μερικά mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Δοκίμασε αυτό το τραγούδι με " + Mods.toShortNamesContinuous(mods); } /** * The user's IRC nick name could not be resolved to an osu user id. The * message should suggest to contact @Tillerinobot or /u/Tillerino. * * @param exceptionMarker * a marker to reference the created log entry. six or eight * characters. * @param name * the irc nick which could not be resolved * @return */ public String unresolvableName(String exceptionMarker, String name) { return "Το ονομά σου με μπερδεύει. Είσαι απαγορευμένος; Εάν όχι, παρακαλώ [https://github.com/Tillerino/Tillerinobot/wiki/Contact επικοινώνησε με τον Tillerino]. (reference " + exceptionMarker + ")"; } @Override public String excuseForError() { return "Συγνώμη, υπήρχε αυτή η όμορφη σειρά από άσσους και μηδενικά και παρασύρθηκα. Τί ήθελες ξανα;"; } @Override public String complaint() { return "Το παράπονό σου κατατέθηκε. Ο Tillerino θα το κοιτάξει όταν μπορέσει."; } @Override public void hug(final IRCBotUser user, OsuApiUser apiUser) { user.message("Έλα εδώ εσυ!"); user.action("Αγκαλιάζει " + apiUser.getUserName()); } @Override public String help() { return "Γειά! Είμαι το ρομπότ που σκότωσε τον Tillerino και πήρε τον λογαριασμό του. Πλάκα κάνω, αλλά όντως χρησιμοποιώ τον λογαριασμό αρκετά." + " [https://twitter.com/Tillerinobot status και updates]" + " - [https://github.com/Tillerino/Tillerinobot/wiki εντολές]" + " - [http://ppaddict.tillerino.org/ ppaddict]" + " - [https://github.com/Tillerino/Tillerinobot/wiki/Contact επικοινωνία]"; } @Override public String faq() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ Συχνά ερωτώμενες ερωτήσεις]"; } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Συγνώμη, σε αυτό το σημείο " + feature + "είναι μόνο διαθέσιμο για παίκτες που εχουν ξεπερασμένη τάξη " + minRank + "."; } @Override public String mixedNomodAndMods() { return "Τί εννοείς nomods με mods;"; } @Override public String outOfRecommendations() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do" + " Έχω προτίνει ό,τι μπορώ να σκεφτώ]. " + " Προσπάθησε άλλες επιλογές προτάσεων ή χρησιμοποίησε το !rest. Εάν δεν είσαι σίγουρος, έλεγξε το !help."; } @Override public String notRanked() { return "Απ' ότι φαίνεται αυτό το τραγούδι δεν είναι εγκεκριμένο."; } @Override public void optionalCommentOnNP(IRCBotUser user, OsuApiUser apiUser, BeatmapMeta meta) { // regular Tillerino doesn't comment on this } @Override public void optionalCommentOnWith(IRCBotUser user, OsuApiUser apiUser, BeatmapMeta meta) { // regular Tillerino doesn't comment on this } @Override public void optionalCommentOnRecommendation(IRCBotUser user, OsuApiUser apiUser, Recommendation meta) { // regular Tillerino doesn't comment on this } @Override public boolean isChanged() { return false; } @Override public void setChanged(boolean changed) { } @Override public String invalidAccuracy(String acc) { return "Άκυρη ακρίβεια: \"" + acc + "\""; } @Override public void optionalCommentOnLanguage(IRCBotUser user, OsuApiUser apiUser) { user.message("Ο N for Niko με βοήθησε να μάθω Ελληνικά"); } @Override public String invalidChoice(String invalid, String choices) { return "Συγνώμη, αλλά \"" + invalid + "\" δεν υπολογίζει. Προσπάθησε αυτά: " + choices + "!"; } @Override public String setFormat() { return "Η σύνταξη για να ρυθμιστεί η παράμετρος είναι !set ρύθμιση ποσού. Δοκίμασε !help εάν χρειάζεσαι περισσότερες υποδείξεις."; } @Override public String apiTimeoutException() { return new Default().apiTimeoutException(); } @Override public String noRecentPlays() { return new Default().noRecentPlays(); } @Override public String isSetId() { return new Default().isSetId(); } @Override public String getPatience() { return new Default().getPatience(); } }
Liby99/Tillerinobot
tillerinobot/src/main/java/tillerino/tillerinobot/lang/Greek.java
3,750
//github.com/Tillerino/Tillerinobot/wiki/FAQ Συχνά ερωτώμενες ερωτήσεις]";
line_comment
el
package tillerino.tillerinobot.lang; import java.util.List; import java.util.Random; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import tillerino.tillerinobot.BeatmapMeta; import tillerino.tillerinobot.IRCBot.IRCBotUser; import tillerino.tillerinobot.RecommendationsManager.Recommendation; /** * @author Till https://github.com/nikosbks https://osu.ppy.sh/u/3619345 */ public class Greek implements Language { @Override public String unknownBeatmap() { return "Συγνώμη, δεν γνωρίζω αυτό το τραγούδι. Ίσως είναι αρκετά νεο, πολυ δύσκολο, μη εγκεκριμένο ή να μην είναι για το osu standard mode." ; } @Override public String internalException(String marker) { return "Εχ... μάλλον φαίνεται ότι ο ανθρώπινος Tillerino έκανε μαντάρα την σύνδεσή μου." +" Εάν δεν το παρατηρήσει σύντομα, μπορείς [https://github.com/Tillerino/Tillerinobot/wiki/Contact να τον ενημερώσεις]; (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Τί συμβαίνει; Παίρνω μονο παραλογίες από τον server του osu. Μπορείς να μου πείς τι σημαίνει αυτο; 0011101001010000" + " Ο ανθρώπινος Tillerino λέει ότι δεν υπάρχει κάτι για να ανησυχείς, και ότι πρέπει να ξαναπροσπαθήσουμε." + " Εάν ανησυχείς πάρα πολύ για κάποιο λογο, μπορείς να [https://github.com/Tillerino/Tillerinobot/wiki/Contact του το πείς]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Δεν υπάρχουν δεδομένα για τα ζητούμενα mods." ; } @Override public void welcomeUser(IRCBotUser user, OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { user.message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { user.message("Καλώς ήρθες πίσω," + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { user.message(apiUser.getUserName() + "..."); user.message("...είσαι εσύ αυτός; Πάει πολύς καιρός!"); user.message("Είναι ωραίο να σε έχουμε πίσω. Μπορώ να σε ενδιαφέρω με μια πρόταση;"); } else { String[] messages = { "Φαίνεσαι σαν να θες μια πρόταση.", "Πόσο ωραίο να σε βλέπω :)", "Ο αγαπημένος μου άνθρωπος. (Μην το πείς στούς άλλους!)", "Τι ευχάριστη έκπληξη! ^.^", "Περίμενα ότι θα εμφανιστείς. Όλοι οι άλλοι άνθρωποι ειναι μπούφοι, αλλα μην τους πείς ότι το ειπα! :3", "Τι έχεις την διάθεση να κάνεις σήμερα;", }; Random random = new Random(); String message = messages[random.nextInt(messages.length)]; user.message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Άγνωστη εντολή \"" + command + "\". Πληκτρολόγησε !help αν χρειάζεσαι βοήθεια!"; } @Override public String noInformationForMods() { return "Συγνώμη, δεν μπορώ να παρέχω πληροφορίες για αυτά τα mods αυτή τη στιγμή"; } @Override public String malformattedMods(String mods) { return "Αυτα τα mods δεν φαίνονται σωστά. Τα mods μπορεί να είναι ενας συνδυασμός από DT HR HD HT EZ NC FL SO NF.Συνδυάζοντάς τα χωρίς κενά ή ειδικούς χαρακτήρες. Παράδειγμα: !with HDHR, !with DTEZ"; } @Override public String noLastSongInfo() { return "Δεν θυμάμαι να πήρες καμία πληροφορία τραγουδιού..."; } @Override public String tryWithMods() { return "Δοκίμασε αυτό το τραγούδι με μερικά mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Δοκίμασε αυτό το τραγούδι με " + Mods.toShortNamesContinuous(mods); } /** * The user's IRC nick name could not be resolved to an osu user id. The * message should suggest to contact @Tillerinobot or /u/Tillerino. * * @param exceptionMarker * a marker to reference the created log entry. six or eight * characters. * @param name * the irc nick which could not be resolved * @return */ public String unresolvableName(String exceptionMarker, String name) { return "Το ονομά σου με μπερδεύει. Είσαι απαγορευμένος; Εάν όχι, παρακαλώ [https://github.com/Tillerino/Tillerinobot/wiki/Contact επικοινώνησε με τον Tillerino]. (reference " + exceptionMarker + ")"; } @Override public String excuseForError() { return "Συγνώμη, υπήρχε αυτή η όμορφη σειρά από άσσους και μηδενικά και παρασύρθηκα. Τί ήθελες ξανα;"; } @Override public String complaint() { return "Το παράπονό σου κατατέθηκε. Ο Tillerino θα το κοιτάξει όταν μπορέσει."; } @Override public void hug(final IRCBotUser user, OsuApiUser apiUser) { user.message("Έλα εδώ εσυ!"); user.action("Αγκαλιάζει " + apiUser.getUserName()); } @Override public String help() { return "Γειά! Είμαι το ρομπότ που σκότωσε τον Tillerino και πήρε τον λογαριασμό του. Πλάκα κάνω, αλλά όντως χρησιμοποιώ τον λογαριασμό αρκετά." + " [https://twitter.com/Tillerinobot status και updates]" + " - [https://github.com/Tillerino/Tillerinobot/wiki εντολές]" + " - [http://ppaddict.tillerino.org/ ppaddict]" + " - [https://github.com/Tillerino/Tillerinobot/wiki/Contact επικοινωνία]"; } @Override public String faq() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ Συχνά<SUF> } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Συγνώμη, σε αυτό το σημείο " + feature + "είναι μόνο διαθέσιμο για παίκτες που εχουν ξεπερασμένη τάξη " + minRank + "."; } @Override public String mixedNomodAndMods() { return "Τί εννοείς nomods με mods;"; } @Override public String outOfRecommendations() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do" + " Έχω προτίνει ό,τι μπορώ να σκεφτώ]. " + " Προσπάθησε άλλες επιλογές προτάσεων ή χρησιμοποίησε το !rest. Εάν δεν είσαι σίγουρος, έλεγξε το !help."; } @Override public String notRanked() { return "Απ' ότι φαίνεται αυτό το τραγούδι δεν είναι εγκεκριμένο."; } @Override public void optionalCommentOnNP(IRCBotUser user, OsuApiUser apiUser, BeatmapMeta meta) { // regular Tillerino doesn't comment on this } @Override public void optionalCommentOnWith(IRCBotUser user, OsuApiUser apiUser, BeatmapMeta meta) { // regular Tillerino doesn't comment on this } @Override public void optionalCommentOnRecommendation(IRCBotUser user, OsuApiUser apiUser, Recommendation meta) { // regular Tillerino doesn't comment on this } @Override public boolean isChanged() { return false; } @Override public void setChanged(boolean changed) { } @Override public String invalidAccuracy(String acc) { return "Άκυρη ακρίβεια: \"" + acc + "\""; } @Override public void optionalCommentOnLanguage(IRCBotUser user, OsuApiUser apiUser) { user.message("Ο N for Niko με βοήθησε να μάθω Ελληνικά"); } @Override public String invalidChoice(String invalid, String choices) { return "Συγνώμη, αλλά \"" + invalid + "\" δεν υπολογίζει. Προσπάθησε αυτά: " + choices + "!"; } @Override public String setFormat() { return "Η σύνταξη για να ρυθμιστεί η παράμετρος είναι !set ρύθμιση ποσού. Δοκίμασε !help εάν χρειάζεσαι περισσότερες υποδείξεις."; } @Override public String apiTimeoutException() { return new Default().apiTimeoutException(); } @Override public String noRecentPlays() { return new Default().noRecentPlays(); } @Override public String isSetId() { return new Default().isSetId(); } @Override public String getPatience() { return new Default().getPatience(); } }
29430_3
import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.Locale; import java.util.ResourceBundle; public class DuidokuGUI { Duidoku logic; JFrame main; JPanel board; JPanel side; JButton[][] tiles; int display; JLabel label; JLabel label1; String player_name; private ResourceBundle bundle; public DuidokuGUI(String player, int display, Locale loc) { bundle = ResourceBundle.getBundle("i18n.MessageListBundle", loc); this.display=display; player_name=player; logic = new Duidoku(display); main = new JFrame("Duidoku 4x4"); board = new JPanel(); label=new JLabel(bundle.getString("gl")); label1=new JLabel(); label.setFont(new Font("Arial", Font.BOLD, 30)); label.setForeground (Color.lightGray.darker()); main.setForeground(Color.BLACK); board.setSize(600, 600); board.setLayout(new GridLayout(5, 5)); side = new JPanel(); side.setSize(30, 200); side.setLayout(new GridLayout(3, 1)); side.setVisible(true); JPanel pn=new JPanel(); pn.add(label); side.add(label1); side.add(pn); tiles = new Tile[4][4]; //See code for the tiles for (int i = 0; i < 4; i++) { tiles[i] = new Tile[4]; for (int j = 0; j < 4; j++) { tiles[i][j] = new Tile(' ', false, i + 1, j + 1, display); if((i==j)||(i==0 && j==1)||(i==1 && j==0)||(i==2 && j==3)||(i==3 && j==2)){ tiles[i][j].setBorder(BorderFactory.createLineBorder(Color.gray.darker(),2)); } tiles[i][j].setSize(15, 15); tiles[i][j].setVisible(true); board.add(tiles[i][j]); } } JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); sp.setResizeWeight(0.55); sp.setEnabled(false); sp.setDividerSize(0); sp.add(board); sp.add(side); JButton back = new JButton(bundle.getString("back")); back.setPreferredSize(new Dimension(100, 50)); back.setBackground(Color.WHITE); back.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if(!logic.isFull()) { int b = JOptionPane.showConfirmDialog(main, bundle.getString("backmsg"), bundle.getString("main"), JOptionPane.YES_NO_OPTION); if (b == 0) { main.dispose(); Menu main = new Menu(loc); } }else{ main.dispose(); Menu main = new Menu(loc); } } }); JButton select = new JButton(bundle.getString("new")); select.setBackground(Color.WHITE); select.setPreferredSize(new Dimension(100, 50)); select.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if (!logic.isFull()) { int n = JOptionPane.showConfirmDialog(main, bundle.getString("newgame"), bundle.getString("new"), JOptionPane.YES_NO_OPTION); if (n == 0) { main.dispose(); DuidokuGUI dui = new DuidokuGUI(player, display, loc); } } else { main.dispose(); DuidokuGUI dui = new DuidokuGUI(player, display, loc); } } }); JPanel header = new JPanel(); header.setSize(400, 50); header.add(back); header.add(select); header.setVisible(true); JSplitPane sp1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT); sp1.setResizeWeight(0.1); sp1.setEnabled(false); sp1.setDividerSize(0); sp1.add(header); sp1.add(sp); main.add(sp1); main.setSize(800, 600); main.setLocationRelativeTo(null); main.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); main.setVisible(true); main.setResizable(true); } public class Tile extends JButton { Coordinates c; JButton[] choices; char value; boolean locked; JFrame help; public Tile(char value, boolean locked, int x, int y, int display) { this.value = value; this.setText(String.valueOf(value)); c = new Coordinates(x, y, logic.dimensions); choices = new JButton[4]; this.locked = locked; setFont(new Font("Arial", Font.BOLD, 30)); setBackground(Color.WHITE.brighter()); if (!locked) { this.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { main.setEnabled(false); help = new JFrame(bundle.getString("choose")); help.setResizable(false); help.setSize(250, 250); help.setLocationRelativeTo(DuidokuGUI.Tile.this); choose(display); help.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { main.setEnabled(true); } }); } }); } } public void choose(int display) { JPanel pane = new JPanel(); pane.setVisible(true); setFont(new Font("Arial", Font.BOLD, 30)); pane.setLayout(new GridLayout(2, 2, 2, 2)); for (int i = 0; i < 4; i++) { if (display == 1) //If i chose to display numbers { choices[i] = new DuidokuGUI.Tile.Choice(Integer.toString(i + 1)); choices[i].setFont(new Font("Arial", Font.BOLD, 30)); if (!logic.Helper(c.getX(), c.getY()).contains((char) ('0' + (i + 1)))) { choices[i].setEnabled(false); choices[i].setBackground(Color.lightGray); }else{ choices[i].setBackground(Color.WHITE); } } else { choices[i] = new DuidokuGUI.Tile.Choice(Character.toString(logic.getLetters().get(i))); choices[i].setFont(new Font("Arial", Font.BOLD, 30)); if (!logic.Helper(c.getX(), c.getY()).contains(logic.getLetters().get(i))) { choices[i].setEnabled(false); choices[i].setBackground(Color.lightGray); }else{ choices[i].setBackground(Color.WHITE.brighter()); } } pane.add(choices[i]); } help.add(pane); help.setVisible(true); } public class Choice extends JButton { char val; public Choice(String text) { this.setText(text); val = text.charAt(0); this.setSize(30, 30); this.setVisible(true); this.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if(!logic.isFull()) { main.setEnabled(true); logic.player(c.getX(), c.getY(), val); setBackground(Color.LIGHT_GRAY); DuidokuGUI.Tile.this.setText(Character.toString(logic.getTable()[c.getX() - 1][c.getY() - 1].getValue())); //Goes to the logic's table and matches the numbers to the UI display because putting in the value may not have vbeen successful DuidokuGUI.Tile.this.help.dispose(); DuidokuGUI.Tile.this.setEnabled(false); check(); if (logic.isFull()) { label.setText(bundle.getString("win")); //εδω κανει το save για τα score(οταν κερδιζει) if(!player_name.equals("Anonymous")) { PlayerReaderWriter save = new PlayerReaderWriter(); ArrayList<Player> players = save.Read("scores.txt"); if (players == null) { players = new ArrayList<>(); } boolean found = false; for (Player p : players) { if(p.getName().equals(player_name)) { p.setVictories(p.getVictories() + 1); found = true; break; } } if(!found) { players.add(new Player(player_name, 1, 0, null, null)); } save.Write(players, "scores.txt"); } } if(!logic.isFull()) { logic.pc(); tiles[logic.getCurrent_x_pc()][logic.getCurrent_y_pc()].setText(Character.toString(logic.getCurrent_c_pc())); tiles[logic.getCurrent_x_pc()][logic.getCurrent_y_pc()].setBackground(Color.pink); tiles[logic.getCurrent_x_pc()][logic.getCurrent_y_pc()].setEnabled(false); check(); if (logic.isFull()) { label.setText(bundle.getString("lose")); // εδω κανει το save για τα score(οταν χανει) if(!player_name.equals("Anonymous")) { PlayerReaderWriter save = new PlayerReaderWriter(); ArrayList<Player> players = save.Read("scores.txt"); if (players == null) { players = new ArrayList<>(); } boolean found = false; for (Player p : players) { if(p.getName().equals(player_name)) { p.setDefeats(p.getDefeats() + 1); found = true; break; } } if(!found) { players.add(new Player(player_name, 0, 1, null, null)); } save.Write(players, "scores.txt"); } } } } } }); } } public void check() { logic.check_duidoku(); for (int i = 0; i < logic.dimensions; i++) { for (int j = 0; j < logic.dimensions; j++) { if (logic.getTable()[i][j].isBlocked_cell()) { tiles[i][j].setEnabled(false); tiles[i][j].setBackground(Color.black.brighter()); } } } } } }
LukaSt99/Sudoku-GUI
src/DuidokuGUI.java
2,624
//εδω κανει το save για τα score(οταν κερδιζει)
line_comment
el
import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.Locale; import java.util.ResourceBundle; public class DuidokuGUI { Duidoku logic; JFrame main; JPanel board; JPanel side; JButton[][] tiles; int display; JLabel label; JLabel label1; String player_name; private ResourceBundle bundle; public DuidokuGUI(String player, int display, Locale loc) { bundle = ResourceBundle.getBundle("i18n.MessageListBundle", loc); this.display=display; player_name=player; logic = new Duidoku(display); main = new JFrame("Duidoku 4x4"); board = new JPanel(); label=new JLabel(bundle.getString("gl")); label1=new JLabel(); label.setFont(new Font("Arial", Font.BOLD, 30)); label.setForeground (Color.lightGray.darker()); main.setForeground(Color.BLACK); board.setSize(600, 600); board.setLayout(new GridLayout(5, 5)); side = new JPanel(); side.setSize(30, 200); side.setLayout(new GridLayout(3, 1)); side.setVisible(true); JPanel pn=new JPanel(); pn.add(label); side.add(label1); side.add(pn); tiles = new Tile[4][4]; //See code for the tiles for (int i = 0; i < 4; i++) { tiles[i] = new Tile[4]; for (int j = 0; j < 4; j++) { tiles[i][j] = new Tile(' ', false, i + 1, j + 1, display); if((i==j)||(i==0 && j==1)||(i==1 && j==0)||(i==2 && j==3)||(i==3 && j==2)){ tiles[i][j].setBorder(BorderFactory.createLineBorder(Color.gray.darker(),2)); } tiles[i][j].setSize(15, 15); tiles[i][j].setVisible(true); board.add(tiles[i][j]); } } JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); sp.setResizeWeight(0.55); sp.setEnabled(false); sp.setDividerSize(0); sp.add(board); sp.add(side); JButton back = new JButton(bundle.getString("back")); back.setPreferredSize(new Dimension(100, 50)); back.setBackground(Color.WHITE); back.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if(!logic.isFull()) { int b = JOptionPane.showConfirmDialog(main, bundle.getString("backmsg"), bundle.getString("main"), JOptionPane.YES_NO_OPTION); if (b == 0) { main.dispose(); Menu main = new Menu(loc); } }else{ main.dispose(); Menu main = new Menu(loc); } } }); JButton select = new JButton(bundle.getString("new")); select.setBackground(Color.WHITE); select.setPreferredSize(new Dimension(100, 50)); select.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if (!logic.isFull()) { int n = JOptionPane.showConfirmDialog(main, bundle.getString("newgame"), bundle.getString("new"), JOptionPane.YES_NO_OPTION); if (n == 0) { main.dispose(); DuidokuGUI dui = new DuidokuGUI(player, display, loc); } } else { main.dispose(); DuidokuGUI dui = new DuidokuGUI(player, display, loc); } } }); JPanel header = new JPanel(); header.setSize(400, 50); header.add(back); header.add(select); header.setVisible(true); JSplitPane sp1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT); sp1.setResizeWeight(0.1); sp1.setEnabled(false); sp1.setDividerSize(0); sp1.add(header); sp1.add(sp); main.add(sp1); main.setSize(800, 600); main.setLocationRelativeTo(null); main.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); main.setVisible(true); main.setResizable(true); } public class Tile extends JButton { Coordinates c; JButton[] choices; char value; boolean locked; JFrame help; public Tile(char value, boolean locked, int x, int y, int display) { this.value = value; this.setText(String.valueOf(value)); c = new Coordinates(x, y, logic.dimensions); choices = new JButton[4]; this.locked = locked; setFont(new Font("Arial", Font.BOLD, 30)); setBackground(Color.WHITE.brighter()); if (!locked) { this.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { main.setEnabled(false); help = new JFrame(bundle.getString("choose")); help.setResizable(false); help.setSize(250, 250); help.setLocationRelativeTo(DuidokuGUI.Tile.this); choose(display); help.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { main.setEnabled(true); } }); } }); } } public void choose(int display) { JPanel pane = new JPanel(); pane.setVisible(true); setFont(new Font("Arial", Font.BOLD, 30)); pane.setLayout(new GridLayout(2, 2, 2, 2)); for (int i = 0; i < 4; i++) { if (display == 1) //If i chose to display numbers { choices[i] = new DuidokuGUI.Tile.Choice(Integer.toString(i + 1)); choices[i].setFont(new Font("Arial", Font.BOLD, 30)); if (!logic.Helper(c.getX(), c.getY()).contains((char) ('0' + (i + 1)))) { choices[i].setEnabled(false); choices[i].setBackground(Color.lightGray); }else{ choices[i].setBackground(Color.WHITE); } } else { choices[i] = new DuidokuGUI.Tile.Choice(Character.toString(logic.getLetters().get(i))); choices[i].setFont(new Font("Arial", Font.BOLD, 30)); if (!logic.Helper(c.getX(), c.getY()).contains(logic.getLetters().get(i))) { choices[i].setEnabled(false); choices[i].setBackground(Color.lightGray); }else{ choices[i].setBackground(Color.WHITE.brighter()); } } pane.add(choices[i]); } help.add(pane); help.setVisible(true); } public class Choice extends JButton { char val; public Choice(String text) { this.setText(text); val = text.charAt(0); this.setSize(30, 30); this.setVisible(true); this.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if(!logic.isFull()) { main.setEnabled(true); logic.player(c.getX(), c.getY(), val); setBackground(Color.LIGHT_GRAY); DuidokuGUI.Tile.this.setText(Character.toString(logic.getTable()[c.getX() - 1][c.getY() - 1].getValue())); //Goes to the logic's table and matches the numbers to the UI display because putting in the value may not have vbeen successful DuidokuGUI.Tile.this.help.dispose(); DuidokuGUI.Tile.this.setEnabled(false); check(); if (logic.isFull()) { label.setText(bundle.getString("win")); //εδω κανει<SUF> if(!player_name.equals("Anonymous")) { PlayerReaderWriter save = new PlayerReaderWriter(); ArrayList<Player> players = save.Read("scores.txt"); if (players == null) { players = new ArrayList<>(); } boolean found = false; for (Player p : players) { if(p.getName().equals(player_name)) { p.setVictories(p.getVictories() + 1); found = true; break; } } if(!found) { players.add(new Player(player_name, 1, 0, null, null)); } save.Write(players, "scores.txt"); } } if(!logic.isFull()) { logic.pc(); tiles[logic.getCurrent_x_pc()][logic.getCurrent_y_pc()].setText(Character.toString(logic.getCurrent_c_pc())); tiles[logic.getCurrent_x_pc()][logic.getCurrent_y_pc()].setBackground(Color.pink); tiles[logic.getCurrent_x_pc()][logic.getCurrent_y_pc()].setEnabled(false); check(); if (logic.isFull()) { label.setText(bundle.getString("lose")); // εδω κανει το save για τα score(οταν χανει) if(!player_name.equals("Anonymous")) { PlayerReaderWriter save = new PlayerReaderWriter(); ArrayList<Player> players = save.Read("scores.txt"); if (players == null) { players = new ArrayList<>(); } boolean found = false; for (Player p : players) { if(p.getName().equals(player_name)) { p.setDefeats(p.getDefeats() + 1); found = true; break; } } if(!found) { players.add(new Player(player_name, 0, 1, null, null)); } save.Write(players, "scores.txt"); } } } } } }); } } public void check() { logic.check_duidoku(); for (int i = 0; i < logic.dimensions; i++) { for (int j = 0; j < logic.dimensions; j++) { if (logic.getTable()[i][j].isBlocked_cell()) { tiles[i][j].setEnabled(false); tiles[i][j].setBackground(Color.black.brighter()); } } } } } }
2809_19
package com.emmanouilpapadimitrou.healthapp.Fragments; import android.app.AlertDialog; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.support.v4.app.Fragment; import android.widget.TextView; import android.widget.Toast; import com.emmanouilpapadimitrou.healthapp.Activities.PatientsActivity; import com.emmanouilpapadimitrou.healthapp.Adapters.NotesAdapter; import com.emmanouilpapadimitrou.healthapp.POJOs.*; import com.emmanouilpapadimitrou.healthapp.R; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; public class NotesFragment extends Fragment { private ArrayList<Note> allNotes; private FirebaseAuth firebaseAuth; private String userID; private DatabaseReference referenceDB; private ListView notesList; private FloatingActionButton addNotesBtn; private Users currentUser; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_notes, container, false); //Παίρνουμε τον χρήστη currentUser = ((PatientsActivity)getActivity()).getCurrentUser(); //Ορισμός της λίστας που περιέχει όλα τα αντικείμενα των εξετάσεων allNotes = new ArrayList<Note>(); //Μεταβλητή που μας δίνει τα στοιχεία του συνδεδεμένου χρήστη firebaseAuth = FirebaseAuth.getInstance(); //Ανάθεση του ID σε μεταβλητή για μελλοντική χρήστη userID = firebaseAuth.getCurrentUser().getUid(); //Ορισμός της βάσης στην μεταβλητή για οποιαδήποτε μελλοντική χρήστη referenceDB = FirebaseDatabase.getInstance().getReference(); //Σύνδεση μεταβλητής με την λίστα στο layout notesList = (ListView) view.findViewById(R.id.notesList); //Παίρνουμε τον επιλεγμένο χρήστη με όλα του τα στοιχεία final Patient patient = ((PatientsActivity)getActivity()).getCurrentPatient(); //Παίρνουμε όλες τις σημειώσεις από την βάση referenceDB.child("notes").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(final DataSnapshot note : dataSnapshot.getChildren()){ final Note n = new Note(); for(final DataSnapshot noteChild : note.child("users").getChildren()){ //Θα βρούμε το όνομα του χρήστη από το id final String userID = String.valueOf(noteChild.getKey()); referenceDB.child("users").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot1) { for(DataSnapshot userTemp : dataSnapshot1.getChildren()){ if(userID.equals(String.valueOf(userTemp.getKey()))){ n.setId(String.valueOf(note.getKey())); n.setInfo(String.valueOf( note.child("info").getValue())); n.setDate(String.valueOf( note.child("date").getValue())); if(String.valueOf(userTemp.child("type").getValue()).equals("doctor")){ n.setUser("Δρ. " +String.valueOf(userTemp.child("name").getValue())+" " + String.valueOf(userTemp.child("surname").getValue())); } else{ n.setUser(String.valueOf(userTemp.child("name").getValue())+" " + String.valueOf(userTemp.child("surname").getValue())); } for(DataSnapshot patientTempID : note.child("patients").getChildren()){ //Αν είναι ο χρήστης που επιλέχθηκε βάλε την εξέταση στην λίστα if(patient.getId().equals(String.valueOf(patientTempID.getKey()))){ allNotes.add(n); } } } } //Εμφανίζουμε όλες τις εξετάσεις του ασθενούς με τις απαραίτητες πληροφορίες // Create the adapter to convert the array to views NotesAdapter adapter = new NotesAdapter(getActivity(),allNotes); // Attach the adapter to a ListView notesList.setAdapter(adapter); } @Override public void onCancelled(DatabaseError databaseError) { } }); } } } @Override public void onCancelled(DatabaseError databaseError) { } }); //Κουμπί εισαγωγής νέας σημείωσης addNotesBtn = (FloatingActionButton) view.findViewById(R.id.addNotesBtn); addNotesBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Το κουμπί πατήθηκε final AlertDialog.Builder mBuilder = new AlertDialog.Builder(getActivity()); View mView = getLayoutInflater().inflate(R.layout.note_dialog,null); mBuilder.setView(mView); final AlertDialog dialog = mBuilder.create(); //Παίρνουμε την σημείωση του χρήστη final EditText noteInput = (EditText) mView.findViewById(R.id.noteInput); //Κουμπιά Button inputButton = (Button) mView.findViewById(R.id.inputButton); Button denyButton = (Button) mView.findViewById(R.id.denyButton); //Κουμπί για πίσω denyButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); //Κουμπί εισαγωγής inputButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Τρέχουσα ημερομηνία DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); final String date = df.format(Calendar.getInstance().getTime()); //Ελέγχουμε αν είναι άδειο τα πεδίο if(!noteInput.getText().toString().isEmpty()){ referenceDB.child("notes").orderByKey().limitToLast(1).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(final DataSnapshot noteTmp : dataSnapshot.getChildren()){ String currentNoteId = noteTmp.getKey(); currentNoteId = currentNoteId.substring(currentNoteId.length() - 6); int newIntNoteId = Integer.parseInt(currentNoteId) + 1; //Βάζουμε τα απαραίτητα μηδενικά ώστε να υπακούει στο format του id String newStringNoteId = String.valueOf(newIntNoteId); String zeroes = ""; switch(newStringNoteId.length()){ case 1: zeroes+="00000"; break; case 2: zeroes+="0000"; break; case 3: zeroes+="000"; break; case 4: zeroes+="00"; break; case 5: zeroes+="0"; break; } newStringNoteId ="note"+ zeroes + newStringNoteId; final Note newNote = new Note(newStringNoteId, date, noteInput.getText().toString(), currentUser.getName() +" " + currentUser.getSurname()); //Βάζουμε τα στοιχεία της σημείωσης στο πεδίο notes referenceDB.child("notes") .child(newNote.getId()) .setValue(newNote); referenceDB.child("notes") .child(newNote.getId()) .child("patients") .child(patient.getId()) .setValue(true); referenceDB.child("notes") .child(newNote.getId()) .child("users") .child(userID) .setValue(true); //Ενημέρωση ιστορικού //Δημιουργία id νέου ιστορικού final String finalNewStringNoteId = newStringNoteId; referenceDB.child("history").orderByKey().limitToLast(1).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(final DataSnapshot histId : dataSnapshot.getChildren()) { String currentHistId = histId.getKey(); currentHistId = currentHistId.substring(currentHistId.length() - 11); int newIntHistoryId = Integer.parseInt(currentHistId) + 1; //Βάζουμε τα απαραίτητα μηδενικά ώστε να υπακούει στο format του id String newStringHistoryId = String.valueOf(newIntHistoryId); String zeroes = ""; switch (newStringHistoryId.length()) { case 1: zeroes += "0000000000"; break; case 2: zeroes += "000000000"; break; case 3: zeroes += "00000000"; break; case 4: zeroes += "0000000"; break; case 5: zeroes += "000000"; break; case 6: zeroes += "00000"; break; case 7: zeroes += "0000"; break; case 8: zeroes += "000"; break; case 9: zeroes += "00"; break; case 10: zeroes += "0"; break; } newStringHistoryId ="h"+ zeroes + newStringHistoryId; DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); String date = df.format(Calendar.getInstance().getTime()); History newHistory = new History(newStringHistoryId, date, "notes", newNote.getId(), currentUser.getName() +"\n" + currentUser.getSurname(), "create", newNote.getInfo() ); //Εισαγωγή νέου ιστορικού στην βάση referenceDB.child("history") .child(newHistory.getId()) .setValue(newHistory); referenceDB.child("history") .child(newHistory.getId()) .child("type") .child("notes") .setValue(finalNewStringNoteId); referenceDB.child("history") .child(newHistory.getId()) .child("patients") .child(patient.getId()) .setValue(true); referenceDB.child("history") .child(newHistory.getId()) .child("users") .child(userID) .setValue(true); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } Toast.makeText(getActivity(), "Εισαγωγή σημείωσης επιτυχής!", Toast.LENGTH_LONG).show(); dialog.dismiss(); } @Override public void onCancelled(DatabaseError databaseError) { } }); } else{ Toast.makeText(getActivity(),"Μην αφήνετε πεδία κενά!",Toast.LENGTH_LONG).show(); } } }); dialog.show(); } }); //Διαγραφή Σημείωσης //Ελέγχουμε ποια σημείωση πάτησε από την λίστα notesList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { final Note noteSelected = (Note) notesList.getItemAtPosition(position); //Προβολή παραθύρου για επιβεβαίωση διαγραφής φαρμάκου final AlertDialog.Builder mBuilder = new AlertDialog.Builder(getActivity()); View mView = getLayoutInflater().inflate(R.layout.remove_confirmation_dialog,null); mBuilder.setView(mView); final AlertDialog dialog = mBuilder.create(); TextView removeMedicineView = (TextView) mView.findViewById(R.id.removeMedicineView); removeMedicineView.setText("Διαγραφή σημείωσης;\nΔεν μπορεί να αναιρεθεί!"); //Κουμπιά Button denyButton = (Button) mView.findViewById(R.id.denyButton); Button confirmButton = (Button) mView.findViewById(R.id.confirmButton); //Κουμπί για πίσω denyButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); //Κουμπί για επιβεβαίωση διαγραφής confirmButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Διαγραφή από το πεδίο medicines referenceDB.child("notes").child(noteSelected.getId()).removeValue(); //Ενημέρωση ιστορικού //Δημιουργία id νέου ιστορικού referenceDB.child("history").orderByKey().limitToLast(1).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Log.d("TEST","mpike"); for(final DataSnapshot histId : dataSnapshot.getChildren()) { String currentHistId = histId.getKey(); currentHistId = currentHistId.substring(currentHistId.length() - 11); int newIntHistoryId = Integer.parseInt(currentHistId) + 1; //Βάζουμε τα απαραίτητα μηδενικά ώστε να υπακούει στο format του id String newStringHistoryId = String.valueOf(newIntHistoryId); String zeroes = ""; switch (newStringHistoryId.length()) { case 1: zeroes += "0000000000"; break; case 2: zeroes += "000000000"; break; case 3: zeroes += "00000000"; break; case 4: zeroes += "0000000"; break; case 5: zeroes += "000000"; break; case 6: zeroes += "00000"; break; case 7: zeroes += "0000"; break; case 8: zeroes += "000"; break; case 9: zeroes += "00"; break; case 10: zeroes += "0"; break; } newStringHistoryId ="h"+ zeroes + newStringHistoryId; DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); String date = df.format(Calendar.getInstance().getTime()); History newHistory = new History(newStringHistoryId, date, "notes", noteSelected.getId(), currentUser.getName() +" " + currentUser.getSurname(), "delete", noteSelected.getInfo() ); //Εισαγωγή νέου ιστορικού στην βάση referenceDB.child("history") .child(newHistory.getId()) .setValue(newHistory); referenceDB.child("history") .child(newHistory.getId()) .child("type") .child("notes") .setValue(noteSelected.getId()); referenceDB.child("history") .child(newHistory.getId()) .child("patients") .child(patient.getId()) .setValue(true); referenceDB.child("history") .child(newHistory.getId()) .child("users") .child(userID) .setValue(true); } } @Override public void onCancelled(DatabaseError databaseError) { } }); Toast.makeText(getActivity(),"Επιτυχής διαγραφή!",Toast.LENGTH_LONG).show(); dialog.dismiss(); ((PatientsActivity)getActivity()).reloadCurrentFragment(); } }); dialog.show(); return false; } }); return view; } }
ManolisPapd/HealthApp
Android/HealthApp/app/src/main/java/com/emmanouilpapadimitrou/healthapp/Fragments/NotesFragment.java
4,637
//Βάζουμε τα στοιχεία της σημείωσης στο πεδίο notes
line_comment
el
package com.emmanouilpapadimitrou.healthapp.Fragments; import android.app.AlertDialog; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.support.v4.app.Fragment; import android.widget.TextView; import android.widget.Toast; import com.emmanouilpapadimitrou.healthapp.Activities.PatientsActivity; import com.emmanouilpapadimitrou.healthapp.Adapters.NotesAdapter; import com.emmanouilpapadimitrou.healthapp.POJOs.*; import com.emmanouilpapadimitrou.healthapp.R; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; public class NotesFragment extends Fragment { private ArrayList<Note> allNotes; private FirebaseAuth firebaseAuth; private String userID; private DatabaseReference referenceDB; private ListView notesList; private FloatingActionButton addNotesBtn; private Users currentUser; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_notes, container, false); //Παίρνουμε τον χρήστη currentUser = ((PatientsActivity)getActivity()).getCurrentUser(); //Ορισμός της λίστας που περιέχει όλα τα αντικείμενα των εξετάσεων allNotes = new ArrayList<Note>(); //Μεταβλητή που μας δίνει τα στοιχεία του συνδεδεμένου χρήστη firebaseAuth = FirebaseAuth.getInstance(); //Ανάθεση του ID σε μεταβλητή για μελλοντική χρήστη userID = firebaseAuth.getCurrentUser().getUid(); //Ορισμός της βάσης στην μεταβλητή για οποιαδήποτε μελλοντική χρήστη referenceDB = FirebaseDatabase.getInstance().getReference(); //Σύνδεση μεταβλητής με την λίστα στο layout notesList = (ListView) view.findViewById(R.id.notesList); //Παίρνουμε τον επιλεγμένο χρήστη με όλα του τα στοιχεία final Patient patient = ((PatientsActivity)getActivity()).getCurrentPatient(); //Παίρνουμε όλες τις σημειώσεις από την βάση referenceDB.child("notes").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(final DataSnapshot note : dataSnapshot.getChildren()){ final Note n = new Note(); for(final DataSnapshot noteChild : note.child("users").getChildren()){ //Θα βρούμε το όνομα του χρήστη από το id final String userID = String.valueOf(noteChild.getKey()); referenceDB.child("users").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot1) { for(DataSnapshot userTemp : dataSnapshot1.getChildren()){ if(userID.equals(String.valueOf(userTemp.getKey()))){ n.setId(String.valueOf(note.getKey())); n.setInfo(String.valueOf( note.child("info").getValue())); n.setDate(String.valueOf( note.child("date").getValue())); if(String.valueOf(userTemp.child("type").getValue()).equals("doctor")){ n.setUser("Δρ. " +String.valueOf(userTemp.child("name").getValue())+" " + String.valueOf(userTemp.child("surname").getValue())); } else{ n.setUser(String.valueOf(userTemp.child("name").getValue())+" " + String.valueOf(userTemp.child("surname").getValue())); } for(DataSnapshot patientTempID : note.child("patients").getChildren()){ //Αν είναι ο χρήστης που επιλέχθηκε βάλε την εξέταση στην λίστα if(patient.getId().equals(String.valueOf(patientTempID.getKey()))){ allNotes.add(n); } } } } //Εμφανίζουμε όλες τις εξετάσεις του ασθενούς με τις απαραίτητες πληροφορίες // Create the adapter to convert the array to views NotesAdapter adapter = new NotesAdapter(getActivity(),allNotes); // Attach the adapter to a ListView notesList.setAdapter(adapter); } @Override public void onCancelled(DatabaseError databaseError) { } }); } } } @Override public void onCancelled(DatabaseError databaseError) { } }); //Κουμπί εισαγωγής νέας σημείωσης addNotesBtn = (FloatingActionButton) view.findViewById(R.id.addNotesBtn); addNotesBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Το κουμπί πατήθηκε final AlertDialog.Builder mBuilder = new AlertDialog.Builder(getActivity()); View mView = getLayoutInflater().inflate(R.layout.note_dialog,null); mBuilder.setView(mView); final AlertDialog dialog = mBuilder.create(); //Παίρνουμε την σημείωση του χρήστη final EditText noteInput = (EditText) mView.findViewById(R.id.noteInput); //Κουμπιά Button inputButton = (Button) mView.findViewById(R.id.inputButton); Button denyButton = (Button) mView.findViewById(R.id.denyButton); //Κουμπί για πίσω denyButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); //Κουμπί εισαγωγής inputButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Τρέχουσα ημερομηνία DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); final String date = df.format(Calendar.getInstance().getTime()); //Ελέγχουμε αν είναι άδειο τα πεδίο if(!noteInput.getText().toString().isEmpty()){ referenceDB.child("notes").orderByKey().limitToLast(1).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(final DataSnapshot noteTmp : dataSnapshot.getChildren()){ String currentNoteId = noteTmp.getKey(); currentNoteId = currentNoteId.substring(currentNoteId.length() - 6); int newIntNoteId = Integer.parseInt(currentNoteId) + 1; //Βάζουμε τα απαραίτητα μηδενικά ώστε να υπακούει στο format του id String newStringNoteId = String.valueOf(newIntNoteId); String zeroes = ""; switch(newStringNoteId.length()){ case 1: zeroes+="00000"; break; case 2: zeroes+="0000"; break; case 3: zeroes+="000"; break; case 4: zeroes+="00"; break; case 5: zeroes+="0"; break; } newStringNoteId ="note"+ zeroes + newStringNoteId; final Note newNote = new Note(newStringNoteId, date, noteInput.getText().toString(), currentUser.getName() +" " + currentUser.getSurname()); //Βάζουμε τα<SUF> referenceDB.child("notes") .child(newNote.getId()) .setValue(newNote); referenceDB.child("notes") .child(newNote.getId()) .child("patients") .child(patient.getId()) .setValue(true); referenceDB.child("notes") .child(newNote.getId()) .child("users") .child(userID) .setValue(true); //Ενημέρωση ιστορικού //Δημιουργία id νέου ιστορικού final String finalNewStringNoteId = newStringNoteId; referenceDB.child("history").orderByKey().limitToLast(1).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(final DataSnapshot histId : dataSnapshot.getChildren()) { String currentHistId = histId.getKey(); currentHistId = currentHistId.substring(currentHistId.length() - 11); int newIntHistoryId = Integer.parseInt(currentHistId) + 1; //Βάζουμε τα απαραίτητα μηδενικά ώστε να υπακούει στο format του id String newStringHistoryId = String.valueOf(newIntHistoryId); String zeroes = ""; switch (newStringHistoryId.length()) { case 1: zeroes += "0000000000"; break; case 2: zeroes += "000000000"; break; case 3: zeroes += "00000000"; break; case 4: zeroes += "0000000"; break; case 5: zeroes += "000000"; break; case 6: zeroes += "00000"; break; case 7: zeroes += "0000"; break; case 8: zeroes += "000"; break; case 9: zeroes += "00"; break; case 10: zeroes += "0"; break; } newStringHistoryId ="h"+ zeroes + newStringHistoryId; DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); String date = df.format(Calendar.getInstance().getTime()); History newHistory = new History(newStringHistoryId, date, "notes", newNote.getId(), currentUser.getName() +"\n" + currentUser.getSurname(), "create", newNote.getInfo() ); //Εισαγωγή νέου ιστορικού στην βάση referenceDB.child("history") .child(newHistory.getId()) .setValue(newHistory); referenceDB.child("history") .child(newHistory.getId()) .child("type") .child("notes") .setValue(finalNewStringNoteId); referenceDB.child("history") .child(newHistory.getId()) .child("patients") .child(patient.getId()) .setValue(true); referenceDB.child("history") .child(newHistory.getId()) .child("users") .child(userID) .setValue(true); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } Toast.makeText(getActivity(), "Εισαγωγή σημείωσης επιτυχής!", Toast.LENGTH_LONG).show(); dialog.dismiss(); } @Override public void onCancelled(DatabaseError databaseError) { } }); } else{ Toast.makeText(getActivity(),"Μην αφήνετε πεδία κενά!",Toast.LENGTH_LONG).show(); } } }); dialog.show(); } }); //Διαγραφή Σημείωσης //Ελέγχουμε ποια σημείωση πάτησε από την λίστα notesList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { final Note noteSelected = (Note) notesList.getItemAtPosition(position); //Προβολή παραθύρου για επιβεβαίωση διαγραφής φαρμάκου final AlertDialog.Builder mBuilder = new AlertDialog.Builder(getActivity()); View mView = getLayoutInflater().inflate(R.layout.remove_confirmation_dialog,null); mBuilder.setView(mView); final AlertDialog dialog = mBuilder.create(); TextView removeMedicineView = (TextView) mView.findViewById(R.id.removeMedicineView); removeMedicineView.setText("Διαγραφή σημείωσης;\nΔεν μπορεί να αναιρεθεί!"); //Κουμπιά Button denyButton = (Button) mView.findViewById(R.id.denyButton); Button confirmButton = (Button) mView.findViewById(R.id.confirmButton); //Κουμπί για πίσω denyButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); //Κουμπί για επιβεβαίωση διαγραφής confirmButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Διαγραφή από το πεδίο medicines referenceDB.child("notes").child(noteSelected.getId()).removeValue(); //Ενημέρωση ιστορικού //Δημιουργία id νέου ιστορικού referenceDB.child("history").orderByKey().limitToLast(1).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Log.d("TEST","mpike"); for(final DataSnapshot histId : dataSnapshot.getChildren()) { String currentHistId = histId.getKey(); currentHistId = currentHistId.substring(currentHistId.length() - 11); int newIntHistoryId = Integer.parseInt(currentHistId) + 1; //Βάζουμε τα απαραίτητα μηδενικά ώστε να υπακούει στο format του id String newStringHistoryId = String.valueOf(newIntHistoryId); String zeroes = ""; switch (newStringHistoryId.length()) { case 1: zeroes += "0000000000"; break; case 2: zeroes += "000000000"; break; case 3: zeroes += "00000000"; break; case 4: zeroes += "0000000"; break; case 5: zeroes += "000000"; break; case 6: zeroes += "00000"; break; case 7: zeroes += "0000"; break; case 8: zeroes += "000"; break; case 9: zeroes += "00"; break; case 10: zeroes += "0"; break; } newStringHistoryId ="h"+ zeroes + newStringHistoryId; DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); String date = df.format(Calendar.getInstance().getTime()); History newHistory = new History(newStringHistoryId, date, "notes", noteSelected.getId(), currentUser.getName() +" " + currentUser.getSurname(), "delete", noteSelected.getInfo() ); //Εισαγωγή νέου ιστορικού στην βάση referenceDB.child("history") .child(newHistory.getId()) .setValue(newHistory); referenceDB.child("history") .child(newHistory.getId()) .child("type") .child("notes") .setValue(noteSelected.getId()); referenceDB.child("history") .child(newHistory.getId()) .child("patients") .child(patient.getId()) .setValue(true); referenceDB.child("history") .child(newHistory.getId()) .child("users") .child(userID) .setValue(true); } } @Override public void onCancelled(DatabaseError databaseError) { } }); Toast.makeText(getActivity(),"Επιτυχής διαγραφή!",Toast.LENGTH_LONG).show(); dialog.dismiss(); ((PatientsActivity)getActivity()).reloadCurrentFragment(); } }); dialog.show(); return false; } }); return view; } }
24503_0
package gr.aueb.cf.ch3; import java.util.Scanner; /** * Μετράει το πλήθος των ακεραίων που δίνει * ο χρήστης. */ public class DigitCountApp { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int inputNum = 0; int num = 0; int count = 0; System.out.println("Please insert num"); inputNum = scanner.nextInt(); num = inputNum; do { count++; num = num / 10; } while (num != 10); System.out.println("Digit Count: " + count); } }
ManosDaskalelis/Java
cf/ch3/DigitCountApp.java
197
/** * Μετράει το πλήθος των ακεραίων που δίνει * ο χρήστης. */
block_comment
el
package gr.aueb.cf.ch3; import java.util.Scanner; /** * Μετράει το πλήθος<SUF>*/ public class DigitCountApp { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int inputNum = 0; int num = 0; int count = 0; System.out.println("Please insert num"); inputNum = scanner.nextInt(); num = inputNum; do { count++; num = num / 10; } while (num != 10); System.out.println("Digit Count: " + count); } }
6672_7
package gr.aueb.cf.ch5; import java.util.Scanner; /** * Δέχεται από το stdin ένα int για navigation σε ένα μενού * και ένα δεύτερο int για να κάνει print stars (*) ανάλογα. */ public class StarPrintingMethodApp { static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int choice = 0; int num = 0; do { menuNav(); System.out.println(); choice = userInput(); if (choice < 1 || choice > 6) { System.out.println("Wrong choice."); continue; } switch (choice) { case 1: starPrintingMethodGeneral(1); break; case 2: System.out.println("Please insert a number to print vertical stars (*)"); starPrintingMethodVert(); break; case 3: starPrintingMethodGeneral(3); break; case 4: starPrintingMethodGeneral(4); break; case 5: starPrintingMethodGeneral(5); break; default: System.out.println("Wrong Choice"); } } while (choice != 6); } /** * Menu. */ public static void menuNav() { System.out.println("\n\nPlease insert a number 1 - 6 to navigate the menu\n"); System.out.println("1. Prints stars (*) in a horizontal format"); System.out.println("2. Prints stars (*) in a vertical format"); System.out.println("3. Prints stars (*) in a (n X n) format"); System.out.println("4. Prints stars (*) in a (1 - n) format"); System.out.println("5. Prints stars (*) in a (n - 1) format"); System.out.println("6. Exit"); } /** * Μέθοδος που δέχεται τις επιλογές του χρήστη από το stdin. */ public static int userInput() { return scanner.nextInt(); } /** * Μέθοδος που δέχεται στο σώμα της αλλές μεθόδους και αναλόγα το user choice * κάνει print stars(*). * @param choice η επιλογή του χρήστη. * @return επιστρέφει το αποτέλεσμα */ public static int starPrintingMethodGeneral(int choice) { switch (choice) { case 1: System.out.println("Please insert a number for horizontal stars (*)"); int num = userInput(); for (int i = 1; i <= num; i++) { System.out.print("*"); } break; case 3: System.out.println("Please insert number for (n X n) stars (*)"); starPrintingMethodTable(); break; case 4: System.out.println("Please insert number for (1 - n) stars (*)"); starAscending(); break; case 5: System.out.println("Please insert number for (n - 1) stars (*)"); starDescending(); break; } return choice; } /** * Μέθοδος που εκτυπώνει κάθετα stars(*). */ public static void starPrintingMethodVert() { int num = scanner.nextInt(); for (int i = 1; i <= num; i++) { System.out.println("*"); } } /** * Μέθοδος που εκτυπώνει (n X n) stars(*). */ public static void starPrintingMethodTable() { int num = userInput(); for (int i = 1; i <= num; i++) { for (int j = 1; j <= num; j++) { System.out.print("*"); } System.out.println(); } } /** * Μέθοδος που εκτυπώνει (1 - n ) stars(*). */ public static void starAscending() { int num = userInput(); for (int i = 1; i <= num; i++) { for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); } } /** * Μέθοδος που εκτυπώνει ( n - 1) stars(*). */ public static void starDescending() { int num = userInput(); for (int i = 1; i <= num; i++) { for (int j = num; j >= i; j--){ System.out.print("*"); } System.out.println(); } } }
ManosDaskalelis/java-exc
ch5/StarPrintingMethodApp.java
1,251
/** * Μέθοδος που εκτυπώνει ( n - 1) stars(*). */
block_comment
el
package gr.aueb.cf.ch5; import java.util.Scanner; /** * Δέχεται από το stdin ένα int για navigation σε ένα μενού * και ένα δεύτερο int για να κάνει print stars (*) ανάλογα. */ public class StarPrintingMethodApp { static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int choice = 0; int num = 0; do { menuNav(); System.out.println(); choice = userInput(); if (choice < 1 || choice > 6) { System.out.println("Wrong choice."); continue; } switch (choice) { case 1: starPrintingMethodGeneral(1); break; case 2: System.out.println("Please insert a number to print vertical stars (*)"); starPrintingMethodVert(); break; case 3: starPrintingMethodGeneral(3); break; case 4: starPrintingMethodGeneral(4); break; case 5: starPrintingMethodGeneral(5); break; default: System.out.println("Wrong Choice"); } } while (choice != 6); } /** * Menu. */ public static void menuNav() { System.out.println("\n\nPlease insert a number 1 - 6 to navigate the menu\n"); System.out.println("1. Prints stars (*) in a horizontal format"); System.out.println("2. Prints stars (*) in a vertical format"); System.out.println("3. Prints stars (*) in a (n X n) format"); System.out.println("4. Prints stars (*) in a (1 - n) format"); System.out.println("5. Prints stars (*) in a (n - 1) format"); System.out.println("6. Exit"); } /** * Μέθοδος που δέχεται τις επιλογές του χρήστη από το stdin. */ public static int userInput() { return scanner.nextInt(); } /** * Μέθοδος που δέχεται στο σώμα της αλλές μεθόδους και αναλόγα το user choice * κάνει print stars(*). * @param choice η επιλογή του χρήστη. * @return επιστρέφει το αποτέλεσμα */ public static int starPrintingMethodGeneral(int choice) { switch (choice) { case 1: System.out.println("Please insert a number for horizontal stars (*)"); int num = userInput(); for (int i = 1; i <= num; i++) { System.out.print("*"); } break; case 3: System.out.println("Please insert number for (n X n) stars (*)"); starPrintingMethodTable(); break; case 4: System.out.println("Please insert number for (1 - n) stars (*)"); starAscending(); break; case 5: System.out.println("Please insert number for (n - 1) stars (*)"); starDescending(); break; } return choice; } /** * Μέθοδος που εκτυπώνει κάθετα stars(*). */ public static void starPrintingMethodVert() { int num = scanner.nextInt(); for (int i = 1; i <= num; i++) { System.out.println("*"); } } /** * Μέθοδος που εκτυπώνει (n X n) stars(*). */ public static void starPrintingMethodTable() { int num = userInput(); for (int i = 1; i <= num; i++) { for (int j = 1; j <= num; j++) { System.out.print("*"); } System.out.println(); } } /** * Μέθοδος που εκτυπώνει (1 - n ) stars(*). */ public static void starAscending() { int num = userInput(); for (int i = 1; i <= num; i++) { for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); } } /** * Μέθοδος που εκτυπώνει<SUF>*/ public static void starDescending() { int num = userInput(); for (int i = 1; i <= num; i++) { for (int j = num; j >= i; j--){ System.out.print("*"); } System.out.println(); } } }
6820_4
package View.Side_Panels; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.util.Arrays; import static Util.Util.scaleImage; public class CapturedMonsters extends JPanel{ private JLabel top = new JLabel("Captures"); private JPanel capturedPanel = new JPanel(); private JLabel bottom = new JLabel("Captured: 0"); private final JLabel[][] monstersPictures = new JLabel[4][3]; // Όλες οι εικόνες και τα texts. private JPanel images; // Πάνελ που περιέχει όλες τις εικόνες. private int picturesWidth; private int picturesHeight; private final int[] captives = new int[12]; private int ID; private final BufferedImage[] enemyMonsters; private int[] capturedMonsters; public CapturedMonsters(int width, int height, BufferedImage[] enemyMonsters){ this.enemyMonsters = enemyMonsters; this.capturedMonsters = new int[enemyMonsters.length]; for (int i = 0; i < enemyMonsters.length; i++) this.capturedMonsters[i] = 0; // Το Resize του View, επικαλείται πάντα στην αρχή. // Εφόσον δε δημιούργησα μέθοδο αρχικοποίησης των πάνελς // και επικαλούμαι τα nextRound. this.ID = -1; this.setSize(new Dimension(width, height)); this.setLayout(new BorderLayout()); this.setUpBottomHalf(); this.setVisible(true); } private void setUpBottomHalf(){ JPanel bottomHalf = new JPanel(); bottomHalf.setLayout(new BorderLayout()); bottomHalf.setPreferredSize(new Dimension(this.getWidth(), this.getHeight())); setUpLabels(); this.capturedPanel.setBackground(Color.GRAY); this.addCaptiveMonsters(); bottomHalf.add(this.top, BorderLayout.NORTH); bottomHalf.add(this.capturedPanel, BorderLayout.CENTER); this.add(bottomHalf); } private void setUpLabels(){ this.top = new JLabel("Captures"); this.top.setHorizontalAlignment(SwingConstants.CENTER); this.capturedPanel = new JPanel(); this.capturedPanel.setLayout(new BorderLayout()); this.bottom = new JLabel("Captured: 0"); this.bottom.setForeground(Color.WHITE); this.images = new JPanel(); this.images.setLayout(new GridLayout(4, 3)); this.images.setBackground(Color.GRAY); this.scaleCapturedPanel(); this.setUpImages(); } private void setUpImages(){ for(int i = 0; i < 4; ++i){ for(int j = 0; j < 3; ++j){ monstersPictures[i][j] = new JLabel("", null, JLabel.LEADING); images.add(monstersPictures[i][j]); } } this.getCaptiveMonsters(); } private void addCaptiveMonsters(){ this.picturesWidth = this.getWidth(); this.picturesHeight = this.getHeight(); this.capturedPanel.add(images, BorderLayout.CENTER); this.capturedPanel.add(bottom, BorderLayout.SOUTH); this.add(this.capturedPanel); } public void nextRound(int[] referenceToMonsters){ this.ID = (this. ID == 1) ? 2 : 1; this.getTotalOfCaptives(referenceToMonsters); this.getCaptiveMonsters(); } private void getCaptiveMonsters(){ int monster = 0; int size = this.getHeight() / 23; int height = this.getHeight() / 5; int width = this.getWidth() / 6; Font font = new Font("Verdana", Font.BOLD + Font.ITALIC, size); for(int i = 0; i < 4; ++i){ for(int j = 0; j < 3; ++j){ monstersPictures[i][j].setFont(font); monstersPictures[i][j].setText(Integer.toString(capturedMonsters[monster])); monstersPictures[i][j].setIcon(scaleImage(enemyMonsters[monster], width, height)); ++monster; } } } private void getTotalOfCaptives(int[] referenceToMonsters){ if(referenceToMonsters == null) return; int size = referenceToMonsters.length; int sum = 0; for(int i = 0; i < size; ++i) { captives[i] = capturedMonsters[i]; sum += captives[i]; } this.setTotalCaptives(sum); } private void setTotalCaptives(int sum){ this.bottom.setText("Captured: " + sum); } public void scalePanel(int width, int height){ if(this.ID == -1){ this.ID = 2; return; } this.setSize(width, height); this.picturesWidth = this.getWidth(); this.picturesHeight = this.getHeight(); this.getCaptiveMonsters(); this.scaleCapturedPanel(); } // Επειδή, αλλάζει μόνο του rounds. public void restartGame(){ Arrays.fill(capturedMonsters, 0); for(JLabel[] row : monstersPictures) for(JLabel monster : row) monster.setText(Integer.toString(0)); setTotalCaptives(0); } private void scaleCapturedPanel(){ int size = this.getHeight() / 30; this.top.setFont(new Font("Verdana", Font.BOLD + Font.ITALIC, 2 * size)); this.bottom.setFont(new Font("Verdana", Font.BOLD + Font.ITALIC, size)); } public void captureMonster(int index) { ++this.capturedMonsters[index]; updateCapturedMonsters(index); } public void rescueMonster(int index) { --this.capturedMonsters[index]; updateCapturedMonsters(index); } private void updateCapturedMonsters(int index) { int row = index / 3; int col = index % 3; int size = this.getHeight() / 23; // TODO: Font class's field. Font font = new Font("Verdana", Font.BOLD + Font.ITALIC, size); monstersPictures[row][col].setFont(font); monstersPictures[row][col].setText(Integer.toString(capturedMonsters[index])); int sum = 0; for(int captives : capturedMonsters) sum += captives; setTotalCaptives(sum); } }
ManosKast/Online_Stratego
src/View/Side_Panels/CapturedMonsters.java
1,651
// και επικαλούμαι τα nextRound.
line_comment
el
package View.Side_Panels; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.util.Arrays; import static Util.Util.scaleImage; public class CapturedMonsters extends JPanel{ private JLabel top = new JLabel("Captures"); private JPanel capturedPanel = new JPanel(); private JLabel bottom = new JLabel("Captured: 0"); private final JLabel[][] monstersPictures = new JLabel[4][3]; // Όλες οι εικόνες και τα texts. private JPanel images; // Πάνελ που περιέχει όλες τις εικόνες. private int picturesWidth; private int picturesHeight; private final int[] captives = new int[12]; private int ID; private final BufferedImage[] enemyMonsters; private int[] capturedMonsters; public CapturedMonsters(int width, int height, BufferedImage[] enemyMonsters){ this.enemyMonsters = enemyMonsters; this.capturedMonsters = new int[enemyMonsters.length]; for (int i = 0; i < enemyMonsters.length; i++) this.capturedMonsters[i] = 0; // Το Resize του View, επικαλείται πάντα στην αρχή. // Εφόσον δε δημιούργησα μέθοδο αρχικοποίησης των πάνελς // και επικαλούμαι<SUF> this.ID = -1; this.setSize(new Dimension(width, height)); this.setLayout(new BorderLayout()); this.setUpBottomHalf(); this.setVisible(true); } private void setUpBottomHalf(){ JPanel bottomHalf = new JPanel(); bottomHalf.setLayout(new BorderLayout()); bottomHalf.setPreferredSize(new Dimension(this.getWidth(), this.getHeight())); setUpLabels(); this.capturedPanel.setBackground(Color.GRAY); this.addCaptiveMonsters(); bottomHalf.add(this.top, BorderLayout.NORTH); bottomHalf.add(this.capturedPanel, BorderLayout.CENTER); this.add(bottomHalf); } private void setUpLabels(){ this.top = new JLabel("Captures"); this.top.setHorizontalAlignment(SwingConstants.CENTER); this.capturedPanel = new JPanel(); this.capturedPanel.setLayout(new BorderLayout()); this.bottom = new JLabel("Captured: 0"); this.bottom.setForeground(Color.WHITE); this.images = new JPanel(); this.images.setLayout(new GridLayout(4, 3)); this.images.setBackground(Color.GRAY); this.scaleCapturedPanel(); this.setUpImages(); } private void setUpImages(){ for(int i = 0; i < 4; ++i){ for(int j = 0; j < 3; ++j){ monstersPictures[i][j] = new JLabel("", null, JLabel.LEADING); images.add(monstersPictures[i][j]); } } this.getCaptiveMonsters(); } private void addCaptiveMonsters(){ this.picturesWidth = this.getWidth(); this.picturesHeight = this.getHeight(); this.capturedPanel.add(images, BorderLayout.CENTER); this.capturedPanel.add(bottom, BorderLayout.SOUTH); this.add(this.capturedPanel); } public void nextRound(int[] referenceToMonsters){ this.ID = (this. ID == 1) ? 2 : 1; this.getTotalOfCaptives(referenceToMonsters); this.getCaptiveMonsters(); } private void getCaptiveMonsters(){ int monster = 0; int size = this.getHeight() / 23; int height = this.getHeight() / 5; int width = this.getWidth() / 6; Font font = new Font("Verdana", Font.BOLD + Font.ITALIC, size); for(int i = 0; i < 4; ++i){ for(int j = 0; j < 3; ++j){ monstersPictures[i][j].setFont(font); monstersPictures[i][j].setText(Integer.toString(capturedMonsters[monster])); monstersPictures[i][j].setIcon(scaleImage(enemyMonsters[monster], width, height)); ++monster; } } } private void getTotalOfCaptives(int[] referenceToMonsters){ if(referenceToMonsters == null) return; int size = referenceToMonsters.length; int sum = 0; for(int i = 0; i < size; ++i) { captives[i] = capturedMonsters[i]; sum += captives[i]; } this.setTotalCaptives(sum); } private void setTotalCaptives(int sum){ this.bottom.setText("Captured: " + sum); } public void scalePanel(int width, int height){ if(this.ID == -1){ this.ID = 2; return; } this.setSize(width, height); this.picturesWidth = this.getWidth(); this.picturesHeight = this.getHeight(); this.getCaptiveMonsters(); this.scaleCapturedPanel(); } // Επειδή, αλλάζει μόνο του rounds. public void restartGame(){ Arrays.fill(capturedMonsters, 0); for(JLabel[] row : monstersPictures) for(JLabel monster : row) monster.setText(Integer.toString(0)); setTotalCaptives(0); } private void scaleCapturedPanel(){ int size = this.getHeight() / 30; this.top.setFont(new Font("Verdana", Font.BOLD + Font.ITALIC, 2 * size)); this.bottom.setFont(new Font("Verdana", Font.BOLD + Font.ITALIC, size)); } public void captureMonster(int index) { ++this.capturedMonsters[index]; updateCapturedMonsters(index); } public void rescueMonster(int index) { --this.capturedMonsters[index]; updateCapturedMonsters(index); } private void updateCapturedMonsters(int index) { int row = index / 3; int col = index % 3; int size = this.getHeight() / 23; // TODO: Font class's field. Font font = new Font("Verdana", Font.BOLD + Font.ITALIC, size); monstersPictures[row][col].setFont(font); monstersPictures[row][col].setText(Integer.toString(capturedMonsters[index])); int sum = 0; for(int captives : capturedMonsters) sum += captives; setTotalCaptives(sum); } }
3735_13
package com.example.tecktrove.util; import java.util.Calendar; /** * Αμετάβλητη κλάση για τη διαχείριση ημερομηνιών * αγνοώντας την ώρα. * */ public class SimpleCalendar implements Comparable<SimpleCalendar> { private static final long MILLIS_PER_DAY = 86400000; private Calendar date; /** * Κατασκευάζει μία ημερομηνία με βάση το έτος, * το μήνα και την ημέρα του μήνα. * @param year Το έτος * @param month Ο μήνας από 1 έως 12 * @param day Η ημέρα του μήνα */ public SimpleCalendar(int year, int month, int day) { date = Calendar.getInstance(); date.set(year, month - 1, day); trimToDays(this.date); } /** * Κατασκευάζει μία ημερομηνία λαμβάνοντας. * ως παράμετρο αντικείμενο της κλάσης {@code Calendar} * @param date Η ημερομηνία */ public SimpleCalendar(Calendar date) { this.date = Calendar.getInstance(); this.date.setTimeInMillis(date.getTimeInMillis()); trimToDays(this.date); } private void trimToDays(Calendar javaDate) { javaDate.set(Calendar.HOUR_OF_DAY, 0); javaDate.set(Calendar.MINUTE, 0); javaDate.set(Calendar.SECOND, 0); javaDate.set(Calendar.MILLISECOND, 0); } /** * Η διάρκεια σε ημέρες σε σχέση με μία άλλη ημερομηνία. * @param other Η δεύτερη ημερομηνία για την οποία * υπολογίζεται η διάρκεια * @return Ο αριθμός των ημερών. Θετικός αριθμός ημερών * σημαίνει ότι η άλλη ημερομηνία είναι μεταγενέστερη, * ενώ αρνητικός το αντίθετο. */ public long durationInDays(SimpleCalendar other) { long timeDiff = other.date.getTimeInMillis() - date.getTimeInMillis(); return timeDiff / MILLIS_PER_DAY; } /** * Επιστρέφει το έτος της ημερομηνίας. * @return Το έτος */ public int getYear() { return date.get(Calendar.YEAR); } /** * Επιστρέφει το μήνα της ημερομηνίας (1-12). * @return Ο μήνας */ public int getMonth() { return date.get(Calendar.MONTH) + 1; } /** * Επιστρέφει την ημέρα σε του μήνα. * @return Η ημέρα του μήνα */ public int getDayOfMonth() { return date.get(Calendar.DAY_OF_MONTH); } /** * Επιστρέφει την ημέρα της εβδομάδας της ημερομηνίας. * @return Η ημέρα της εβδομάδας */ public int getDayOfWeek() { return date.get(Calendar.DAY_OF_WEEK); } /** * Επιστρέφει {@code true} αν η ημερομηνία είναι. * μεταγενέστερη μίας άλλης ημερομηνίας * @param other Η άλλη ημερομηνία * @return {@code true} αν η ημερομηνία είναι * μεταγενέστερη της άλλης */ public boolean after(SimpleCalendar other) { if (equals(other)) { return false; } return date.after(other.date); } /** * Επιστρέφει {@code true} αν η ημερομηνία είναι. * προγενέστερη μίας άλλης ημερομηνίας * @param other Η άλλη ημερομηνία * @return {@code true} αν η ημερομηνία είναι * προγενέστερη της άλλης */ public boolean before(SimpleCalendar other) { if (equals(other)) { return false; } return date.before(other.date); } /** * Επιστρέφει μία ημερομηνία προσθέτοντας κάποιο * αριθμό ημερών. * @param days Ο αριθμός των ημερών που προστίθενται * @return Η νέα ημερομηνία */ public SimpleCalendar addDays(int days) { Calendar newDate = Calendar.getInstance(); newDate.setTimeInMillis(date.getTimeInMillis()); newDate.add(Calendar.DAY_OF_MONTH, days); return new SimpleCalendar(newDate); } /** * Επιστρέφει μία ημερομηνία τύπου {@code Calendar}. * @return Η ημερομηνία */ public Calendar getJavaCalendar() { Calendar javaCalendar = Calendar.getInstance(); javaCalendar.setTimeInMillis(date.getTimeInMillis()); trimToDays(javaCalendar); return javaCalendar; } /** * {@inheritDoc} */ public int compareTo(SimpleCalendar other) { return date.compareTo(other.date); } /** * Η ισότητα βασίζεται σε όλα τα πεδία της διεύθυνσης. * @param other Το άλλο αντικείμενο προς έλεγχο * @return {@code true} αν τα αντικείμενα είναι ίσα */ @Override public boolean equals(Object other) { if (other == null) { return false; } if (this == other) { return true; } if (!(other instanceof SimpleCalendar)) { return false; } SimpleCalendar theDate = (SimpleCalendar) other; if (getYear() != theDate.getYear()) { return false; } if (getMonth() != theDate.getMonth()) { return false; } if (getDayOfMonth() != theDate.getDayOfMonth()) { return false; } return true; } /** * Το HashCode μίας ημερομηνίας * @return Το HashCode */ @Override public int hashCode() { return date == null ? 0 : date.hashCode(); } }
MariaSchoinaki/TechTrove-App
app/src/main/java/com/example/tecktrove/util/SimpleCalendar.java
2,161
/** * Η ισότητα βασίζεται σε όλα τα πεδία της διεύθυνσης. * @param other Το άλλο αντικείμενο προς έλεγχο * @return {@code true} αν τα αντικείμενα είναι ίσα */
block_comment
el
package com.example.tecktrove.util; import java.util.Calendar; /** * Αμετάβλητη κλάση για τη διαχείριση ημερομηνιών * αγνοώντας την ώρα. * */ public class SimpleCalendar implements Comparable<SimpleCalendar> { private static final long MILLIS_PER_DAY = 86400000; private Calendar date; /** * Κατασκευάζει μία ημερομηνία με βάση το έτος, * το μήνα και την ημέρα του μήνα. * @param year Το έτος * @param month Ο μήνας από 1 έως 12 * @param day Η ημέρα του μήνα */ public SimpleCalendar(int year, int month, int day) { date = Calendar.getInstance(); date.set(year, month - 1, day); trimToDays(this.date); } /** * Κατασκευάζει μία ημερομηνία λαμβάνοντας. * ως παράμετρο αντικείμενο της κλάσης {@code Calendar} * @param date Η ημερομηνία */ public SimpleCalendar(Calendar date) { this.date = Calendar.getInstance(); this.date.setTimeInMillis(date.getTimeInMillis()); trimToDays(this.date); } private void trimToDays(Calendar javaDate) { javaDate.set(Calendar.HOUR_OF_DAY, 0); javaDate.set(Calendar.MINUTE, 0); javaDate.set(Calendar.SECOND, 0); javaDate.set(Calendar.MILLISECOND, 0); } /** * Η διάρκεια σε ημέρες σε σχέση με μία άλλη ημερομηνία. * @param other Η δεύτερη ημερομηνία για την οποία * υπολογίζεται η διάρκεια * @return Ο αριθμός των ημερών. Θετικός αριθμός ημερών * σημαίνει ότι η άλλη ημερομηνία είναι μεταγενέστερη, * ενώ αρνητικός το αντίθετο. */ public long durationInDays(SimpleCalendar other) { long timeDiff = other.date.getTimeInMillis() - date.getTimeInMillis(); return timeDiff / MILLIS_PER_DAY; } /** * Επιστρέφει το έτος της ημερομηνίας. * @return Το έτος */ public int getYear() { return date.get(Calendar.YEAR); } /** * Επιστρέφει το μήνα της ημερομηνίας (1-12). * @return Ο μήνας */ public int getMonth() { return date.get(Calendar.MONTH) + 1; } /** * Επιστρέφει την ημέρα σε του μήνα. * @return Η ημέρα του μήνα */ public int getDayOfMonth() { return date.get(Calendar.DAY_OF_MONTH); } /** * Επιστρέφει την ημέρα της εβδομάδας της ημερομηνίας. * @return Η ημέρα της εβδομάδας */ public int getDayOfWeek() { return date.get(Calendar.DAY_OF_WEEK); } /** * Επιστρέφει {@code true} αν η ημερομηνία είναι. * μεταγενέστερη μίας άλλης ημερομηνίας * @param other Η άλλη ημερομηνία * @return {@code true} αν η ημερομηνία είναι * μεταγενέστερη της άλλης */ public boolean after(SimpleCalendar other) { if (equals(other)) { return false; } return date.after(other.date); } /** * Επιστρέφει {@code true} αν η ημερομηνία είναι. * προγενέστερη μίας άλλης ημερομηνίας * @param other Η άλλη ημερομηνία * @return {@code true} αν η ημερομηνία είναι * προγενέστερη της άλλης */ public boolean before(SimpleCalendar other) { if (equals(other)) { return false; } return date.before(other.date); } /** * Επιστρέφει μία ημερομηνία προσθέτοντας κάποιο * αριθμό ημερών. * @param days Ο αριθμός των ημερών που προστίθενται * @return Η νέα ημερομηνία */ public SimpleCalendar addDays(int days) { Calendar newDate = Calendar.getInstance(); newDate.setTimeInMillis(date.getTimeInMillis()); newDate.add(Calendar.DAY_OF_MONTH, days); return new SimpleCalendar(newDate); } /** * Επιστρέφει μία ημερομηνία τύπου {@code Calendar}. * @return Η ημερομηνία */ public Calendar getJavaCalendar() { Calendar javaCalendar = Calendar.getInstance(); javaCalendar.setTimeInMillis(date.getTimeInMillis()); trimToDays(javaCalendar); return javaCalendar; } /** * {@inheritDoc} */ public int compareTo(SimpleCalendar other) { return date.compareTo(other.date); } /** * Η ισότητα βασίζεται<SUF>*/ @Override public boolean equals(Object other) { if (other == null) { return false; } if (this == other) { return true; } if (!(other instanceof SimpleCalendar)) { return false; } SimpleCalendar theDate = (SimpleCalendar) other; if (getYear() != theDate.getYear()) { return false; } if (getMonth() != theDate.getMonth()) { return false; } if (getDayOfMonth() != theDate.getDayOfMonth()) { return false; } return true; } /** * Το HashCode μίας ημερομηνίας * @return Το HashCode */ @Override public int hashCode() { return date == null ? 0 : date.hashCode(); } }
1867_9
//package gr.aueb.cf.ch10; // //import java.util.ArrayList; // //public class CryptoApp { // // public static void main(String[] args) { // final int KEY = 300; // String s = "Coding"; // // String encrypted = encrypt(s, KEY).toString(); // το tostring μετατρέπει τα στοιχεία της λίστας σε string // System.out.println(encrypted); // // String decrypted = decrypt(encrypt(s, KEY), KEY).toString(); // System.out.println(decrypted); // } // // public static ArrayList<Integer> encrypt(String s, int key){ // ArrayList<Integer> encrypted = new ArrayList<>(); // char ch; // int i; // // int prev = cipher(s.charAt(0), -1, key); // encrypted.add(prev); // // // //το string εισόδου τελειώνει με ένα #. // //θα μπορούσε και με μία αέναη for --> for(;;) // i = 1; // while((ch = s.charAt(i)) != '#') { // // και διαβάζω και συγκρίνω ταυτόχρονα // encrypted.add(cipher(ch, prev, key)); // prev = cipher(ch, prev , key); // i++; // } // encrypted.add(-1); // return encrypted; // } // // public static ArrayList<Character> decrypt(ArrayList<Integer> encrypted, int key){ // ArrayList<Character> decrypted = new ArrayList<>(); // int token; // int i; // int prevToken; // // //για να διαβάσω κάνω .get // prevToken = decipher(encrypted.get(0), -1, key); // decrypted.add((char) prevToken); // autocast σε wrapper κλάση // // i = 1; // while((token = encrypted.get(i)) != -1){ // decrypted.add(decipher(token, prevToken, key)); // prevToken = token; // i++; // } // // return decrypted; // } // // παίρνει έναν χαρακτήρα και τον επιστρέφει κρυπτογραφημένο ώσ int // public static int cipher(char ch, int prev, int key){ // if (prev == -1) return ch; // return(ch + prev) % key; // } // // public static char decipher(int cipher, int prev, int key){ // int de; // if( prev == -1) return (char) cipher; //return ton cipher metatr;epontas to se char // // de = (cipher - prev + key) % key; // return (char) de; // } //}
Mariamakr/codingfactory23a
src/gr/aueb/cf/ch10/CryptoApp.java
816
// //το string εισόδου τελειώνει με ένα #.
line_comment
el
//package gr.aueb.cf.ch10; // //import java.util.ArrayList; // //public class CryptoApp { // // public static void main(String[] args) { // final int KEY = 300; // String s = "Coding"; // // String encrypted = encrypt(s, KEY).toString(); // το tostring μετατρέπει τα στοιχεία της λίστας σε string // System.out.println(encrypted); // // String decrypted = decrypt(encrypt(s, KEY), KEY).toString(); // System.out.println(decrypted); // } // // public static ArrayList<Integer> encrypt(String s, int key){ // ArrayList<Integer> encrypted = new ArrayList<>(); // char ch; // int i; // // int prev = cipher(s.charAt(0), -1, key); // encrypted.add(prev); // // // //το string<SUF> // //θα μπορούσε και με μία αέναη for --> for(;;) // i = 1; // while((ch = s.charAt(i)) != '#') { // // και διαβάζω και συγκρίνω ταυτόχρονα // encrypted.add(cipher(ch, prev, key)); // prev = cipher(ch, prev , key); // i++; // } // encrypted.add(-1); // return encrypted; // } // // public static ArrayList<Character> decrypt(ArrayList<Integer> encrypted, int key){ // ArrayList<Character> decrypted = new ArrayList<>(); // int token; // int i; // int prevToken; // // //για να διαβάσω κάνω .get // prevToken = decipher(encrypted.get(0), -1, key); // decrypted.add((char) prevToken); // autocast σε wrapper κλάση // // i = 1; // while((token = encrypted.get(i)) != -1){ // decrypted.add(decipher(token, prevToken, key)); // prevToken = token; // i++; // } // // return decrypted; // } // // παίρνει έναν χαρακτήρα και τον επιστρέφει κρυπτογραφημένο ώσ int // public static int cipher(char ch, int prev, int key){ // if (prev == -1) return ch; // return(ch + prev) % key; // } // // public static char decipher(int cipher, int prev, int key){ // int de; // if( prev == -1) return (char) cipher; //return ton cipher metatr;epontas to se char // // de = (cipher - prev + key) % key; // return (char) de; // } //}
1939_1
package com.ethelontismos; import java.lang.StringBuilder; import java.util.List; /** * Σύντομη περιγραφή κλάσης: * Η κλάση περιέχει μία μόνο μέθοδο για την δημιουργία ενός Prompt. * * Αναλυτική περιγραφή: * Μέσω ενός String Builder δημιουργώ το prompt-μήνυμα για την τροφοδότηση του ChatGTP 3.5, * ώστε αυτό να προτείνει στο χρήστη τις κατάλληλες δράσεις βάση των ενδιαφερόντων του. */ public class ChatDbKeyword { /** * Εκτενής επεξήγηση της μεθόδου: * Δημιουργία ενός μηνύματος για το ChatGPT μέσω ενός String Builder(sb) το οποίο περιέχει: * τα περιεχόμενα της DB με τις εθελοντικές δράσεις σαν λίστα από Strings, * το targetKeyword που είναι το String με τα ενδιαφέροντα του εκάστοτε χρήστη * και το όνομα του χρήστη. * Επιπλέον, τo sb περιέχει και μηνύματα προτροπής στο Chat όπως: * κάνε match τα δεδομένα της λίστας με το keyword, * γράψε κείμενο που προτείνει στον χρήστη με όνομα +name τις σωστά - αντιστοιχισμένες δράσεις. */ public static String promptBuilder(String targetkeyword,List<VolunteerAction> allActions,String name) { StringBuilder sb = new StringBuilder(); String x = (""); try { sb.append("Θα σου δώσω μία λίστα με δεδομένα,τα οποία θέλω να αντιστοιχίσεις με αυτό το keyword και να κρατήσεις μόνο όσα δεδομένα ταιριάζουν"); sb.append(targetkeyword); sb.append("\n" + "Αυτά είναι τα δεδομένα: "); for (VolunteerAction var : allActions) { sb.append(var).append("\n"); } sb.append("\n Γράψε ένα κείμενο που θα προτείνει στον χρήστη με όνομα: " +name +"τις εθελοντικές δράσεις που θα βρείς απο την αντιστοίχιση που θα κάνεις πιό πάνω"); return sb.toString(); } catch (Exception e) { System.out.println(e.getMessage()); return x; } } }
MariliaGait/TeaMET
src/main/java/com/ethelontismos/ChatDbKeyword.java
1,059
/** * Εκτενής επεξήγηση της μεθόδου: * Δημιουργία ενός μηνύματος για το ChatGPT μέσω ενός String Builder(sb) το οποίο περιέχει: * τα περιεχόμενα της DB με τις εθελοντικές δράσεις σαν λίστα από Strings, * το targetKeyword που είναι το String με τα ενδιαφέροντα του εκάστοτε χρήστη * και το όνομα του χρήστη. * Επιπλέον, τo sb περιέχει και μηνύματα προτροπής στο Chat όπως: * κάνε match τα δεδομένα της λίστας με το keyword, * γράψε κείμενο που προτείνει στον χρήστη με όνομα +name τις σωστά - αντιστοιχισμένες δράσεις. */
block_comment
el
package com.ethelontismos; import java.lang.StringBuilder; import java.util.List; /** * Σύντομη περιγραφή κλάσης: * Η κλάση περιέχει μία μόνο μέθοδο για την δημιουργία ενός Prompt. * * Αναλυτική περιγραφή: * Μέσω ενός String Builder δημιουργώ το prompt-μήνυμα για την τροφοδότηση του ChatGTP 3.5, * ώστε αυτό να προτείνει στο χρήστη τις κατάλληλες δράσεις βάση των ενδιαφερόντων του. */ public class ChatDbKeyword { /** * Εκτενής επεξήγηση της<SUF>*/ public static String promptBuilder(String targetkeyword,List<VolunteerAction> allActions,String name) { StringBuilder sb = new StringBuilder(); String x = (""); try { sb.append("Θα σου δώσω μία λίστα με δεδομένα,τα οποία θέλω να αντιστοιχίσεις με αυτό το keyword και να κρατήσεις μόνο όσα δεδομένα ταιριάζουν"); sb.append(targetkeyword); sb.append("\n" + "Αυτά είναι τα δεδομένα: "); for (VolunteerAction var : allActions) { sb.append(var).append("\n"); } sb.append("\n Γράψε ένα κείμενο που θα προτείνει στον χρήστη με όνομα: " +name +"τις εθελοντικές δράσεις που θα βρείς απο την αντιστοίχιση που θα κάνεις πιό πάνω"); return sb.toString(); } catch (Exception e) { System.out.println(e.getMessage()); return x; } } }
3997_3
/* This file is part of "Ηλεκτρονική Διακίνηση Εγγράφων Δήμου Αθηναίων(ΗΔΕ) Documents' Digital Handling/Digital Signature of Municipality of Athens(DDHDS)". Complementary service to allow digital signing from browser Copyright (C) <2018> Municipality Of Athens Service Author Panagiotis Skarvelis [email protected] This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. <authors' emails : [email protected], [email protected], [email protected]> <authors' address : Λιοσίων 22, Αθήνα - Ελλάδα, ΤΚ:10438 ---- Liosion 22, Athens - Greeece, PC:10438> */ package moa.ds.service.athens.gr; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.Security; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import java.util.Objects; import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.bouncycastle.jce.provider.BouncyCastleProvider; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.Phrase; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.AcroFields; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.ColumnText; import com.itextpdf.text.pdf.PdfDate; import com.itextpdf.text.pdf.PdfName; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfSignature; import com.itextpdf.text.pdf.PdfSignatureAppearance; import com.itextpdf.text.pdf.PdfStamper; import com.itextpdf.text.pdf.security.DigestAlgorithms; import com.itextpdf.text.pdf.security.ExternalDigest; import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard; import com.itextpdf.text.pdf.security.PdfPKCS7; import moa.ds.service.athens.gr.radweriel; import moa.ds.service.athens.gr.MOASSUtils; import moa.ds.service.athens.gr.MOASSConfig; import java.lang.String; /** * Servlet implementation class preSign */ @WebServlet( description = "Get PDF from radweriel uuid and returns hash", urlPatterns = { "/preSign" }, initParams = { @WebInitParam(name = "reason", value = "", description = "reason to sign"), @WebInitParam(name = "signers", value = "", description = "signers of pdf file"), @WebInitParam(name = "uuid", value = "", description = "uuid of pdf file"), @WebInitParam(name = "taskUUID", value = "", description = "uuid of runing task"), @WebInitParam(name = "loggedUser", value = "", description = "the bonita logged user") }) public class preSign extends HttpServlet { private static final long serialVersionUID = 1L; private static X509Certificate cer = null; private static Calendar cal = null; private static String reason = null; private static String uuid = null; private static String taskUUID = null; private static String loggedUser = null; private static String crtEmail = null; private static Integer sigpage = 1; private static Rectangle size = null; private static PdfSignatureAppearance sap=null; private static PdfStamper stamper = null; private static PdfReader reader = null; private static ByteArrayOutputStream baos = null; private static float signHeight=50; private static String signers[]=null; static { Security.addProvider(new BouncyCastleProvider()); } /** * @see HttpServlet#HttpServlet() */ public preSign() { super(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private void setPlaceHolders(int numOfSignatures) throws DocumentException, IOException{ float offset=20; float pageHeight = (numOfSignatures*signHeight)+offset; stamper.insertPage(sigpage, new Rectangle(0, 0, size.getWidth(),pageHeight)); String path = getServletContext().getRealPath("/assets/arialuni.ttf"); BaseFont fonty = BaseFont.createFont(path, BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED); fonty.setSubset(true);//Όλες οι θέσεις των υπογραφών πρέπει να συμπληρωθούν απο τους υπογράφοντες ώστε το έγγραφο να είναι έγκυρο Phrase myWarning = new Phrase("----- Θέσεις Υπογραφών -----", new Font(fonty,10)); ColumnText.showTextAligned(stamper.getOverContent(sigpage),Element.ALIGN_LEFT, myWarning, 0, pageHeight-(offset/2), 0); for (int i=1; i<=numOfSignatures; i++ ) { //TODO na vazo ta cn auton pou prepei na ypograpsoun //TODO on reverse order stamper.addSignature("sig-"+i, sigpage, 0,((signHeight)*(i-1)) , size.getWidth(), (signHeight*i)); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); int numOfSignatures=0; try{ signers = request.getParameter("signers").split(","); numOfSignatures=signers.length; if (numOfSignatures<1||numOfSignatures>6) throw new RuntimeException("λάθος υπογράφοντες"); cer = MOASSUtils.getCer(request.getParameter("cer").getBytes("UTF-8")); reason = request.getParameter("reason"); if (reason=="") reason="signed"; uuid = request.getParameter("uuid").trim(); taskUUID = request.getParameter("taskUUID").trim(); loggedUser = request.getParameter("loggedUser").trim(); } catch (Exception e) { response.getWriter().println("{\"error\":\" Πρόβλημα στις παραμέτρους "+e.getMessage()+"\"}"); return; } try { cal = Calendar.getInstance(); //cal.set(1969, 3, 1,5, 0,0); //cal.setTimeInMillis(5000); baos = new ByteArrayOutputStream(); reader = new PdfReader(radweriel.getDocByID("workspace://SpacesStore/"+uuid)); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // AUTHORIZE CHECKS // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Elenxos an o katoxos tou certificate einai o idios me auton pou exei kanei login crtEmail=MOASSUtils.getCertificateEmail(cer); String userUID= galgallin.getUIDbyEmail(crtEmail); if (!Objects.equals(userUID,loggedUser)) throw new RuntimeException("Δεν έχετε δικαίωμα υπογραφής σε αυτό το βήμα"); //Elegxos an o logged user paei na ypograpsei eggrafo se site pou anikei //String UserOU = galgallin.getOUbyUID(userUID).replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", ""); String UserOU = MOASSUtils.setOuInAppropriateFormat(userUID); String site = radweriel.siteByDocUUID("workspace://SpacesStore/"+uuid).replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", ""); //TODO Dirty workarrounds FIX!!!! /* boolean isProtocolMember = galgallin.checkMembershipInGroupByUID(loggedUser, "protocol", "ou=groups,ou=DIAKINISI_EGGRAFON,ou=APPLICATIONS"); if (!isProtocolMember && !UserOU.equals("ΓΕΝΙΚΟΣ ΓΡΑΜΜΑΤΕΑΣ".replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", "")) && !UserOU.equals("ΔΗΜΑΡΧΟΣ".replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", "")) && !UserOU.equals("Αντιδήμαρχος".replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", "")) && !UserOU.equals("Εντεταλμένος Σύμβουλος".replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", "")) && !UserOU.equals("ΓΕΝΙΚΟΣ ΔΙΕΥΘΥΝΤΗΣ".replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", ""))){ String site = radweriel.siteByDocUUID("workspace://SpacesStore/"+uuid).replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", ""); if (!Objects.equals(site,UserOU)) throw new RuntimeException("1 Δέν επιτρέπεται η υπογραφή, το λάθος καταγράφηκε και θα χρησιμοποιηθεί προς διώξή σας αν διαπιστωθεί εσκεμμένη προσπάθεια παραβίασης"); } */ if(!MOASSUtils.transcendPersonRole(userUID)){ if (!Objects.equals(site,UserOU)) throw new RuntimeException("1 Δέν επιτρέπεται η υπογραφή, το λάθος καταγράφηκε και θα χρησιμοποιηθεί προς διώξή σας αν διαπιστωθεί εσκεμμένη προσπάθεια παραβίασης"); } //elenxos an o xristis einai allowed sto sygkekrimeno taskUUID if (!thales.cantitateIsValid(taskUUID,loggedUser)) throw new RuntimeException("2 Δέν επιτρέπεται η υπογραφή, το λάθος καταγράφηκε και θα χρησιμοποιηθεί προς διώξή σας αν διαπιστωθεί εσκεμμένη προσπάθεια παραβίασης"); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Stoixeia tou xrhsth String certInfo = cer.getSubjectX500Principal().getName(); String creator = certInfo.substring(certInfo.indexOf("CN=") + 3,certInfo.indexOf(",OU", certInfo.indexOf("CN=") + 3)); //System.out.println(reader.getCertificationLevel()); //TODO isos prepei na to koitao AcroFields fields = reader.getAcroFields(); ArrayList<String> names = fields.getSignatureNames(); int sigs=names.size(); if ((sigs+1)>numOfSignatures) throw new RuntimeException("Έχουν πραγματοποιηθεί όλες οι υπογραφές"); //if (MOASSUtils.isSignedBy(fields,loggedUser)) throw new RuntimeException("Έχετε ήδη υπογράψει"); if (!Objects.equals(userUID,signers[sigs])) throw new RuntimeException("Δεν αναμένεται υπογραφή απο εσάς σε αύτο το βήμα"); if (sigs==0) { //Create signatures placeholders in new created page stamper = new PdfStamper(reader,baos); Map<String, String> info = reader.getInfo(); //info.put("Title", "Hello World"); //info.put("Subject", "Hello World with changed metadata"); //info.put("Keywords", signers); info.put("Creator", "MOASS signer"); info.put("Author", creator); info.put("ModDate", cal.getTime().toString()); info.put("CreationDate", cal.getTime().toString()); //info.put("CreationDate", "D:20120816122649+02'00'"); stamper.setMoreInfo(info); //create new page to hold signatures int pages =reader.getNumberOfPages(); size = reader.getPageSize(1); sigpage=pages+1; setPlaceHolders(numOfSignatures); stamper.close(); reader.close(); //Create a copy from modified PDF with signature placeholders PdfReader copy = new PdfReader(new ByteArrayInputStream(baos.toByteArray())); baos.reset();//Reset stream to reuse it stamper = PdfStamper.createSignature(copy, baos, '7', new File("/tmp"),false); sap = stamper.getSignatureAppearance(); sap.setVisibleSignature("sig-1"); //H proth ypografh einai gia to certificate //CERTIFIED_NO_CHANGES_ALLOWED Gia eggrafa pou den dexontai alles ypografes.TODO Na do ta locks gia thn teleutea ypografh sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS); } else{ stamper = PdfStamper.createSignature(reader, baos, '7', new File("/tmp"),true); sap = stamper.getSignatureAppearance(); // sap.setVisibleSignature(new Rectangle(0, 0, size.getWidth(), 200), sigpage, "sig1"); sap.setVisibleSignature("sig-"+(sigs+1));//TODO select based on logged user sap.setCertificationLevel(PdfSignatureAppearance.NOT_CERTIFIED); } //set Font String path = getServletContext().getRealPath(MOASSConfig.getProperty("font")); BaseFont fonty = BaseFont.createFont(path, BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED); fonty.setSubset(true); Font sapFont = new Font(fonty,8); sap.setLayer2Font(sapFont); sap.setCertificate(cer); sap.setSignDate(cal); sap.setReason(reason); sap.setLocation("Athens"); sap.setSignatureCreator(creator); sap.setContact("Municipality of Athens"); //set the dic PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED); dic.setReason(sap.getReason()); dic.setLocation(sap.getLocation()); dic.setName(creator); dic.setSignatureCreator(sap.getSignatureCreator()); dic.setContact(sap.getContact()); dic.setDate(new PdfDate(sap.getSignDate())); dic.setCert(cer.getEncoded()); sap.setCryptoDictionary(dic); HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>(); int estimatedSize =16384; exc.put(PdfName.CONTENTS, new Integer(estimatedSize * 2 + 2));// sap.preClose(exc); ExternalDigest externalDigest = new ExternalDigest() { public MessageDigest getMessageDigest(String hashAlgorithm) throws GeneralSecurityException { return DigestAlgorithms.getMessageDigest(hashAlgorithm, null); } }; PdfPKCS7 sgn = new PdfPKCS7(null, new Certificate[] { cer }, "SHA256", null, externalDigest, false); InputStream data = sap.getRangeStream(); byte hash[] = DigestAlgorithms.digest(data,externalDigest.getMessageDigest("SHA256")); byte[] aab = sgn.getAuthenticatedAttributeBytes(hash, cal, null, null, CryptoStandard.CMS); byte[] sh = MessageDigest.getInstance("SHA256", "BC").digest(aab); HttpSession session = request.getSession(true); session.setAttribute("sgn", sgn); session.setAttribute("hash", hash); session.setAttribute("cal", cal); session.setAttribute("sap", sap); session.setAttribute("baos", baos); session.setAttribute("uuid", uuid); String HASH2SIGN = new String(String.format("%064x", new java.math.BigInteger(1, sh))); response.getWriter().println("{\"HASH2SIGN\":\""+HASH2SIGN+"\"}"); } catch (DocumentException e) { throw new IOException(e); } catch (GeneralSecurityException e) { throw new IOException(e); } catch (Exception e) { System.out.println(e); //e.printStackTrace(); response.getWriter().println("{\"error\":\""+e.getMessage()+"\"}"); } } }
MunicipalityOfAthens/MOASS
src/moa/ds/service/athens/gr/preSign.java
4,749
//Όλες οι θέσεις των υπογραφών πρέπει να συμπληρωθούν απο τους υπογράφοντες ώστε το έγγραφο να είναι έγκυρο
line_comment
el
/* This file is part of "Ηλεκτρονική Διακίνηση Εγγράφων Δήμου Αθηναίων(ΗΔΕ) Documents' Digital Handling/Digital Signature of Municipality of Athens(DDHDS)". Complementary service to allow digital signing from browser Copyright (C) <2018> Municipality Of Athens Service Author Panagiotis Skarvelis [email protected] This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. <authors' emails : [email protected], [email protected], [email protected]> <authors' address : Λιοσίων 22, Αθήνα - Ελλάδα, ΤΚ:10438 ---- Liosion 22, Athens - Greeece, PC:10438> */ package moa.ds.service.athens.gr; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.Security; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import java.util.Objects; import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.bouncycastle.jce.provider.BouncyCastleProvider; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.Phrase; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.AcroFields; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.ColumnText; import com.itextpdf.text.pdf.PdfDate; import com.itextpdf.text.pdf.PdfName; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfSignature; import com.itextpdf.text.pdf.PdfSignatureAppearance; import com.itextpdf.text.pdf.PdfStamper; import com.itextpdf.text.pdf.security.DigestAlgorithms; import com.itextpdf.text.pdf.security.ExternalDigest; import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard; import com.itextpdf.text.pdf.security.PdfPKCS7; import moa.ds.service.athens.gr.radweriel; import moa.ds.service.athens.gr.MOASSUtils; import moa.ds.service.athens.gr.MOASSConfig; import java.lang.String; /** * Servlet implementation class preSign */ @WebServlet( description = "Get PDF from radweriel uuid and returns hash", urlPatterns = { "/preSign" }, initParams = { @WebInitParam(name = "reason", value = "", description = "reason to sign"), @WebInitParam(name = "signers", value = "", description = "signers of pdf file"), @WebInitParam(name = "uuid", value = "", description = "uuid of pdf file"), @WebInitParam(name = "taskUUID", value = "", description = "uuid of runing task"), @WebInitParam(name = "loggedUser", value = "", description = "the bonita logged user") }) public class preSign extends HttpServlet { private static final long serialVersionUID = 1L; private static X509Certificate cer = null; private static Calendar cal = null; private static String reason = null; private static String uuid = null; private static String taskUUID = null; private static String loggedUser = null; private static String crtEmail = null; private static Integer sigpage = 1; private static Rectangle size = null; private static PdfSignatureAppearance sap=null; private static PdfStamper stamper = null; private static PdfReader reader = null; private static ByteArrayOutputStream baos = null; private static float signHeight=50; private static String signers[]=null; static { Security.addProvider(new BouncyCastleProvider()); } /** * @see HttpServlet#HttpServlet() */ public preSign() { super(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private void setPlaceHolders(int numOfSignatures) throws DocumentException, IOException{ float offset=20; float pageHeight = (numOfSignatures*signHeight)+offset; stamper.insertPage(sigpage, new Rectangle(0, 0, size.getWidth(),pageHeight)); String path = getServletContext().getRealPath("/assets/arialuni.ttf"); BaseFont fonty = BaseFont.createFont(path, BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED); fonty.setSubset(true);//Όλες οι<SUF> Phrase myWarning = new Phrase("----- Θέσεις Υπογραφών -----", new Font(fonty,10)); ColumnText.showTextAligned(stamper.getOverContent(sigpage),Element.ALIGN_LEFT, myWarning, 0, pageHeight-(offset/2), 0); for (int i=1; i<=numOfSignatures; i++ ) { //TODO na vazo ta cn auton pou prepei na ypograpsoun //TODO on reverse order stamper.addSignature("sig-"+i, sigpage, 0,((signHeight)*(i-1)) , size.getWidth(), (signHeight*i)); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); int numOfSignatures=0; try{ signers = request.getParameter("signers").split(","); numOfSignatures=signers.length; if (numOfSignatures<1||numOfSignatures>6) throw new RuntimeException("λάθος υπογράφοντες"); cer = MOASSUtils.getCer(request.getParameter("cer").getBytes("UTF-8")); reason = request.getParameter("reason"); if (reason=="") reason="signed"; uuid = request.getParameter("uuid").trim(); taskUUID = request.getParameter("taskUUID").trim(); loggedUser = request.getParameter("loggedUser").trim(); } catch (Exception e) { response.getWriter().println("{\"error\":\" Πρόβλημα στις παραμέτρους "+e.getMessage()+"\"}"); return; } try { cal = Calendar.getInstance(); //cal.set(1969, 3, 1,5, 0,0); //cal.setTimeInMillis(5000); baos = new ByteArrayOutputStream(); reader = new PdfReader(radweriel.getDocByID("workspace://SpacesStore/"+uuid)); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // AUTHORIZE CHECKS // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Elenxos an o katoxos tou certificate einai o idios me auton pou exei kanei login crtEmail=MOASSUtils.getCertificateEmail(cer); String userUID= galgallin.getUIDbyEmail(crtEmail); if (!Objects.equals(userUID,loggedUser)) throw new RuntimeException("Δεν έχετε δικαίωμα υπογραφής σε αυτό το βήμα"); //Elegxos an o logged user paei na ypograpsei eggrafo se site pou anikei //String UserOU = galgallin.getOUbyUID(userUID).replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", ""); String UserOU = MOASSUtils.setOuInAppropriateFormat(userUID); String site = radweriel.siteByDocUUID("workspace://SpacesStore/"+uuid).replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", ""); //TODO Dirty workarrounds FIX!!!! /* boolean isProtocolMember = galgallin.checkMembershipInGroupByUID(loggedUser, "protocol", "ou=groups,ou=DIAKINISI_EGGRAFON,ou=APPLICATIONS"); if (!isProtocolMember && !UserOU.equals("ΓΕΝΙΚΟΣ ΓΡΑΜΜΑΤΕΑΣ".replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", "")) && !UserOU.equals("ΔΗΜΑΡΧΟΣ".replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", "")) && !UserOU.equals("Αντιδήμαρχος".replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", "")) && !UserOU.equals("Εντεταλμένος Σύμβουλος".replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", "")) && !UserOU.equals("ΓΕΝΙΚΟΣ ΔΙΕΥΘΥΝΤΗΣ".replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", ""))){ String site = radweriel.siteByDocUUID("workspace://SpacesStore/"+uuid).replaceAll("[ /s\\/,.!@#$%^&*()-+_=]", ""); if (!Objects.equals(site,UserOU)) throw new RuntimeException("1 Δέν επιτρέπεται η υπογραφή, το λάθος καταγράφηκε και θα χρησιμοποιηθεί προς διώξή σας αν διαπιστωθεί εσκεμμένη προσπάθεια παραβίασης"); } */ if(!MOASSUtils.transcendPersonRole(userUID)){ if (!Objects.equals(site,UserOU)) throw new RuntimeException("1 Δέν επιτρέπεται η υπογραφή, το λάθος καταγράφηκε και θα χρησιμοποιηθεί προς διώξή σας αν διαπιστωθεί εσκεμμένη προσπάθεια παραβίασης"); } //elenxos an o xristis einai allowed sto sygkekrimeno taskUUID if (!thales.cantitateIsValid(taskUUID,loggedUser)) throw new RuntimeException("2 Δέν επιτρέπεται η υπογραφή, το λάθος καταγράφηκε και θα χρησιμοποιηθεί προς διώξή σας αν διαπιστωθεί εσκεμμένη προσπάθεια παραβίασης"); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Stoixeia tou xrhsth String certInfo = cer.getSubjectX500Principal().getName(); String creator = certInfo.substring(certInfo.indexOf("CN=") + 3,certInfo.indexOf(",OU", certInfo.indexOf("CN=") + 3)); //System.out.println(reader.getCertificationLevel()); //TODO isos prepei na to koitao AcroFields fields = reader.getAcroFields(); ArrayList<String> names = fields.getSignatureNames(); int sigs=names.size(); if ((sigs+1)>numOfSignatures) throw new RuntimeException("Έχουν πραγματοποιηθεί όλες οι υπογραφές"); //if (MOASSUtils.isSignedBy(fields,loggedUser)) throw new RuntimeException("Έχετε ήδη υπογράψει"); if (!Objects.equals(userUID,signers[sigs])) throw new RuntimeException("Δεν αναμένεται υπογραφή απο εσάς σε αύτο το βήμα"); if (sigs==0) { //Create signatures placeholders in new created page stamper = new PdfStamper(reader,baos); Map<String, String> info = reader.getInfo(); //info.put("Title", "Hello World"); //info.put("Subject", "Hello World with changed metadata"); //info.put("Keywords", signers); info.put("Creator", "MOASS signer"); info.put("Author", creator); info.put("ModDate", cal.getTime().toString()); info.put("CreationDate", cal.getTime().toString()); //info.put("CreationDate", "D:20120816122649+02'00'"); stamper.setMoreInfo(info); //create new page to hold signatures int pages =reader.getNumberOfPages(); size = reader.getPageSize(1); sigpage=pages+1; setPlaceHolders(numOfSignatures); stamper.close(); reader.close(); //Create a copy from modified PDF with signature placeholders PdfReader copy = new PdfReader(new ByteArrayInputStream(baos.toByteArray())); baos.reset();//Reset stream to reuse it stamper = PdfStamper.createSignature(copy, baos, '7', new File("/tmp"),false); sap = stamper.getSignatureAppearance(); sap.setVisibleSignature("sig-1"); //H proth ypografh einai gia to certificate //CERTIFIED_NO_CHANGES_ALLOWED Gia eggrafa pou den dexontai alles ypografes.TODO Na do ta locks gia thn teleutea ypografh sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS); } else{ stamper = PdfStamper.createSignature(reader, baos, '7', new File("/tmp"),true); sap = stamper.getSignatureAppearance(); // sap.setVisibleSignature(new Rectangle(0, 0, size.getWidth(), 200), sigpage, "sig1"); sap.setVisibleSignature("sig-"+(sigs+1));//TODO select based on logged user sap.setCertificationLevel(PdfSignatureAppearance.NOT_CERTIFIED); } //set Font String path = getServletContext().getRealPath(MOASSConfig.getProperty("font")); BaseFont fonty = BaseFont.createFont(path, BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED); fonty.setSubset(true); Font sapFont = new Font(fonty,8); sap.setLayer2Font(sapFont); sap.setCertificate(cer); sap.setSignDate(cal); sap.setReason(reason); sap.setLocation("Athens"); sap.setSignatureCreator(creator); sap.setContact("Municipality of Athens"); //set the dic PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED); dic.setReason(sap.getReason()); dic.setLocation(sap.getLocation()); dic.setName(creator); dic.setSignatureCreator(sap.getSignatureCreator()); dic.setContact(sap.getContact()); dic.setDate(new PdfDate(sap.getSignDate())); dic.setCert(cer.getEncoded()); sap.setCryptoDictionary(dic); HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>(); int estimatedSize =16384; exc.put(PdfName.CONTENTS, new Integer(estimatedSize * 2 + 2));// sap.preClose(exc); ExternalDigest externalDigest = new ExternalDigest() { public MessageDigest getMessageDigest(String hashAlgorithm) throws GeneralSecurityException { return DigestAlgorithms.getMessageDigest(hashAlgorithm, null); } }; PdfPKCS7 sgn = new PdfPKCS7(null, new Certificate[] { cer }, "SHA256", null, externalDigest, false); InputStream data = sap.getRangeStream(); byte hash[] = DigestAlgorithms.digest(data,externalDigest.getMessageDigest("SHA256")); byte[] aab = sgn.getAuthenticatedAttributeBytes(hash, cal, null, null, CryptoStandard.CMS); byte[] sh = MessageDigest.getInstance("SHA256", "BC").digest(aab); HttpSession session = request.getSession(true); session.setAttribute("sgn", sgn); session.setAttribute("hash", hash); session.setAttribute("cal", cal); session.setAttribute("sap", sap); session.setAttribute("baos", baos); session.setAttribute("uuid", uuid); String HASH2SIGN = new String(String.format("%064x", new java.math.BigInteger(1, sh))); response.getWriter().println("{\"HASH2SIGN\":\""+HASH2SIGN+"\"}"); } catch (DocumentException e) { throw new IOException(e); } catch (GeneralSecurityException e) { throw new IOException(e); } catch (Exception e) { System.out.println(e); //e.printStackTrace(); response.getWriter().println("{\"error\":\""+e.getMessage()+"\"}"); } } }
785_0
package gr.aueb.cf.ch2; import java.util.Scanner; // Κάνει import από την εντολή Scanner in /** * Scanner Demo. Reads two ints from * stdin (keyboard) and prints the sum */ public class ScannerApp { public static void main(String[] args) { // Δήλωση και αρχικοποίηση μεταβλητών Scanner in = new Scanner(System.in); // System in -> αντιστοιχεί το πληκτρολόγιο μέσα στο πρόγραμμα. int num1; int num2; int sum; // Εντολές System.out.println("Please insert two ints"); num1 = in.nextInt(); // η nextInt() περιμένει να δώσει ο χρήστης 2 ακεραίους num2 = in.nextInt(); // αν δεν δώσει ακέραιους, αποτυγχάνει. sum = num1 + num2; // Εκτύπωση αποτελεσμάτων. System.out.printf("Sum of %d + %d = %d", num1, num2, sum); } }
MytilinisV/codingfactorytestbed
ch2/ScannerApp.java
373
// Κάνει import από την εντολή Scanner in
line_comment
el
package gr.aueb.cf.ch2; import java.util.Scanner; // Κάνει import<SUF> /** * Scanner Demo. Reads two ints from * stdin (keyboard) and prints the sum */ public class ScannerApp { public static void main(String[] args) { // Δήλωση και αρχικοποίηση μεταβλητών Scanner in = new Scanner(System.in); // System in -> αντιστοιχεί το πληκτρολόγιο μέσα στο πρόγραμμα. int num1; int num2; int sum; // Εντολές System.out.println("Please insert two ints"); num1 = in.nextInt(); // η nextInt() περιμένει να δώσει ο χρήστης 2 ακεραίους num2 = in.nextInt(); // αν δεν δώσει ακέραιους, αποτυγχάνει. sum = num1 + num2; // Εκτύπωση αποτελεσμάτων. System.out.printf("Sum of %d + %d = %d", num1, num2, sum); } }
4441_11
public class CircularlyLinkedList <E> { // E = element private static class Node <E> { private E element; // Αναφορά στο στοιχείο στο οποίο δείχνει ο συγκεκριμένος κόμβος private Node <E> next; // Αναφορά στον αμέσως επόμενο κόμβο της λίστας public Node (E e, Node<E> n) { // constructor element = e; next = n; } public E getElement() {return element;} // Επιστρέφει το στοιχείο στο οποίο δείχνει ο συγκεκριμένος κόμβος public Node<E> getNext() {return next;} // Επιστρέφει τον επόμενο κόμβο από τον συγκεκριμένο public void setNext(Node<E> n) {next = n;} // Αλλάζει τον αμέσως επόμενο κόμβο από τον συγκεκριμένο } // Μεταβλητές αρχικοποίησης της CircularlyLinkedList // Στην συγκεκριμένη λίστα, δεν είναι αναγκαία η ύπαρξη αναφοράς στο head της λίστας // παρα μόνο στο tail καθώς μπορούμε ανά πάσα στιγμή να έχουμε πρόσβαση στο head με τον εξής τρόπο: // _head_ = tail.getNext(); [Το head είναι δηλαδή το tail.getNext()] protected Node<E> tail = null; // Κόμβος tail της λίστας (null αν είναι κενή) protected int size = 0; // Πλήθος κόμβων της λίστας, αρχικά 0 public CircularlyLinkedList() { // constructor // Δημιουργεί μία αρχικά κενή κυκλική λίστα // με tail (και head) ίσο με null και size = 0 } // Μέθοδοι public int size() {return size;} // Επιστρέφει το μέγεθος της λίστας, δηλαδή το πλήθος των κόμβων της public boolean isEmpty() {return size == 0;} // Αν η λίστα είναι άδεια, θα έχει και 0 κόμβους. Οπότε θα επιστραφεί true. public E getFirst() { // Επιστρέφει τo πρώτο στοιχείο της λίστας, χωρίς να το αφαιρέσει από αυτήν if (isEmpty()){ return null;} return tail.getNext().getElement(); // Επιστρέφει το στοιχείο στο οποίο δείχνει ο κόμβος "head" => tail.getNext() } public E getLast() { // Επιστρέφει τo τελευταίο στοιχείο της λίστας, χωρίς να το αφαιρέσει από αυτήν if (isEmpty()) {return null;} return tail.getElement(); // Επιστρέφει το στοιχείο στο οποίο δείχνει ο κόμβος tail } public void rotate() { // Πηγαίνει το πρώτο στοιχείο στο τέλος της λίστας if (tail != null) { // Αν δεν είναι άδεια tail = tail.getNext();} // το παλιό "head" γίνεται το νέο tail } public void addFirst(E e) { // Προσθέτει το στοιχείο e στην αρχή της λίστας if (isEmpty()) { tail = new Node<E>(e, null); tail.setNext(tail); // Κυκλική σύνδεση με τον εαυτό του. }else { Node<E> newest = new Node<E> (e, tail.getNext()); tail.setNext(newest); // Αλλαγή του "head" της λίστας. } size++; // Αύξηση κατά 1 του πλήθους των κόμβων του πίνακα } public void addLast(E e) { // Προσθέτει το στοιχείο e στο τέλος της λίστας. addFirst(e); // Τοποθετεί το στοιχείο στην αρχή της λίστας. rotate(); // Ο κόμβος που δείχνει στο στοιχείο e γίνεται τώρα ο tail } // (Οπότε το e "πάει" στο τέλος της λίστας) public E removeFirst() { // Αφαιρεί από την λίστα το πρώτο στοιχείο και το επιστρέφει if (isEmpty()) {return null;} // Άδεια λίστα, οπότε δεν έχει να επιστρέψει κάτι Node<E> head = tail.getNext(); // Δημιουργία προσωρινής μεταβλητής head if (head == tail) { tail =null; // Πρέπει να είναι ο μοναδικός κόμβος στη λίστα. }else {tail.setNext(head.getNext()); // Αφαιρούμε το " head " από τη λίστα } size--; // Μείωση κατά 1 του πλήθους των κόμβων του πίνακα return head.getElement(); // Επιστροφή του αφαιρούμενου στοιχείου } }
NIKOMAHOS/AUEB_Projects-Exercises
Data Structures with Java/Εργασία 1/src/CircularlyLinkedList.java
2,012
// Πλήθος κόμβων της λίστας, αρχικά 0
line_comment
el
public class CircularlyLinkedList <E> { // E = element private static class Node <E> { private E element; // Αναφορά στο στοιχείο στο οποίο δείχνει ο συγκεκριμένος κόμβος private Node <E> next; // Αναφορά στον αμέσως επόμενο κόμβο της λίστας public Node (E e, Node<E> n) { // constructor element = e; next = n; } public E getElement() {return element;} // Επιστρέφει το στοιχείο στο οποίο δείχνει ο συγκεκριμένος κόμβος public Node<E> getNext() {return next;} // Επιστρέφει τον επόμενο κόμβο από τον συγκεκριμένο public void setNext(Node<E> n) {next = n;} // Αλλάζει τον αμέσως επόμενο κόμβο από τον συγκεκριμένο } // Μεταβλητές αρχικοποίησης της CircularlyLinkedList // Στην συγκεκριμένη λίστα, δεν είναι αναγκαία η ύπαρξη αναφοράς στο head της λίστας // παρα μόνο στο tail καθώς μπορούμε ανά πάσα στιγμή να έχουμε πρόσβαση στο head με τον εξής τρόπο: // _head_ = tail.getNext(); [Το head είναι δηλαδή το tail.getNext()] protected Node<E> tail = null; // Κόμβος tail της λίστας (null αν είναι κενή) protected int size = 0; // Πλήθος κόμβων<SUF> public CircularlyLinkedList() { // constructor // Δημιουργεί μία αρχικά κενή κυκλική λίστα // με tail (και head) ίσο με null και size = 0 } // Μέθοδοι public int size() {return size;} // Επιστρέφει το μέγεθος της λίστας, δηλαδή το πλήθος των κόμβων της public boolean isEmpty() {return size == 0;} // Αν η λίστα είναι άδεια, θα έχει και 0 κόμβους. Οπότε θα επιστραφεί true. public E getFirst() { // Επιστρέφει τo πρώτο στοιχείο της λίστας, χωρίς να το αφαιρέσει από αυτήν if (isEmpty()){ return null;} return tail.getNext().getElement(); // Επιστρέφει το στοιχείο στο οποίο δείχνει ο κόμβος "head" => tail.getNext() } public E getLast() { // Επιστρέφει τo τελευταίο στοιχείο της λίστας, χωρίς να το αφαιρέσει από αυτήν if (isEmpty()) {return null;} return tail.getElement(); // Επιστρέφει το στοιχείο στο οποίο δείχνει ο κόμβος tail } public void rotate() { // Πηγαίνει το πρώτο στοιχείο στο τέλος της λίστας if (tail != null) { // Αν δεν είναι άδεια tail = tail.getNext();} // το παλιό "head" γίνεται το νέο tail } public void addFirst(E e) { // Προσθέτει το στοιχείο e στην αρχή της λίστας if (isEmpty()) { tail = new Node<E>(e, null); tail.setNext(tail); // Κυκλική σύνδεση με τον εαυτό του. }else { Node<E> newest = new Node<E> (e, tail.getNext()); tail.setNext(newest); // Αλλαγή του "head" της λίστας. } size++; // Αύξηση κατά 1 του πλήθους των κόμβων του πίνακα } public void addLast(E e) { // Προσθέτει το στοιχείο e στο τέλος της λίστας. addFirst(e); // Τοποθετεί το στοιχείο στην αρχή της λίστας. rotate(); // Ο κόμβος που δείχνει στο στοιχείο e γίνεται τώρα ο tail } // (Οπότε το e "πάει" στο τέλος της λίστας) public E removeFirst() { // Αφαιρεί από την λίστα το πρώτο στοιχείο και το επιστρέφει if (isEmpty()) {return null;} // Άδεια λίστα, οπότε δεν έχει να επιστρέψει κάτι Node<E> head = tail.getNext(); // Δημιουργία προσωρινής μεταβλητής head if (head == tail) { tail =null; // Πρέπει να είναι ο μοναδικός κόμβος στη λίστα. }else {tail.setNext(head.getNext()); // Αφαιρούμε το " head " από τη λίστα } size--; // Μείωση κατά 1 του πλήθους των κόμβων του πίνακα return head.getElement(); // Επιστροφή του αφαιρούμενου στοιχείου } }
221_1
package griniaris; import java.util.Random; import javax.swing.ImageIcon; public class Dice { Random rand = new Random(); private final int n = rand.nextInt(6) + 1; @Override public String toString() { return "Ο αριθμός είναι: " + n; } //για να μπορούμε να πάρουμε τον αριθμό του ζαριού public int getN() { return n; } //για να μπορούμε να αλλάξουμε γραφικά την εικόνα του ζαριού μας ανάλογα με το αποτέλεσμα της ρίψης public ImageIcon getDiceIcon(){ return (new ImageIcon(".\\dice" + n + ".png")); } }
NasosG/Griniaris-Ludo-Java
Griniaris/src/griniaris/Dice.java
263
//για να μπορούμε να αλλάξουμε γραφικά την εικόνα του ζαριού μας ανάλογα με το αποτέλεσμα της ρίψης
line_comment
el
package griniaris; import java.util.Random; import javax.swing.ImageIcon; public class Dice { Random rand = new Random(); private final int n = rand.nextInt(6) + 1; @Override public String toString() { return "Ο αριθμός είναι: " + n; } //για να μπορούμε να πάρουμε τον αριθμό του ζαριού public int getN() { return n; } //για να<SUF> public ImageIcon getDiceIcon(){ return (new ImageIcon(".\\dice" + n + ".png")); } }
1673_1
package project2; import static java.lang.Math.abs; /** * * @author Gthanasis */ public abstract class Board { private Piece[][] pieces = new Piece[8][8]; private final Color a = Color.WHITE; private final Color b = Color.BLACK; private Location loc; private int scorea=0,scoreb=0; private int l; public Board(){} public Board(int i) { l=i; } public int get() { return l; } public Piece getPieceAt(Location loc) { return pieces[loc.getRow()][7-loc.getCol()]; } public Piece getPieceAt(int r, int c) { return pieces[r][7-c]; } public void setPiece(Piece[][] pc) { for(int i=0;i<8;i++) for(int j=0;j<8;j++) pieces[i][7-j]=pc[i][j]; } void init() { Board br; br=new Board(1){}; for(int i=2; i<6; i++){ for(int j=0; j<8; j++){ pieces[i][j]=new Empty(i,j,a,br); } } for(int i=0; i<8; i++){ pieces[6][i]=(new Pawn(1,i,b,br)); } pieces[7][0]=(new Rook(0,0,b,br)); pieces[7][7]=(new Rook(0,7,b,br)); pieces[7][2]=(new Bishop(0, 2, b,br)); pieces[7][5]=(new Bishop(0, 5, b,br)); pieces[7][1]=(new Knight(0, 1, b,br)); pieces[7][6]=(new Knight(0, 6, b,br)); pieces[7][4]=(new Queen(0, 4, b,br)); pieces[7][3]=(new King(0, 3, b,br)); for(int i=0; i<8; i++){ pieces[1][i]=(new Pawn(6,i,a,br)); } pieces[0][0]=(new Rook(7, 0, a,br)); pieces[0][7]=(new Rook(7, 7, a,br)); pieces[0][2]=(new Bishop(7, 2, a,br)); pieces[0][5]=(new Bishop(7, 5, a,br)); pieces[0][1]=(new Knight(7, 1, a,br)); pieces[0][6]=(new Knight(7, 6, a,br)); pieces[0][4]=(new Queen(7, 4, a,br)); pieces[0][3]=(new King(7, 3, a,br)); print(); } public void print() {/*Εκτύπωση κομματιών χωρίς αποθήκευση σε στρινγκ μετά απο αυτή ακολουθεί και η συνάρτηση toString() που μπορεί να κάνει το ίδιο αλλά τα αποθηκέυει σε κατάλληλο αλφαριθμητικό*/ System.out.print(" "); for(char ch = 'a' ; ch <= 'h' ; ch++ ) System.out.print(ch); System.out.println(); for (int i=7;i>=0;i--){ System.out.print((i+1)+" "); for (int j=7;j>=0;j--){ if(pieces[i][j]!=null) if (pieces[i][j].toString().equals("r") ){ //if (pieces[i][j].c==0 ||pieces[i][j].c==7){ if (pieces[i][j].color==a) System.out.print("R"); else System.out.print("r"); } else if (pieces[i][j].toString().equals("b")){ if (pieces[i][j].color==a) System.out.print("B"); else System.out.print("b"); } else if (pieces[i][j].toString().equals("k")){ if (pieces[i][j].color==a) System.out.print("K"); else System.out.print("k"); } else if (pieces[i][j].toString().equals("q")){ if (pieces[i][j].color==a) System.out.print("Q"); else System.out.print("q"); } else if (pieces[i][j].toString().equals("n")){ if (pieces[i][j].color==a) System.out.print("N"); else System.out.print("n"); } else if (pieces[i][j].toString().equals("p")){ if (pieces[i][j].color==a) System.out.print("P"); else System.out.print("p"); } else System.out.print(" "); } System.out.print(" "+(i+1)); System.out.print(" |"); if (i==7) System.out.print(" SCORE"); else if (i==5) System.out.print(" WHITE | BLACK"); else if (i==3) System.out.printf(" %d %d", scorea, scoreb); System.out.println(); } System.out.print(" "); for(char ch = 'a' ; ch <= 'h' ; ch++ ) System.out.print(ch); System.out.println(); } @Override public String toString() { String str; str=(" "); for(char ch = 'a' ; ch <= 'h' ; ch++ ) str=str+ch; str=str+"\n"; for (int i=7;i>=0;i--){ str=str+((i+1)+" "); for (int j=7;j>=0;j--){ if(pieces[i][j]!=null) if (pieces[i][j].toString().equals("r") ){ if (pieces[i][j].color==a) str=str+"R"; else str=str+"r"; } else if (pieces[i][j].toString().equals("b")){ if (pieces[i][j].color==a) str=str+"B"; else str=str+"b"; } else if (pieces[i][j].toString().equals("k")){ if (pieces[i][j].color==a) str=str+"K"; else str=str+"k"; } else if (pieces[i][j].toString().equals("q")){ if (pieces[i][j].color==a) str=str+"Q"; else str=str+"q"; } else if (pieces[i][j].toString().equals("n")){ if (pieces[i][j].color==a) str=str+"N"; else str=str+"n"; } else if (pieces[i][j].toString().equals("p")){ if (pieces[i][j].color==a) str=str+"P"; else str=str+"p"; } else str=str+" "; } str=str+(" "+(i+1)); str=str+"\n"; } str=str+(" "); for(char ch = 'a' ; ch <= 'h' ; ch++ ) str=str+(ch); str=str+"\n"; //System.out.println(str); return str; } public void movePiece(Location from, Location to) {//kinhsh kommatiou otan h telikh thesh einai kenh int r,c,r2,c2; r=from.getRow(); c=from.getCol(); r2=to.getRow(); c2=to.getCol(); Piece temp = pieces[r][7-c]; pieces[r][7-c] = pieces[r2][7-c2]; pieces[r2][7-c2] = temp; } public void movePieceCapturing(Location from, Location to) {//kinhsh kommatiou otan h telikh thesh einai kateilhmenh apo antipalo kommati int r,c,r2,c2; r=from.getRow(); c=from.getCol(); r2=to.getRow(); c2=to.getCol(); Piece temp = pieces[r][7-c]; Board bb=temp.brd; String s = pieces[r2][7-c2].toString(); Color cl = pieces[r2][7-c2].color; pieces[r][7-c] = new Empty(r,7-c,a,bb); pieces[r2][7-c2] = temp; if(cl==a){//auxhsh antistoixou score if(s.equals("p"))scoreb++; else if(s.equals("r"))scoreb+=5; else if(s.equals("n"))scoreb+=3; else if(s.equals("b"))scoreb+=3; else if(s.equals("q"))scoreb+=9; } else{ if(s.equals("p"))scorea++; else if(s.equals("r"))scorea+=5; else if(s.equals("n"))scorea+=3; else if(s.equals("b"))scorea+=3; else if(s.equals("q"))scorea+=9; } } public boolean freeHorizontalPath(Location from, Location to) { return (to.getRow() == from.getRow()); } public int movePawn(Location from, Location to) {//kapoioi apo tous elegxous gia th kinhshs tou pioniou sthn katallhlh kateuthunsh if (freeVerticalPath(from, to)){ //if(pieces[from.getRow()][7-from.getCol()]!=null) if(pieces[from.getRow()][7-from.getCol()].color==a){ if (from.getRow()==1||from.getRow()==6){ if (abs(to.getRow()-from.getRow())>=1 && abs(to.getRow()-from.getRow())<=2){ for(int i=(to.getRow());i>(to.getRow()-abs(to.getRow()-from.getRow()));i--){ for(int j=(7-from.getCol());j>=(7-to.getCol());j--){ if (pieces[i][j].toString().equals("e")){ } else{ System.out.println("\n--There is another piece in this position\n"); return -1; } } } return 1; } } else if ((to.getRow()-from.getRow())==1){ if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else{ System.out.println("\n--There is another piece in this position\n"); return -1; } } else{ return -1; } } else { if (abs(to.getRow()-from.getRow())>=1 && abs(to.getRow()-from.getRow())<=2){ try{ for(int i=abs(from.getRow()-1);i>=abs(to.getRow());i--){ for(int j=abs(7-to.getCol());j>=abs(7-to.getCol());j--){ if (pieces[i][j].toString().equals("e")){ } else{ System.out.println("\n--There is another piece in this position\n"); return -1; } } } }catch(ArrayIndexOutOfBoundsException e){ System.out.println("\n--There is another piece in this position\n"); return -1; } return 1; } else if ((to.getRow()-from.getRow())==-1){ if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else{ System.out.println("\n--There is another piece in this position\n"); return -1; } } else{ return -1; } } } else if (freeDiagonalPath(from, to)||freeAntidiagonalPath(from, to)){ if (abs(to.getRow()-from.getRow())==1||abs(to.getCol()-from.getCol())==1){ if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2; } } } return -1; } public int moveRook(Location from, Location to) {//elegxoi gia kinhshs tou purgou ekei pou prepei if (freeVerticalPath(from, to)){ if(to.getRow()>from.getRow()){ for(int i=(to.getRow())-1;i>(to.getRow()-abs(to.getRow()-from.getRow()));i--){ for(int j=(7-from.getCol());j>=(7-to.getCol());j--){/*elegxos gia kena sta endiamesa tetragona tou komatiou kai ths telikhs theshs **afou to komati den mporei na perasei an uparxei allo komati ekei*/ if (pieces[i][j].toString().equals("e")){ } else return -1; } } if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){ return -1; } else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2; } } else{ for(int i=abs(from.getRow()-1);i>=abs(to.getRow());i--){ for(int j=abs(7-to.getCol());j>=abs(7-to.getCol());j--){ if (pieces[i][j].toString().equals("e")){ } else return -1; } } if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){ return -1; } else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2; } } return 1; } else if (freeHorizontalPath(from, to)){ if(to.getCol()>from.getCol()){ for(int i=abs(to.getRow());i>=abs(to.getRow());i--){ for(int j=(to.getCol())-1;j>(to.getCol())-abs(to.getCol()-from.getCol());j--){ /*elegxos gia kena sta endiamesa tetragona tou komatiou kai ths telikhs theshs **afou to komati den mporei na perasei an uparxei allo komati ekei*/ if (pieces[to.getRow()][7-j].toString().equals("e")){ } else return -1; } } if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){ return -1; } else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2; } } else{ for(int i=abs(to.getRow());i>=abs(to.getRow());i--){ for(int j=abs(7-(to.getCol())-1);j>(7-from.getCol());j--){ if (pieces[i][j].toString().equals("e")){ } else return -1; } } if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){ return -1; } else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2; } } return 1; } return -1; } public int moveBishop(Location from, Location to) {//kapoioi apo tous elegxous gia th kinhshs tou axiomatikou stis katallhles kateuthunseis if(to.getRow()>from.getRow()){ if (freeDiagonalPath(from, to)){ int j=(to.getCol()-1); for(int i=(to.getRow()-1);i>(to.getRow())-abs(to.getRow()-from.getRow());i--){ /*elegxos gia kena sta endiamesa tetragona tou komatiou kai ths telikhs theshs **afou to komati den mporei na perasei an uparxei allo komati ekei*/ if (j>(to.getCol())-abs(to.getCol()-from.getCol())){ if (pieces[i][7-j].toString().equals("e")){ } else return -1; } j--; } if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){ return -1; } else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2; } return 1; } else if (freeAntidiagonalPath(from, to)){ int j=abs(7-(to.getCol()+1)); for(int i=(to.getRow()-1);i>(to.getRow()-abs(to.getRow()-from.getRow()));i--){ if(j>(7-from.getCol())){ if (pieces[i][j].toString().equals("e")){ System.out.println(i+" "+j); } else return -1; } j--; } if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){ return -1; } else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2; } return 1; } else System.out.println("Bishops can only move diagonally or antidiagonally"); return -1; } else{ if (freeDiagonalPath(from, to)){ int j=(7-from.getCol()); for(int i=abs(from.getRow()-1);i>=abs(to.getRow());i--){ if(j<=abs(7-(to.getCol()))){ if (pieces[i][j].toString().equals("e")){ } else return -1; } j++; } if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){ return -1; } else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2; } return 1; } else if (freeAntidiagonalPath(from, to)){ int j=(to.getCol()-1); for(int i=(to.getRow()+1);i>(to.getRow())-abs(to.getRow()-from.getRow());i--){ if (j>(to.getCol())-abs(to.getCol()-from.getCol())){ if (pieces[i][7-j].toString().equals("e")){ } else return -1; } j--; } if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){ return -1; } else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2; } return 1; } else System.out.println("Bishops can only move diagonally or antidiagonally"); return -1; } } public int moveKnight(Location from, Location to) {// kinhsh tou ippou if (freeKnightsPath(from, to)){ /*elegxos mono an to tetragono sto opoio paei einai keno*/ if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){ //an einai idiou xromatos den mporei na paei return -1; } else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2;/*an einai diaforetikou epistrefei ton katallhlo arithmo sto knight etsi oste na kalestei h movepiececapturing apo ekei kai na 'faei'-apomakrunei to antipalo kommati*/ } } return -1; } int moveKing(Location from, Location to) {//kinhsh tou basilia if (freeVerticalPath(from, to)){ if ((to.getRow()-from.getRow())==1){ if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){ return -1; } else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2; } } } if (freeHorizontalPath(from, to)){ if (abs(7-to.getCol()-(7-from.getCol()))==1){ if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){ return -1; } else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2; } } } else if (freeDiagonalPath(from, to)||freeAntidiagonalPath(from, to)){ if (abs(to.getRow()-from.getRow())==1||abs(to.getCol()-from.getCol())==1){ if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){ return -1; } else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2; } } } return -1; } public boolean freeVerticalPath(Location from, Location to) { return (to.getCol() == from.getCol()); } public boolean freeDiagonalPath(Location from, Location to) { return (to.getRow() - from.getRow() == to.getCol() - from.getCol()); } public boolean freeAntidiagonalPath(Location from, Location to) { return (abs(to.getRow() - from.getRow()) == abs((7-to.getCol()) - (7-from.getCol()))); } public boolean freeKnightsPath(Location from, Location to) { boolean knight; knight = (to.getRow() == from.getRow() - 2 || to.getRow() == from.getRow() + 2); if (knight) knight = (to.getCol() == from.getCol() - 1 || to.getCol() == from.getCol() + 1 ); if (knight) return true; knight = (to.getRow() == from.getRow() - 1 || to.getRow() == from.getRow() + 1); if (knight) knight = (to.getCol() == from.getCol() - 2 || to.getCol() == from.getCol() + 2 ); return knight; } }
NasosG/cmd-chess-java
cmdChess/src/project2/Board.java
6,746
/*Εκτύπωση κομματιών χωρίς αποθήκευση σε στρινγκ μετά απο αυτή ακολουθεί και η συνάρτηση toString() που μπορεί να κάνει το ίδιο αλλά τα αποθηκέυει σε κατάλληλο αλφαριθμητικό*/
block_comment
el
package project2; import static java.lang.Math.abs; /** * * @author Gthanasis */ public abstract class Board { private Piece[][] pieces = new Piece[8][8]; private final Color a = Color.WHITE; private final Color b = Color.BLACK; private Location loc; private int scorea=0,scoreb=0; private int l; public Board(){} public Board(int i) { l=i; } public int get() { return l; } public Piece getPieceAt(Location loc) { return pieces[loc.getRow()][7-loc.getCol()]; } public Piece getPieceAt(int r, int c) { return pieces[r][7-c]; } public void setPiece(Piece[][] pc) { for(int i=0;i<8;i++) for(int j=0;j<8;j++) pieces[i][7-j]=pc[i][j]; } void init() { Board br; br=new Board(1){}; for(int i=2; i<6; i++){ for(int j=0; j<8; j++){ pieces[i][j]=new Empty(i,j,a,br); } } for(int i=0; i<8; i++){ pieces[6][i]=(new Pawn(1,i,b,br)); } pieces[7][0]=(new Rook(0,0,b,br)); pieces[7][7]=(new Rook(0,7,b,br)); pieces[7][2]=(new Bishop(0, 2, b,br)); pieces[7][5]=(new Bishop(0, 5, b,br)); pieces[7][1]=(new Knight(0, 1, b,br)); pieces[7][6]=(new Knight(0, 6, b,br)); pieces[7][4]=(new Queen(0, 4, b,br)); pieces[7][3]=(new King(0, 3, b,br)); for(int i=0; i<8; i++){ pieces[1][i]=(new Pawn(6,i,a,br)); } pieces[0][0]=(new Rook(7, 0, a,br)); pieces[0][7]=(new Rook(7, 7, a,br)); pieces[0][2]=(new Bishop(7, 2, a,br)); pieces[0][5]=(new Bishop(7, 5, a,br)); pieces[0][1]=(new Knight(7, 1, a,br)); pieces[0][6]=(new Knight(7, 6, a,br)); pieces[0][4]=(new Queen(7, 4, a,br)); pieces[0][3]=(new King(7, 3, a,br)); print(); } public void print() {/*Εκτύπωση κομματιών χωρίς<SUF>*/ System.out.print(" "); for(char ch = 'a' ; ch <= 'h' ; ch++ ) System.out.print(ch); System.out.println(); for (int i=7;i>=0;i--){ System.out.print((i+1)+" "); for (int j=7;j>=0;j--){ if(pieces[i][j]!=null) if (pieces[i][j].toString().equals("r") ){ //if (pieces[i][j].c==0 ||pieces[i][j].c==7){ if (pieces[i][j].color==a) System.out.print("R"); else System.out.print("r"); } else if (pieces[i][j].toString().equals("b")){ if (pieces[i][j].color==a) System.out.print("B"); else System.out.print("b"); } else if (pieces[i][j].toString().equals("k")){ if (pieces[i][j].color==a) System.out.print("K"); else System.out.print("k"); } else if (pieces[i][j].toString().equals("q")){ if (pieces[i][j].color==a) System.out.print("Q"); else System.out.print("q"); } else if (pieces[i][j].toString().equals("n")){ if (pieces[i][j].color==a) System.out.print("N"); else System.out.print("n"); } else if (pieces[i][j].toString().equals("p")){ if (pieces[i][j].color==a) System.out.print("P"); else System.out.print("p"); } else System.out.print(" "); } System.out.print(" "+(i+1)); System.out.print(" |"); if (i==7) System.out.print(" SCORE"); else if (i==5) System.out.print(" WHITE | BLACK"); else if (i==3) System.out.printf(" %d %d", scorea, scoreb); System.out.println(); } System.out.print(" "); for(char ch = 'a' ; ch <= 'h' ; ch++ ) System.out.print(ch); System.out.println(); } @Override public String toString() { String str; str=(" "); for(char ch = 'a' ; ch <= 'h' ; ch++ ) str=str+ch; str=str+"\n"; for (int i=7;i>=0;i--){ str=str+((i+1)+" "); for (int j=7;j>=0;j--){ if(pieces[i][j]!=null) if (pieces[i][j].toString().equals("r") ){ if (pieces[i][j].color==a) str=str+"R"; else str=str+"r"; } else if (pieces[i][j].toString().equals("b")){ if (pieces[i][j].color==a) str=str+"B"; else str=str+"b"; } else if (pieces[i][j].toString().equals("k")){ if (pieces[i][j].color==a) str=str+"K"; else str=str+"k"; } else if (pieces[i][j].toString().equals("q")){ if (pieces[i][j].color==a) str=str+"Q"; else str=str+"q"; } else if (pieces[i][j].toString().equals("n")){ if (pieces[i][j].color==a) str=str+"N"; else str=str+"n"; } else if (pieces[i][j].toString().equals("p")){ if (pieces[i][j].color==a) str=str+"P"; else str=str+"p"; } else str=str+" "; } str=str+(" "+(i+1)); str=str+"\n"; } str=str+(" "); for(char ch = 'a' ; ch <= 'h' ; ch++ ) str=str+(ch); str=str+"\n"; //System.out.println(str); return str; } public void movePiece(Location from, Location to) {//kinhsh kommatiou otan h telikh thesh einai kenh int r,c,r2,c2; r=from.getRow(); c=from.getCol(); r2=to.getRow(); c2=to.getCol(); Piece temp = pieces[r][7-c]; pieces[r][7-c] = pieces[r2][7-c2]; pieces[r2][7-c2] = temp; } public void movePieceCapturing(Location from, Location to) {//kinhsh kommatiou otan h telikh thesh einai kateilhmenh apo antipalo kommati int r,c,r2,c2; r=from.getRow(); c=from.getCol(); r2=to.getRow(); c2=to.getCol(); Piece temp = pieces[r][7-c]; Board bb=temp.brd; String s = pieces[r2][7-c2].toString(); Color cl = pieces[r2][7-c2].color; pieces[r][7-c] = new Empty(r,7-c,a,bb); pieces[r2][7-c2] = temp; if(cl==a){//auxhsh antistoixou score if(s.equals("p"))scoreb++; else if(s.equals("r"))scoreb+=5; else if(s.equals("n"))scoreb+=3; else if(s.equals("b"))scoreb+=3; else if(s.equals("q"))scoreb+=9; } else{ if(s.equals("p"))scorea++; else if(s.equals("r"))scorea+=5; else if(s.equals("n"))scorea+=3; else if(s.equals("b"))scorea+=3; else if(s.equals("q"))scorea+=9; } } public boolean freeHorizontalPath(Location from, Location to) { return (to.getRow() == from.getRow()); } public int movePawn(Location from, Location to) {//kapoioi apo tous elegxous gia th kinhshs tou pioniou sthn katallhlh kateuthunsh if (freeVerticalPath(from, to)){ //if(pieces[from.getRow()][7-from.getCol()]!=null) if(pieces[from.getRow()][7-from.getCol()].color==a){ if (from.getRow()==1||from.getRow()==6){ if (abs(to.getRow()-from.getRow())>=1 && abs(to.getRow()-from.getRow())<=2){ for(int i=(to.getRow());i>(to.getRow()-abs(to.getRow()-from.getRow()));i--){ for(int j=(7-from.getCol());j>=(7-to.getCol());j--){ if (pieces[i][j].toString().equals("e")){ } else{ System.out.println("\n--There is another piece in this position\n"); return -1; } } } return 1; } } else if ((to.getRow()-from.getRow())==1){ if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else{ System.out.println("\n--There is another piece in this position\n"); return -1; } } else{ return -1; } } else { if (abs(to.getRow()-from.getRow())>=1 && abs(to.getRow()-from.getRow())<=2){ try{ for(int i=abs(from.getRow()-1);i>=abs(to.getRow());i--){ for(int j=abs(7-to.getCol());j>=abs(7-to.getCol());j--){ if (pieces[i][j].toString().equals("e")){ } else{ System.out.println("\n--There is another piece in this position\n"); return -1; } } } }catch(ArrayIndexOutOfBoundsException e){ System.out.println("\n--There is another piece in this position\n"); return -1; } return 1; } else if ((to.getRow()-from.getRow())==-1){ if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else{ System.out.println("\n--There is another piece in this position\n"); return -1; } } else{ return -1; } } } else if (freeDiagonalPath(from, to)||freeAntidiagonalPath(from, to)){ if (abs(to.getRow()-from.getRow())==1||abs(to.getCol()-from.getCol())==1){ if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2; } } } return -1; } public int moveRook(Location from, Location to) {//elegxoi gia kinhshs tou purgou ekei pou prepei if (freeVerticalPath(from, to)){ if(to.getRow()>from.getRow()){ for(int i=(to.getRow())-1;i>(to.getRow()-abs(to.getRow()-from.getRow()));i--){ for(int j=(7-from.getCol());j>=(7-to.getCol());j--){/*elegxos gia kena sta endiamesa tetragona tou komatiou kai ths telikhs theshs **afou to komati den mporei na perasei an uparxei allo komati ekei*/ if (pieces[i][j].toString().equals("e")){ } else return -1; } } if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){ return -1; } else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2; } } else{ for(int i=abs(from.getRow()-1);i>=abs(to.getRow());i--){ for(int j=abs(7-to.getCol());j>=abs(7-to.getCol());j--){ if (pieces[i][j].toString().equals("e")){ } else return -1; } } if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){ return -1; } else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2; } } return 1; } else if (freeHorizontalPath(from, to)){ if(to.getCol()>from.getCol()){ for(int i=abs(to.getRow());i>=abs(to.getRow());i--){ for(int j=(to.getCol())-1;j>(to.getCol())-abs(to.getCol()-from.getCol());j--){ /*elegxos gia kena sta endiamesa tetragona tou komatiou kai ths telikhs theshs **afou to komati den mporei na perasei an uparxei allo komati ekei*/ if (pieces[to.getRow()][7-j].toString().equals("e")){ } else return -1; } } if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){ return -1; } else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2; } } else{ for(int i=abs(to.getRow());i>=abs(to.getRow());i--){ for(int j=abs(7-(to.getCol())-1);j>(7-from.getCol());j--){ if (pieces[i][j].toString().equals("e")){ } else return -1; } } if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){ return -1; } else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2; } } return 1; } return -1; } public int moveBishop(Location from, Location to) {//kapoioi apo tous elegxous gia th kinhshs tou axiomatikou stis katallhles kateuthunseis if(to.getRow()>from.getRow()){ if (freeDiagonalPath(from, to)){ int j=(to.getCol()-1); for(int i=(to.getRow()-1);i>(to.getRow())-abs(to.getRow()-from.getRow());i--){ /*elegxos gia kena sta endiamesa tetragona tou komatiou kai ths telikhs theshs **afou to komati den mporei na perasei an uparxei allo komati ekei*/ if (j>(to.getCol())-abs(to.getCol()-from.getCol())){ if (pieces[i][7-j].toString().equals("e")){ } else return -1; } j--; } if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){ return -1; } else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2; } return 1; } else if (freeAntidiagonalPath(from, to)){ int j=abs(7-(to.getCol()+1)); for(int i=(to.getRow()-1);i>(to.getRow()-abs(to.getRow()-from.getRow()));i--){ if(j>(7-from.getCol())){ if (pieces[i][j].toString().equals("e")){ System.out.println(i+" "+j); } else return -1; } j--; } if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){ return -1; } else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2; } return 1; } else System.out.println("Bishops can only move diagonally or antidiagonally"); return -1; } else{ if (freeDiagonalPath(from, to)){ int j=(7-from.getCol()); for(int i=abs(from.getRow()-1);i>=abs(to.getRow());i--){ if(j<=abs(7-(to.getCol()))){ if (pieces[i][j].toString().equals("e")){ } else return -1; } j++; } if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){ return -1; } else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2; } return 1; } else if (freeAntidiagonalPath(from, to)){ int j=(to.getCol()-1); for(int i=(to.getRow()+1);i>(to.getRow())-abs(to.getRow()-from.getRow());i--){ if (j>(to.getCol())-abs(to.getCol()-from.getCol())){ if (pieces[i][7-j].toString().equals("e")){ } else return -1; } j--; } if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){ return -1; } else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2; } return 1; } else System.out.println("Bishops can only move diagonally or antidiagonally"); return -1; } } public int moveKnight(Location from, Location to) {// kinhsh tou ippou if (freeKnightsPath(from, to)){ /*elegxos mono an to tetragono sto opoio paei einai keno*/ if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){ //an einai idiou xromatos den mporei na paei return -1; } else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2;/*an einai diaforetikou epistrefei ton katallhlo arithmo sto knight etsi oste na kalestei h movepiececapturing apo ekei kai na 'faei'-apomakrunei to antipalo kommati*/ } } return -1; } int moveKing(Location from, Location to) {//kinhsh tou basilia if (freeVerticalPath(from, to)){ if ((to.getRow()-from.getRow())==1){ if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){ return -1; } else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2; } } } if (freeHorizontalPath(from, to)){ if (abs(7-to.getCol()-(7-from.getCol()))==1){ if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){ return -1; } else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2; } } } else if (freeDiagonalPath(from, to)||freeAntidiagonalPath(from, to)){ if (abs(to.getRow()-from.getRow())==1||abs(to.getCol()-from.getCol())==1){ if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){ return 1; } else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){ return -1; } else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){ return 2; } } } return -1; } public boolean freeVerticalPath(Location from, Location to) { return (to.getCol() == from.getCol()); } public boolean freeDiagonalPath(Location from, Location to) { return (to.getRow() - from.getRow() == to.getCol() - from.getCol()); } public boolean freeAntidiagonalPath(Location from, Location to) { return (abs(to.getRow() - from.getRow()) == abs((7-to.getCol()) - (7-from.getCol()))); } public boolean freeKnightsPath(Location from, Location to) { boolean knight; knight = (to.getRow() == from.getRow() - 2 || to.getRow() == from.getRow() + 2); if (knight) knight = (to.getCol() == from.getCol() - 1 || to.getCol() == from.getCol() + 1 ); if (knight) return true; knight = (to.getRow() == from.getRow() - 1 || to.getRow() == from.getRow() + 1); if (knight) knight = (to.getCol() == from.getCol() - 2 || to.getCol() == from.getCol() + 2 ); return knight; } }
6121_1
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @WebServlet("/QuizServlet") public class QuizServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Questionnaire questionnaire = new Questionnaire(); List<String> userResponses = questionnaire.collectUserResponses(); // Κλήση του TestAPI για αποστολή απαντήσεων στο ChatGPT TestAPI testAPI = new TestAPI(); List<String> gptResponses = testAPI.getWineRecommendations(String.join(", ", userResponses)); // Ναταλία και Σοφία τροποποιήστε τα ονόματα αναλόγως --> κλήση του TestAPI για αποθήκευση των απαντήσεων στη βάση δεδομένων try { testAPI.saveResponsesToDatabase(gptResponses); } catch (Exception e) { e.printStackTrace(); // Εδώ μπορείτε να χειριστείτε τυχόν σφάλματα σύνδεσης ή αποθήκευσης στη βάση δεδομένων } // Εδώ θα προσθέσω πληροφορίες αφού πρώτα φτιάξουμε την σελίδα html για τα αποτελέσματα και την μορφή αποτελεσμάτων αφού τα πάρουμε απο το DB response.sendRedirect("quiz.html"); } }
Natalia-mtvl/GrapeVin
quizServlet.java
550
// Ναταλία και Σοφία τροποποιήστε τα ονόματα αναλόγως --> κλήση του TestAPI για αποθήκευση των απαντήσεων στη βάση δεδομένων
line_comment
el
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @WebServlet("/QuizServlet") public class QuizServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Questionnaire questionnaire = new Questionnaire(); List<String> userResponses = questionnaire.collectUserResponses(); // Κλήση του TestAPI για αποστολή απαντήσεων στο ChatGPT TestAPI testAPI = new TestAPI(); List<String> gptResponses = testAPI.getWineRecommendations(String.join(", ", userResponses)); // Ναταλία και<SUF> try { testAPI.saveResponsesToDatabase(gptResponses); } catch (Exception e) { e.printStackTrace(); // Εδώ μπορείτε να χειριστείτε τυχόν σφάλματα σύνδεσης ή αποθήκευσης στη βάση δεδομένων } // Εδώ θα προσθέσω πληροφορίες αφού πρώτα φτιάξουμε την σελίδα html για τα αποτελέσματα και την μορφή αποτελεσμάτων αφού τα πάρουμε απο το DB response.sendRedirect("quiz.html"); } }